/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ function webpackJsonpCallback(data) {
/******/ var chunkIds = data[0];
/******/ var moreModules = data[1];
/******/ var executeModules = data[2];
/******/
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, resolves = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId]) {
/******/ resolves.push(installedChunks[chunkId][0]);
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(data);
/******/
/******/ while(resolves.length) {
/******/ resolves.shift()();
/******/ }
/******/
/******/ // add entry modules from loaded chunk to deferred list
/******/ deferredModules.push.apply(deferredModules, executeModules || []);
/******/
/******/ // run deferred modules when all chunks ready
/******/ return checkDeferredModules();
/******/ };
/******/ function checkDeferredModules() {
/******/ var result;
/******/ for(var i = 0; i < deferredModules.length; i++) {
/******/ var deferredModule = deferredModules[i];
/******/ var fulfilled = true;
/******/ for(var j = 1; j < deferredModule.length; j++) {
/******/ var depId = deferredModule[j];
/******/ if(installedChunks[depId] !== 0) fulfilled = false;
/******/ }
/******/ if(fulfilled) {
/******/ deferredModules.splice(i--, 1);
/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
/******/ }
/******/ }
/******/ return result;
/******/ }
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // Promise = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 2: 0
/******/ };
/******/
/******/ var deferredModules = [];
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ jsonpArray.push = webpackJsonpCallback;
/******/ jsonpArray = jsonpArray.slice();
/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/ // add entry module to deferred list
/******/ deferredModules.push([14,0]);
/******/ // run deferred modules when ready
/******/ return checkDeferredModules();
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!***********************!*\
!*** ./src/Player.js ***!
\***********************/
/*! exports provided: Player, loadPlayer */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Player", function() { return Player; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPlayer", function() { return loadPlayer; });
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Corporation/Corporation */ 31);
/* harmony import */ var _PersonObjects_Player_PlayerObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./PersonObjects/Player/PlayerObject */ 284);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/JSONReviver */ 17);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! decimal.js */ 44);
let Player = new _PersonObjects_Player_PlayerObject__WEBPACK_IMPORTED_MODULE_1__[/* PlayerObject */ "a"]();
function loadPlayer(saveString) {
Player = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["Reviver"]);
// Parse Decimal.js objects
Player.money = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](Player.money);
if (Player.corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__[/* Corporation */ "c"]) {
Player.corporation.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](Player.corporation.funds);
Player.corporation.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](Player.corporation.revenue);
Player.corporation.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](Player.corporation.expenses);
for (var i = 0; i < Player.corporation.divisions.length; ++i) {
var ind = Player.corporation.divisions[i];
ind.lastCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](ind.lastCycleRevenue);
ind.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](ind.lastCycleExpenses);
ind.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](ind.thisCycleRevenue);
ind.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](ind.thisCycleExpenses);
}
}
}
/***/ }),
/* 1 */,
/* 2 */
/*!*********************************!*\
!*** ./src/ui/numeralFormat.ts ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const numeral = __webpack_require__(/*! numeral */ 81);
__webpack_require__(/*! numeral/locales/bg */ 664);
__webpack_require__(/*! numeral/locales/cs */ 663);
__webpack_require__(/*! numeral/locales/da-dk */ 662);
__webpack_require__(/*! numeral/locales/de */ 661);
__webpack_require__(/*! numeral/locales/en-au */ 660);
__webpack_require__(/*! numeral/locales/en-gb */ 659);
__webpack_require__(/*! numeral/locales/es */ 658);
__webpack_require__(/*! numeral/locales/fr */ 657);
__webpack_require__(/*! numeral/locales/hu */ 656);
__webpack_require__(/*! numeral/locales/it */ 655);
__webpack_require__(/*! numeral/locales/lv */ 654);
__webpack_require__(/*! numeral/locales/no */ 653);
__webpack_require__(/*! numeral/locales/pl */ 652);
__webpack_require__(/*! numeral/locales/ru */ 651);
/* eslint-disable class-methods-use-this */
class NumeralFormatter {
constructor() {
// Default Locale
this.defaultLocale = "en";
this.defaultLocale = 'en';
}
updateLocale(l) {
if (numeral.locale(l) == null) {
console.warn(`Invalid locale for numeral: ${l}`);
numeral.locale(this.defaultLocale);
return false;
}
return true;
}
format(n, format) {
// numeraljs doesnt properly format numbers that are too big or too small
if (Math.abs(n) < 1e-6) {
n = 0;
}
return numeral(n).format(format);
}
formatBigNumber(n) {
return this.format(n, "0.000a");
}
formatMoney(n) {
return this.format(n, "$0.000a");
}
formatPercentage(n, decimalPlaces = 2) {
const formatter = "0." + "0".repeat(decimalPlaces) + "%";
return this.format(n, formatter);
}
}
exports.numeralWrapper = new NumeralFormatter();
/***/ }),
/* 3 */
/*!******************************************!*\
!*** ./utils/uiHelpers/createElement.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function setElementAnchor(el, params) {
if (params.text !== undefined) {
el.text = params.text;
}
if (params.href !== undefined) {
el.href = params.href;
}
if (params.target !== undefined) {
el.target = params.target;
}
}
function setElementInput(el, params) {
if (params.name !== undefined) {
el.name = params.name;
}
if (params.value !== undefined) {
el.value = params.value;
}
if (params.type !== undefined) {
el.type = params.type;
}
if (params.checked !== undefined) {
el.checked = params.checked;
}
if (params.pattern !== undefined) {
el.pattern = params.pattern;
}
if (params.maxLength !== undefined) {
el.maxLength = params.maxLength;
}
if (params.placeholder !== undefined) {
el.placeholder = params.placeholder;
}
if (params.max !== undefined) {
el.max = params.max;
}
if (params.min !== undefined) {
el.min = params.min;
}
if (params.step !== undefined) {
el.step = params.step;
}
}
function setElementLabel(el, params) {
if (params.for !== undefined) {
el.htmlFor = params.for;
}
}
function setElementListeners(el, params) {
// tslint:disable:no-unbound-method
if (params.clickListener !== undefined) {
el.addEventListener("click", params.clickListener);
}
if (params.inputListener !== undefined) {
el.addEventListener("input", params.inputListener);
}
if (params.changeListener !== undefined) {
el.addEventListener("change", params.changeListener);
}
if (params.onkeyup !== undefined) {
el.addEventListener("keyup", params.onkeyup);
}
if (params.onkeydown !== undefined) {
el.addEventListener("keydown", params.onkeydown);
}
if (params.onfocus !== undefined) {
el.addEventListener("focus", params.onfocus);
}
// tslint:enable:no-unbound-method
}
function setElementStyle(el, params) {
if (params.display !== undefined) {
el.style.display = params.display;
}
if (params.visibility !== undefined) {
el.style.visibility = params.visibility;
}
if (params.margin !== undefined) {
el.style.margin = params.margin;
}
if (params.marginLeft !== undefined) {
el.style.marginLeft = params.marginLeft;
}
if (params.marginTop !== undefined) {
el.style.marginTop = params.marginTop;
}
if (params.padding !== undefined) {
el.style.padding = params.padding;
}
if (params.color !== undefined) {
el.style.color = params.color;
}
if (params.border !== undefined) {
el.style.border = params.border;
}
if (params.float !== undefined) {
el.style.cssFloat = params.float;
}
if (params.fontSize !== undefined) {
el.style.fontSize = params.fontSize;
}
if (params.whiteSpace !== undefined) {
el.style.whiteSpace = params.whiteSpace;
}
if (params.width !== undefined) {
el.style.width = params.width;
}
if (params.backgroundColor !== undefined) {
el.style.backgroundColor = params.backgroundColor;
}
if (params.position !== undefined) {
el.style.position = params.position;
}
if (params.overflow !== undefined) {
el.style.overflow = params.overflow;
}
}
function setElementTooltip(el, params) {
if (params.tooltip !== undefined && params.tooltip !== "") {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptext",
innerHTML: params.tooltip,
}));
}
else if (params.tooltipleft !== undefined) {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptextleft",
innerHTML: params.tooltipleft,
}));
}
else if (params.tooltipsmall !== undefined) {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptext smallfont",
innerHTML: params.tooltipsmall,
}));
}
else if (params.tooltiplow !== undefined) {
el.className += "tooltip";
el.appendChild(createElement("span", {
class: "tooltiptextlow",
innerHTML: params.tooltiplow,
}));
}
}
/**
* An all-in-one-call way of creating an element to be added to the DOM at some point.
* @param tagName The HTML tag/element name
* @param params Additional parameters to set on the element
*/
function createElement(tagName, params = {}) {
const el = document.createElement(tagName);
if (params.id !== undefined) {
el.id = params.id;
}
if (params.class !== undefined) {
el.className = params.class;
}
if (params.innerHTML !== undefined) {
el.innerHTML = params.innerHTML;
}
if (params.innerText !== undefined) {
el.innerText = params.innerText;
}
if (params.tabIndex !== undefined) {
el.tabIndex = params.tabIndex;
}
setElementAnchor(el, params);
setElementInput(el, params);
setElementLabel(el, params);
setElementListeners(el, params);
setElementStyle(el, params);
setElementTooltip(el, params);
return el;
}
exports.createElement = createElement;
/***/ }),
/* 4 */
/*!****************************************************!*\
!*** ./src/Augmentation/data/AugmentationNames.ts ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AugmentationNames = {
Targeting1: "Augmented Targeting I",
Targeting2: "Augmented Targeting II",
Targeting3: "Augmented Targeting III",
SyntheticHeart: "Synthetic Heart",
SynfibrilMuscle: "Synfibril Muscle",
CombatRib1: "Combat Rib I",
CombatRib2: "Combat Rib II",
CombatRib3: "Combat Rib III",
NanofiberWeave: "Nanofiber Weave",
SubdermalArmor: "NEMEAN Subdermal Weave",
WiredReflexes: "Wired Reflexes",
GrapheneBoneLacings: "Graphene Bone Lacings",
BionicSpine: "Bionic Spine",
GrapheneBionicSpine: "Graphene Bionic Spine Upgrade",
BionicLegs: "Bionic Legs",
GrapheneBionicLegs: "Graphene Bionic Legs Upgrade",
SpeechProcessor: "Speech Processor Implant",
TITN41Injection: "TITN-41 Gene-Modification Injection",
EnhancedSocialInteractionImplant: "Enhanced Social Interaction Implant",
BitWire: "BitWire",
ArtificialBioNeuralNetwork: "Artificial Bio-neural Network Implant",
ArtificialSynapticPotentiation: "Artificial Synaptic Potentiation",
EnhancedMyelinSheathing: "Enhanced Myelin Sheathing",
SynapticEnhancement: "Synaptic Enhancement Implant",
NeuralRetentionEnhancement: "Neural-Retention Enhancement",
DataJack: "DataJack",
ENM: "Embedded Netburner Module",
ENMCore: "Embedded Netburner Module Core Implant",
ENMCoreV2: "Embedded Netburner Module Core V2 Upgrade",
ENMCoreV3: "Embedded Netburner Module Core V3 Upgrade",
ENMAnalyzeEngine: "Embedded Netburner Module Analyze Engine",
ENMDMA: "Embedded Netburner Module Direct Memory Access Upgrade",
Neuralstimulator: "Neuralstimulator",
NeuralAccelerator: "Neural Accelerator",
CranialSignalProcessorsG1: "Cranial Signal Processors - Gen I",
CranialSignalProcessorsG2: "Cranial Signal Processors - Gen II",
CranialSignalProcessorsG3: "Cranial Signal Processors - Gen III",
CranialSignalProcessorsG4: "Cranial Signal Processors - Gen IV",
CranialSignalProcessorsG5: "Cranial Signal Processors - Gen V",
NeuronalDensification: "Neuronal Densification",
NuoptimalInjectorImplant: "Nuoptimal Nootropic Injector Implant",
SpeechEnhancement: "Speech Enhancement",
FocusWire: "FocusWire",
PCDNI: "PC Direct-Neural Interface",
PCDNIOptimizer: "PC Direct-Neural Interface Optimization Submodule",
PCDNINeuralNetwork: "PC Direct-Neural Interface NeuroNet Injector",
ADRPheromone1: "ADR-V1 Pheromone Gene",
ADRPheromone2: "ADR-V2 Pheromone Gene",
ShadowsSimulacrum: "The Shadow's Simulacrum",
HacknetNodeCPUUpload: "Hacknet Node CPU Architecture Neural-Upload",
HacknetNodeCacheUpload: "Hacknet Node Cache Architecture Neural-Upload",
HacknetNodeNICUpload: "Hacknet Node NIC Architecture Neural-Upload",
HacknetNodeKernelDNI: "Hacknet Node Kernel Direct-Neural Interface",
HacknetNodeCoreDNI: "Hacknet Node Core Direct-Neural Interface",
NeuroFluxGovernor: "NeuroFlux Governor",
Neurotrainer1: "Neurotrainer I",
Neurotrainer2: "Neurotrainer II",
Neurotrainer3: "Neurotrainer III",
Hypersight: "HyperSight Corneal Implant",
LuminCloaking1: "LuminCloaking-V1 Skin Implant",
LuminCloaking2: "LuminCloaking-V2 Skin Implant",
HemoRecirculator: "HemoRecirculator",
SmartSonar: "SmartSonar Implant",
PowerRecirculator: "Power Recirculation Core",
QLink: "QLink",
TheRedPill: "The Red Pill",
SPTN97: "SPTN-97 Gene Modification",
HiveMind: "ECorp HVMind Implant",
CordiARCReactor: "CordiARC Fusion Reactor",
SmartJaw: "SmartJaw",
Neotra: "Neotra",
Xanipher: "Xanipher",
nextSENS: "nextSENS Gene Modification",
OmniTekInfoLoad: "OmniTek InfoLoad",
PhotosyntheticCells: "Photosynthetic Cells",
Neurolink: "BitRunners Neurolink",
TheBlackHand: "The Black Hand",
CRTX42AA: "CRTX42-AA Gene Modification",
Neuregen: "Neuregen Gene Modification",
CashRoot: "CashRoot Starter Kit",
NutriGen: "NutriGen Implant",
INFRARet: "INFRARET Enhancement",
DermaForce: "DermaForce Particle Barrier",
GrapheneBrachiBlades: "Graphene BranchiBlades Upgrade",
GrapheneBionicArms: "Graphene Bionic Arms Upgrade",
BrachiBlades: "BrachiBlades",
BionicArms: "Bionic Arms",
SNA: "Social Negotiation Assistant (S.N.A)",
EsperEyewear: "EsperTech Bladeburner Eyewear",
EMS4Recombination: "EMS-4 Recombination",
OrionShoulder: "ORION-MKIV Shoulder",
HyperionV1: "Hyperion Plasma Cannon V1",
HyperionV2: "Hyperion Plasma Cannon V2",
GolemSerum: "GOLEM Serum",
VangelisVirus: "Vangelis Virus",
VangelisVirus3: "Vangelis Virus 3.0",
INTERLINKED: "I.N.T.E.R.L.I.N.K.E.D",
BladeRunner: "Blade's Runners",
BladeArmor: "BLADE-51b Tesla Armor",
BladeArmorPowerCells: "BLADE-51b Tesla Armor: Power Cells Upgrade",
BladeArmorEnergyShielding: "BLADE-51b Tesla Armor: Energy Shielding Upgrade",
BladeArmorUnibeam: "BLADE-51b Tesla Armor: Unibeam Upgrade",
BladeArmorOmnibeam: "BLADE-51b Tesla Armor: Omnibeam Upgrade",
BladeArmorIPU: "BLADE-51b Tesla Armor: IPU Upgrade",
BladesSimulacrum: "The Blade's Simulacrum",
};
/***/ }),
/* 5 */
/*!****************************************!*\
!*** ./utils/StringHelperFunctions.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __webpack_require__(/*! ./helpers/isString */ 51);
// Netburner String helper functions
// Replaces the character at an index with a new character
function replaceAt(base, index, character) {
return base.substr(0, index) + character + base.substr(index + character.length);
}
exports.replaceAt = replaceAt;
/*
Converts a date representing time in milliseconds to a string with the format H hours M minutes and S seconds
e.g. 10000 -> "10 seconds"
120000 -> "2 minutes and 0 seconds"
*/
function convertTimeMsToTimeElapsedString(time) {
const millisecondsPerSecond = 1000;
const secondPerMinute = 60;
const minutesPerHours = 60;
const secondPerHours = secondPerMinute * minutesPerHours;
const hoursPerDays = 24;
const secondPerDay = secondPerHours * hoursPerDays;
// Convert ms to seconds, since we only have second-level precision
const totalSeconds = Math.floor(time / millisecondsPerSecond);
const days = Math.floor(totalSeconds / secondPerDay);
const secTruncDays = totalSeconds % secondPerDay;
const hours = Math.floor(secTruncDays / secondPerHours);
const secTruncHours = secTruncDays % secondPerHours;
const minutes = Math.floor(secTruncHours / secondPerMinute);
const secTruncMinutes = secTruncHours % secondPerMinute;
const seconds = secTruncMinutes;
let res = "";
if (days > 0) {
res += `${days} days `;
}
if (hours > 0) {
res += `${hours} hours `;
}
if (minutes > 0) {
res += `${minutes} minutes `;
}
res += `${seconds} seconds`;
return res;
}
exports.convertTimeMsToTimeElapsedString = convertTimeMsToTimeElapsedString;
// Finds the longest common starting substring in a set of strings
function longestCommonStart(strings) {
if (!containsAllStrings(strings)) {
return "";
}
if (strings.length === 0) {
return "";
}
const A = strings.concat()
.sort();
const a1 = A[0];
const a2 = A[A.length - 1];
const L = a1.length;
let i = 0;
const areEqualCaseInsensitive = (a, b) => a.toUpperCase() === b.toUpperCase();
while (i < L && areEqualCaseInsensitive(a1.charAt(i), a2.charAt(i))) {
i++;
}
return a1.substring(0, i);
}
exports.longestCommonStart = longestCommonStart;
// Returns whether an array contains entirely of string objects
function containsAllStrings(arr) {
return arr.every(isString_1.isString);
}
exports.containsAllStrings = containsAllStrings;
// Formats a number with commas and a specific number of decimal digits
function formatNumber(num, numFractionDigits) {
return num.toLocaleString(undefined, {
maximumFractionDigits: numFractionDigits,
minimumFractionDigits: numFractionDigits,
});
}
exports.formatNumber = formatNumber;
// Checks if a string contains HTML elements
function isHTML(str) {
const element = document.createElement("div");
element.innerHTML = str;
const c = element.childNodes;
for (let i = c.length - 1; i >= 0; i--) {
if (c[i].nodeType === 1) {
return true;
}
}
return false;
}
exports.isHTML = isHTML;
// Generates a random alphanumeric string with N characters
function generateRandomString(n) {
let str = "";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < n; i++) {
str += chars.charAt(Math.floor(Math.random() * chars.length));
}
return str;
}
exports.generateRandomString = generateRandomString;
/***/ }),
/* 6 */
/*!***********************************!*\
!*** ./src/NetscriptEvaluator.js ***!
\***********************************/
/*! exports provided: killNetscriptDelay, netscriptDelay, makeRuntimeRejectMsg, resolveNetscriptRequestedThreads, getErrorLineNumber, isScriptErrorMessage */
/*! exports used: isScriptErrorMessage, killNetscriptDelay, makeRuntimeRejectMsg, netscriptDelay, resolveNetscriptRequestedThreads */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return killNetscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return netscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return makeRuntimeRejectMsg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return resolveNetscriptRequestedThreads; });
/* unused harmony export getErrorLineNumber */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isScriptErrorMessage; });
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Netscript/WorkerScript */ 102);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 68);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/acorn */ 79);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 148);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/helpers/isString */ 51);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__);
function killNetscriptDelay(workerScript) {
if (workerScript instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__["WorkerScript"]) {
if (workerScript.delay) {
clearTimeout(workerScript.delay);
workerScript.delayResolve();
}
}
}
function netscriptDelay(time, workerScript) {
return new Promise(function(resolve, reject) {
workerScript.delay = Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_2__["setTimeoutRef"])(() => {
workerScript.delay = null;
resolve();
}, time);
workerScript.delayResolve = resolve;
});
}
function makeRuntimeRejectMsg(workerScript, msg, exp=null) {
var lineNum = "";
if (exp != null) {
var num = getErrorLineNumber(exp, workerScript);
lineNum = " (Line " + num + ")"
}
return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg + lineNum;
}
function resolveNetscriptRequestedThreads(workerScript, functionName, requestedThreads) {
const threads = workerScript.scriptRef.threads;
if (!requestedThreads) {
return (isNaN(threads) || threads < 1) ? 1 : threads;
}
const requestedThreadsAsInt = requestedThreads|0;
if (isNaN(requestedThreads) || requestedThreadsAsInt < 1) {
throw makeRuntimeRejectMsg(workerScript, `Invalid thread count passed to ${functionName}: ${requestedThreads}. Threads must be a positive number.`);
}
if (requestedThreads > threads) {
throw makeRuntimeRejectMsg(workerScript, `Too many threads requested by ${functionName}. Requested: ${requestedThreads}. Has: ${threads}.`);
}
return requestedThreadsAsInt;
}
function getErrorLineNumber(exp, workerScript) {
var code = workerScript.scriptRef.codeCode();
//Split code up to the start of the node
try {
code = code.substring(0, exp.start);
return (code.match(/\n/g) || []).length + 1;
} catch(e) {
return -1;
}
}
function isScriptErrorMessage(msg) {
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__["isString"])(msg)) {return false;}
let splitMsg = msg.split("|");
if (splitMsg.length != 4){
return false;
}
var ip = splitMsg[1];
if (!Object(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4__["isValidIPAddress"])(ip)) {
return false;
}
return true;
}
/***/ }),
/* 7 */
/*!**********************************!*\
!*** ./src/ui/postToTerminal.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 91);
/**
* Adds some output to the terminal.
* @param input Text or HTML to output to the terminal
*/
function post(input) {
postContent(input);
}
exports.post = post;
function postError(input) {
postContent(`ERROR: ${input}`, { color: "#ff2929" });
}
exports.postError = postError;
/**
* Adds some output to the terminal with an identifier of "hack-progress-bar"
* @param input Text or HTML to output to the terminal
*/
function hackProgressBarPost(input) {
postContent(input, { id: "hack-progress-bar" });
}
exports.hackProgressBarPost = hackProgressBarPost;
/**
* Adds some output to the terminal with an identifier of "hack-progress"
* @param input Text or HTML to output to the terminal
*/
function hackProgressPost(input) {
postContent(input, { id: "hack-progress" });
}
exports.hackProgressPost = hackProgressPost;
function postContent(input, config = {}) {
// tslint:disable-next-line:max-line-length
const style = `color: ${config.color != null ? config.color : "var(--my-font-color)"}; background-color:var(--my-background-color);${config.id === undefined ? " white-space:pre-wrap;" : ""}`;
// tslint:disable-next-line:max-line-length
const content = `
${input}
`;
const inputElement = getElementById_1.getElementById("terminal-input");
inputElement.insertAdjacentHTML("beforebegin", content);
scrollTerminalToBottom();
}
exports.postContent = postContent;
function scrollTerminalToBottom() {
const container = getElementById_1.getElementById("terminal-container");
container.scrollTop = container.scrollHeight;
}
/***/ }),
/* 8 */
/*!**************************!*\
!*** ./src/Constants.ts ***!
\**************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CONSTANTS = {
Version: "0.46.3",
/** 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
MilliPerCycle: 200,
// How much reputation is needed to join a megacorporation's faction
CorpFactionRepRequirement: 200e3,
// Base RAM costs
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000,
// Cost to travel to another city
TravelCost: 200e3,
// Faction and Company favor-related things
BaseFavorToDonate: 150,
DonateMoneyToRepDivisor: 1e6,
FactionReputationToFavorBase: 500,
FactionReputationToFavorMult: 1.02,
CompanyReputationToFavorBase: 500,
CompanyReputationToFavorMult: 1.02,
// NeuroFlux Governor Augmentation cost multiplier
NeuroFluxGovernorLevelMult: 1.14,
NumNetscriptPorts: 20,
// Server-related constants
HomeComputerMaxRam: 1073741824,
ServerBaseGrowthRate: 1.03,
ServerMaxGrowthRate: 1.0035,
ServerFortifyAmount: 0.002,
ServerWeakenAmount: 0.05,
PurchasedServerLimit: 25,
PurchasedServerMaxRam: 1048576,
// Augmentation Constants
AugmentationCostMultiplier: 5,
AugmentationRepMultiplier: 2.5,
MultipleAugMultiplier: 1.9,
// TOR Router
TorRouterCost: 200e3,
// Infiltration
InfiltrationBribeBaseAmount: 100e3,
InfiltrationMoneyValue: 5e3,
InfiltrationRepValue: 1.4,
InfiltrationExpPow: 0.8,
// Stock market
WSEAccountCost: 200e6,
TIXAPICost: 5e9,
MarketData4SCost: 1e9,
MarketDataTixApi4SCost: 25e9,
StockMarketCommission: 100e3,
// Hospital/Health
HospitalCostPerHp: 100e3,
// Intelligence-related constants
IntelligenceCrimeWeight: 0.05,
IntelligenceInfiltrationWeight: 0.1,
IntelligenceCrimeBaseExpGain: 0.001,
IntelligenceProgramBaseExpGain: 500,
IntelligenceTerminalHackBaseExpGain: 200,
IntelligenceSingFnBaseExpGain: 0.002,
IntelligenceClassBaseExpGain: 0.000001,
IntelligenceHackingMissionBaseExpGain: 0.03,
// Hacking Missions
// TODO Move this into Hacking Mission implementation
HackingMissionRepToDiffConversion: 10000,
HackingMissionRepToRewardConversion: 7,
HackingMissionSpamTimeIncrease: 25000,
HackingMissionTransferAttackIncrease: 1.05,
HackingMissionMiscDefenseIncrease: 1.05,
HackingMissionDifficultyToHacking: 135,
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 " +
"that initially belong to neither you nor the enemy. The goal of the game is " +
"to capture all of the enemy's Database nodes within the time limit. " +
"If you fail to do this, you will lose.
" +
"Each Node has three stats: Attack, Defense, and HP. There are five different actions that " +
"a Node can take:
" +
"Attack - Targets an enemy Node and lowers its HP. The effectiveness is determined by the owner's Attack, the Player's " +
"hacking level, and the enemy's defense.
" +
"Scan - Targets an enemy Node and lowers its Defense. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the " +
"enemy's defense.
" +
"Weaken - Targets an enemy Node and lowers its Attack. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the enemy's " +
"defense.
" +
"Fortify - Raises the Node's Defense. The effectiveness is determined by your hacking level.
" +
"Overflow - Raises the Node's Attack but lowers its Defense. The effectiveness is determined by your hacking level.
" +
"Note that when determining the effectiveness of the above actions, the TOTAL Attack or Defense of the team is used, not just the " +
"Attack/Defense of the individual Node that is performing the action.
" +
"To capture a Node, you must lower its HP down to 0.
" +
"There are six different types of Nodes:
" +
"CPU Core - These are your main Nodes that are used to perform actions. Capable of performing every action
" +
"Firewall - Nodes with high defense. These Nodes can 'Fortify'
" +
"Database - A special type of Node. The player's objective is to conquer all of the enemy's Database Nodes within " +
"the time limit. These Nodes cannot perform any actions
" +
"Spam - Conquering one of these Nodes will slow the enemy's trace, giving the player additional time to complete " +
"the mission. These Nodes cannot perform any actions
" +
"Transfer - Conquering one of these nodes will increase the Attack of all of your CPU Cores by a small fixed percentage. " +
"These Nodes are capable of performing every action except the 'Attack' action
" +
"Shield - Nodes with high defense. These Nodes can 'Fortify'
" +
"To assign an action to a Node, you must first select one of your Nodes. This can be done by simply clicking on it. Double-clicking " +
"a node will select all of your Nodes of the same type (e.g. select all CPU Core Nodes or all Transfer Nodes). Note that only Nodes " +
"that can perform actions (CPU Core, Transfer, Shield, Firewall) can be selected. Selected Nodes will be denoted with a white highlight. After selecting a Node or multiple Nodes, " +
"select its action using the Action Buttons near the top of the screen. Every action also has a corresponding keyboard " +
"shortcut.
" +
"For certain actions such as attacking, scanning, and weakening, the Node performing the action must have a target. To target " +
"another node, simply click-and-drag from the 'source' Node to a target. A Node can only have one target, and you can target " +
"any Node that is adjacent to one of your Nodes (immediately above, below, or to the side. NOT diagonal). Furthermore, only CPU Cores and Transfer Nodes " +
"can target, since they are the only ones that can perform the related actions. To remove a target, you can simply click on the line that represents " +
"the connection between one of your Nodes and its target. Alternatively, you can select the 'source' Node and click the 'Drop Connection' button, " +
"or press 'd'.
" +
"Other Notes:
" +
"-Whenever a miscellenaous Node (not owned by the player or enemy) is conquered, the defense of all remaining miscellaneous Nodes that " +
"are not actively being targeted will increase by a fixed percentage.
" +
"-Whenever a Node is conquered, its stats are significantly reduced
" +
"-Miscellaneous Nodes slowly raise their defense over time
" +
"-Nodes slowly regenerate health over time.",
// Time-related constants
MillisecondsPer20Hours: 72000000,
GameCyclesPer20Hours: 72000000 / 200,
MillisecondsPer10Hours: 36000000,
GameCyclesPer10Hours: 36000000 / 200,
MillisecondsPer8Hours: 28800000,
GameCyclesPer8Hours: 28800000 / 200,
MillisecondsPer4Hours: 14400000,
GameCyclesPer4Hours: 14400000 / 200,
MillisecondsPer2Hours: 7200000,
GameCyclesPer2Hours: 7200000 / 200,
MillisecondsPerHour: 3600000,
GameCyclesPerHour: 3600000 / 200,
MillisecondsPerHalfHour: 1800000,
GameCyclesPerHalfHour: 1800000 / 200,
MillisecondsPerQuarterHour: 900000,
GameCyclesPerQuarterHour: 900000 / 200,
MillisecondsPerFiveMinutes: 300000,
GameCyclesPerFiveMinutes: 300000 / 200,
// Player Work & Action
FactionWorkHacking: "Faction Hacking Work",
FactionWorkField: "Faction Field Work",
FactionWorkSecurity: "Faction Security Work",
WorkTypeCompany: "Working for Company",
WorkTypeCompanyPartTime: "Working for Company part-time",
WorkTypeFaction: "Working for Faction",
WorkTypeCreateProgram: "Working on Create a Program",
WorkTypeStudyClass: "Studying or Taking a class at university",
WorkTypeCrime: "Committing a crime",
ClassStudyComputerScience: "studying Computer Science",
ClassDataStructures: "taking a Data Structures course",
ClassNetworks: "taking a Networks course",
ClassAlgorithms: "taking an Algorithms course",
ClassManagement: "taking a Management course",
ClassLeadership: "taking a Leadership course",
ClassGymStrength: "training your strength at a gym",
ClassGymDefense: "training your defense at a gym",
ClassGymDexterity: "training your dexterity at a gym",
ClassGymAgility: "training your agility at a gym",
ClassDataStructuresBaseCost: 40,
ClassNetworksBaseCost: 80,
ClassAlgorithmsBaseCost: 320,
ClassManagementBaseCost: 160,
ClassLeadershipBaseCost: 320,
ClassGymBaseCost: 120,
CrimeShoplift: "shoplift",
CrimeRobStore: "rob a store",
CrimeMug: "mug someone",
CrimeLarceny: "commit larceny",
CrimeDrugs: "deal drugs",
CrimeBondForgery: "forge corporate bonds",
CrimeTraffickArms: "traffick illegal arms",
CrimeHomicide: "commit homicide",
CrimeGrandTheftAuto: "commit grand theft auto",
CrimeKidnap: "kidnap someone for ransom",
CrimeAssassination: "assassinate a high-profile target",
CrimeHeist: "pull off the ultimate heist",
// Coding Contract
// TODO Move this into Coding contract impelmentation?
CodingContractBaseFactionRepGain: 2500,
CodingContractBaseCompanyRepGain: 4000,
CodingContractBaseMoneyGain: 75e6,
// BitNode/Source-File related stuff
TotalNumBitNodes: 24,
LatestUpdate: `
v0.47.0
* Stock Market changes:
** Implemented spread. Stock's now have bid and ask prices at which transactions occur
** Large transactions will now influence a stock's price and forecast
** This "influencing" can take effect in the middle of a transaction
** See documentation for more details on these changes
** Added getStockAskPrice(), getStockBidPrice() Netscript functions to the TIX API
** Added getStockPurchaseCost(), getStockSaleGain() Netscript functions to the TIX API
* Re-sleeves can no longer have the NeuroFlux Governor augmentation
** This is just a temporary patch until the mechanic gets re-worked
* Adjusted RAM costs of Netscript Singularity functions (mostly increased)
* Netscript Singularity functions no longer cost extra RAM outside of BitNode-4
* Corporation employees no longer have an "age" stat
* Bug Fix: Corporation employees stats should no longer become negative
* Bug Fix: Fixed sleeve.getInformation() throwing error in certain scenarios
* Bug Fix: Coding contracts should no longer generate on the w0r1d_d43m0n server
* Bug Fix: Duplicate Sleeves now properly have access to all Augmentations if you have a gang
* Bug Fix: getAugmentationsFromFaction() & purchaseAugmentation() functions should now work properly if you have a gang
* Bug Fix: Fixed issue that caused messages (.msg) to be sent when refreshing/reloading the game
* Bug Fix: Purchasing hash upgrades for Bladeburner/Corporation when you don't actually have access to those mechanics no longer gives hashes
* Bug Fix: run(), exec(), and spawn() Netscript functions now throw if called with 0 threads
* Bug Fix: Faction UI should now automatically update reputation
`
};
/***/ }),
/* 9 */
/*!****************************!*\
!*** ./utils/DialogBox.js ***!
\****************************/
/*! exports provided: dialogBoxCreate, dialogBoxOpened */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dialogBoxCreate", function() { return dialogBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dialogBoxOpened", function() { return dialogBoxOpened; });
/**
* Create and display a pop-up dialog box.
* This dialog box does not allow for any interaction and should close when clicking
* outside of it
*/
let dialogBoxes = [];
// Close dialog box when clicking outside
$(document).click(function(event) {
if (dialogBoxOpened && dialogBoxes.length >= 1) {
if (!$(event.target).closest(dialogBoxes[0]).length){
dialogBoxes[0].remove();
dialogBoxes.splice(0, 1);
if (dialogBoxes.length == 0) {
dialogBoxOpened = false;
} else {
dialogBoxes[0].style.visibility = "visible";
}
}
}
});
// Dialog box close buttons
$(document).on('click', '.dialog-box-close-button', function( event ) {
if (dialogBoxOpened && dialogBoxes.length >= 1) {
dialogBoxes[0].remove();
dialogBoxes.splice(0, 1);
if (dialogBoxes.length == 0) {
dialogBoxOpened = false;
} else {
dialogBoxes[0].style.visibility = "visible";
}
}
});
let dialogBoxOpened = false;
function dialogBoxCreate(txt, preformatted=false) {
console.log(`dialogBoxCreate() called`)
var container = document.createElement("div");
container.setAttribute("class", "dialog-box-container");
var content = document.createElement("div");
content.setAttribute("class", "dialog-box-content");
var closeButton = document.createElement("span");
closeButton.setAttribute("class", "dialog-box-close-button");
closeButton.innerHTML = "×"
var textE;
if (preformatted) {
// For text files as they are often computed data that
// shouldn't be wrapped and should retain tabstops.
textE = document.createElement("pre");
textE.innerHTML = txt;
} else {
textE = document.createElement("p");
textE.innerHTML = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
}
content.appendChild(closeButton);
content.appendChild(textE);
container.appendChild(content);
document.body.appendChild(container);
if (dialogBoxes.length >= 1) {
container.style.visibility = "hidden";
}
dialogBoxes.push(container);
setTimeout(function() {
dialogBoxOpened = true;
}, 400);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 10 */
/*!*******************************************!*\
!*** ./src/Netscript/RamCostGenerator.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// TODO remember to update RamCalculations.js and WorkerScript.js
// RAM costs for Netscript functions
exports.RamCostConstants = {
ScriptBaseRamCost: 1.6,
ScriptDomRamCost: 25,
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,
ScriptGetPurchasedServerMaxRam: 0.05,
ScriptRoundRamCost: 0.05,
ScriptReadWriteRamCost: 1.0,
ScriptArbScriptRamCost: 1.0,
ScriptGetScriptRamCost: 0.1,
ScriptGetHackTimeRamCost: 0.05,
ScriptGetFavorToDonate: 0.10,
ScriptCodingContractBaseRamCost: 10,
ScriptSleeveBaseRamCost: 4,
ScriptSingularityFn1RamCost: 2,
ScriptSingularityFn2RamCost: 3,
ScriptSingularityFn3RamCost: 5,
ScriptGangApiBaseRamCost: 4,
ScriptBladeburnerApiBaseRamCost: 4,
};
exports.RamCosts = {
hacknet: {
numNodes: () => 0,
purchaseNode: () => 0,
getPurchaseNodeCost: () => 0,
getNodeStats: () => 0,
upgradeLevel: () => 0,
upgradeRam: () => 0,
upgradeCore: () => 0,
upgradeCache: () => 0,
getLevelUpgradeCost: () => 0,
getRamUpgradeCost: () => 0,
getCoreUpgradeCost: () => 0,
getCacheUpgradeCost: () => 0,
numHashes: () => 0,
hashCost: () => 0,
spendHashes: () => 0,
},
sprintf: () => 0,
vsprintf: () => 0,
scan: () => exports.RamCostConstants.ScriptScanRamCost,
hack: () => exports.RamCostConstants.ScriptHackRamCost,
hackAnalyzeThreads: () => exports.RamCostConstants.ScriptHackAnalyzeRamCost,
hackAnalyzePercent: () => exports.RamCostConstants.ScriptHackAnalyzeRamCost,
hackChance: () => exports.RamCostConstants.ScriptHackAnalyzeRamCost,
sleep: () => 0,
grow: () => exports.RamCostConstants.ScriptGrowRamCost,
growthAnalyze: () => exports.RamCostConstants.ScriptGrowthAnalyzeRamCost,
weaken: () => exports.RamCostConstants.ScriptWeakenRamCost,
print: () => 0,
tprint: () => 0,
clearLog: () => 0,
disableLog: () => 0,
enableLog: () => 0,
isLogEnabled: () => 0,
getScriptLogs: () => 0,
nuke: () => exports.RamCostConstants.ScriptPortProgramRamCost,
brutessh: () => exports.RamCostConstants.ScriptPortProgramRamCost,
ftpcrack: () => exports.RamCostConstants.ScriptPortProgramRamCost,
relaysmtp: () => exports.RamCostConstants.ScriptPortProgramRamCost,
httpworm: () => exports.RamCostConstants.ScriptPortProgramRamCost,
sqlinject: () => exports.RamCostConstants.ScriptPortProgramRamCost,
run: () => exports.RamCostConstants.ScriptRunRamCost,
exec: () => exports.RamCostConstants.ScriptExecRamCost,
spawn: () => exports.RamCostConstants.ScriptSpawnRamCost,
kill: () => exports.RamCostConstants.ScriptKillRamCost,
killall: () => exports.RamCostConstants.ScriptKillRamCost,
exit: () => 0,
scp: () => exports.RamCostConstants.ScriptScpRamCost,
ls: () => exports.RamCostConstants.ScriptScanRamCost,
ps: () => exports.RamCostConstants.ScriptScanRamCost,
hasRootAccess: () => exports.RamCostConstants.ScriptHasRootAccessRamCost,
getIp: () => exports.RamCostConstants.ScriptGetHostnameRamCost,
getHostname: () => exports.RamCostConstants.ScriptGetHostnameRamCost,
getHackingLevel: () => exports.RamCostConstants.ScriptGetHackingLevelRamCost,
getHackingMultipliers: () => exports.RamCostConstants.ScriptGetMultipliersRamCost,
getHacknetMultipliers: () => exports.RamCostConstants.ScriptGetMultipliersRamCost,
getBitNodeMultipliers: () => exports.RamCostConstants.ScriptGetMultipliersRamCost,
getServerMoneyAvailable: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerSecurityLevel: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerBaseSecurityLevel: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerMinSecurityLevel: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerRequiredHackingLevel: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerMaxMoney: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerGrowth: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerNumPortsRequired: () => exports.RamCostConstants.ScriptGetServerRamCost,
getServerRam: () => exports.RamCostConstants.ScriptGetServerRamCost,
serverExists: () => exports.RamCostConstants.ScriptGetServerRamCost,
fileExists: () => exports.RamCostConstants.ScriptFileExistsRamCost,
isRunning: () => exports.RamCostConstants.ScriptIsRunningRamCost,
getStockSymbols: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockPrice: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockAskPrice: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockBidPrice: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockPosition: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockMaxShares: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockPurchaseCost: () => exports.RamCostConstants.ScriptGetStockRamCost,
getStockSaleGain: () => exports.RamCostConstants.ScriptGetStockRamCost,
buyStock: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
sellStock: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
shortStock: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
sellShort: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
placeOrder: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
cancelOrder: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
getOrders: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
getStockVolatility: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
getStockForecast: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
purchase4SMarketData: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
purchase4SMarketDataTixApi: () => exports.RamCostConstants.ScriptBuySellStockRamCost,
getPurchasedServerLimit: () => exports.RamCostConstants.ScriptGetPurchasedServerLimit,
getPurchasedServerMaxRam: () => exports.RamCostConstants.ScriptGetPurchasedServerMaxRam,
getPurchasedServerCost: () => exports.RamCostConstants.ScriptGetPurchaseServerRamCost,
purchaseServer: () => exports.RamCostConstants.ScriptPurchaseServerRamCost,
deleteServer: () => exports.RamCostConstants.ScriptPurchaseServerRamCost,
getPurchasedServers: () => exports.RamCostConstants.ScriptPurchaseServerRamCost,
write: () => exports.RamCostConstants.ScriptReadWriteRamCost,
tryWrite: () => exports.RamCostConstants.ScriptReadWriteRamCost,
read: () => exports.RamCostConstants.ScriptReadWriteRamCost,
peek: () => exports.RamCostConstants.ScriptReadWriteRamCost,
clear: () => exports.RamCostConstants.ScriptReadWriteRamCost,
getPortHandle: () => exports.RamCostConstants.ScriptReadWriteRamCost * 10,
rm: () => exports.RamCostConstants.ScriptReadWriteRamCost,
scriptRunning: () => exports.RamCostConstants.ScriptArbScriptRamCost,
scriptKill: () => exports.RamCostConstants.ScriptArbScriptRamCost,
getScriptName: () => 0,
getScriptRam: () => exports.RamCostConstants.ScriptGetScriptRamCost,
getHackTime: () => exports.RamCostConstants.ScriptGetHackTimeRamCost,
getGrowTime: () => exports.RamCostConstants.ScriptGetHackTimeRamCost,
getWeakenTime: () => exports.RamCostConstants.ScriptGetHackTimeRamCost,
getScriptIncome: () => exports.RamCostConstants.ScriptGetScriptRamCost,
getScriptExpGain: () => exports.RamCostConstants.ScriptGetScriptRamCost,
nFormat: () => 0,
getTimeSinceLastAug: () => exports.RamCostConstants.ScriptGetHackTimeRamCost,
prompt: () => 0,
wget: () => 0,
getFavorToDonate: () => exports.RamCostConstants.ScriptGetFavorToDonate,
// Singularity Functions
universityCourse: () => exports.RamCostConstants.ScriptSingularityFn1RamCost,
gymWorkout: () => exports.RamCostConstants.ScriptSingularityFn1RamCost,
travelToCity: () => exports.RamCostConstants.ScriptSingularityFn1RamCost,
purchaseTor: () => exports.RamCostConstants.ScriptSingularityFn1RamCost,
purchaseProgram: () => exports.RamCostConstants.ScriptSingularityFn1RamCost,
getStats: () => exports.RamCostConstants.ScriptSingularityFn1RamCost / 4,
getCharacterInformation: () => exports.RamCostConstants.ScriptSingularityFn1RamCost / 4,
isBusy: () => exports.RamCostConstants.ScriptSingularityFn1RamCost / 4,
stopAction: () => exports.RamCostConstants.ScriptSingularityFn1RamCost / 2,
upgradeHomeRam: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
getUpgradeHomeRamCost: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 2,
workForCompany: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
applyToCompany: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
getCompanyRep: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 3,
getCompanyFavor: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 3,
getCompanyFavorGain: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 4,
checkFactionInvitations: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
joinFaction: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
workForFaction: () => exports.RamCostConstants.ScriptSingularityFn2RamCost,
getFactionRep: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 3,
getFactionFavor: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 3,
getFactionFavorGain: () => exports.RamCostConstants.ScriptSingularityFn2RamCost / 4,
donateToFaction: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
createProgram: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
commitCrime: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getCrimeChance: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getOwnedAugmentations: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getOwnedSourceFiles: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getAugmentationsFromFaction: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getAugmentationPrereq: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
getAugmentationCost: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
purchaseAugmentation: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
installAugmentations: () => exports.RamCostConstants.ScriptSingularityFn3RamCost,
// Gang API
gang: {
getMemberNames: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 4,
getGangInformation: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getOtherGangInformation: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getMemberInformation: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
canRecruitMember: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 4,
recruitMember: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getTaskNames: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 4,
setMemberTask: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getEquipmentNames: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 4,
getEquipmentCost: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getEquipmentType: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
purchaseEquipment: () => exports.RamCostConstants.ScriptGangApiBaseRamCost,
ascendMember: () => exports.RamCostConstants.ScriptGangApiBaseRamCost,
setTerritoryWarfare: () => exports.RamCostConstants.ScriptGangApiBaseRamCost / 2,
getChanceToWinClash: () => exports.RamCostConstants.ScriptGangApiBaseRamCost,
getBonusTime: () => 0,
},
// Bladeburner API
bladeburner: {
getContractNames: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getOperationNames: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getBlackOpNames: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getBlackOpRank: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 2,
getGeneralActionNames: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getSkillNames: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
startAction: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
stopBladeburnerAction: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 2,
getCurrentAction: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost / 4,
getActionTime: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionEstimatedSuccessChance: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionRepGain: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionCountRemaining: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionMaxLevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionCurrentLevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getActionAutolevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
setActionAutolevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
setActionLevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getRank: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getSkillPoints: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getSkillLevel: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getSkillUpgradeCost: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
upgradeSkill: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getTeamSize: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
setTeamSize: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getCityEstimatedPopulation: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getCityEstimatedCommunities: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getCityChaos: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getCity: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
switchCity: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getStamina: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
joinBladeburnerFaction: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
joinBladeburnerDivision: () => exports.RamCostConstants.ScriptBladeburnerApiBaseRamCost,
getBonusTime: () => 0,
},
// Coding Contract API
codingcontract: {
attempt: () => exports.RamCostConstants.ScriptCodingContractBaseRamCost,
getContractType: () => exports.RamCostConstants.ScriptCodingContractBaseRamCost / 2,
getData: () => exports.RamCostConstants.ScriptCodingContractBaseRamCost / 2,
getDescription: () => exports.RamCostConstants.ScriptCodingContractBaseRamCost / 2,
getNumTriesRemaining: () => exports.RamCostConstants.ScriptCodingContractBaseRamCost / 2,
},
// Duplicate Sleeve API
sleeve: {
getNumSleeves: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToShockRecovery: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToSynchronize: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToCommitCrime: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToUniversityCourse: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
travel: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToCompanyWork: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToFactionWork: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
setToGymWorkout: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
getSleeveStats: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
getTask: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
getInformation: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
getSleeveAugmentations: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
getSleevePurchasableAugs: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
purchaseSleeveAug: () => exports.RamCostConstants.ScriptSleeveBaseRamCost,
},
heart: {
// Easter egg function
break: () => 0,
}
};
function getRamCost(...args) {
if (args.length === 0) {
console.warn(`No arguments passed to getRamCost()`);
return 0;
}
let curr = exports.RamCosts[args[0]];
for (let i = 1; i < args.length; ++i) {
if (curr == null) {
console.warn(`Invalid function passed to getRamCost: ${args}`);
return 0;
}
const currType = typeof curr;
if (currType === "function" || currType === "number") {
break;
}
curr = curr[args[i]];
}
const currType = typeof curr;
if (currType === "function") {
return curr();
}
if (currType === "number") {
return curr;
}
console.warn(`Unexpected type (${currType}) for value [${args}]`);
return 0;
}
exports.getRamCost = getRamCost;
/***/ }),
/* 11 */
/*!*******************************************!*\
!*** ./src/Augmentation/Augmentations.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Augmentations = {};
/***/ }),
/* 12 */
/*!**************************************!*\
!*** ./src/ui/navigationTracking.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The full-screen page the player is currently be on.
* These pages are mutually exclusive.
*/
var Page;
(function (Page) {
/**
* (Default) The terminal is where the player issues all commands, executes scripts, etc.
*/
Page["Terminal"] = "Terminal";
/**
* Displays most of the statistics about the player.
*/
Page["CharacterInfo"] = "CharacterInfo";
/**
* The console for editing Netscript files.
*/
Page["ScriptEditor"] = "ScriptEditor";
/**
* Monitor the scripts currently executing across the servers.
*/
Page["ActiveScripts"] = "ActiveScripts";
/**
* View, purchase, and upgrade Hacknet nodes.
*/
Page["HacknetNodes"] = "HacknetNodes";
/**
* The list of programs the player could potentially build.
*/
Page["CreateProgram"] = "CreateProgram";
/**
* The list of all factions, and invites, available to the player.
*/
Page["Factions"] = "Factions";
/**
* Information about a specific faction.
*/
Page["Faction"] = "Faction";
/**
* The list of installed, and yet-to-be installed, augmentations the player has purchased.
*/
Page["Augmentations"] = "Augmentations";
/**
* A collection of in-game material to learn about the game.
*/
Page["Tutorial"] = "Tutorial";
/**
* A collection of items to manipulate the state of the game. Useful for development.
*/
Page["DevMenu"] = "Dev Menu";
/**
* Visiting a location in the world
*/
Page["Location"] = "Location";
/**
* A blocking page to show the player they are currently doing some action (building a program, working, etc.).
*/
Page["workInProgress"] = "WorkInProgress";
/**
* A special screen to show the player they've reached a certain point in the game.
*/
Page["RedPill"] = "RedPill";
/**
* A special screen to show the player they've reached a certain point in the game.
*/
Page["CinematicText"] = "CinematicText";
/**
* Mini-game to infiltrate a company, gaining experience from successful progress.
*/
Page["Infiltration"] = "Infiltration";
/**
* View the in-game stock market.
*/
Page["StockMarket"] = "StockMarket";
/**
* Manage gang actions and members.
*/
Page["Gang"] = "Gang";
/**
* Perform missions for a Faction.
*/
Page["Mission"] = "Mission";
/**
* Manage a corporation.
*/
Page["Corporation"] = "Corporation";
/**
* Manage special Bladeburner activities.
*/
Page["Bladeburner"] = "Bladeburner";
/**
* Manage your Sleeves
*/
Page["Sleeves"] = "Sleeves";
/**
* Purchase Resleeves
*/
Page["Resleeves"] = "Re-sleeving";
})(Page = exports.Page || (exports.Page = {}));
/**
* This class keeps track of player navigation/routing within the game.
*/
class Routing {
constructor() {
/**
* Tracking the what page the user is currently on.
*/
this.currentPage = null;
}
/**
* Determines if the player is currently on the specified page.
* @param page The page to compare against the current state.
*/
isOn(page) {
return this.currentPage === page;
}
/**
* Routes the player to the appropriate page.
* @param page The page to navigate to.
*/
navigateTo(page) {
this.currentPage = page;
}
}
/**
* The routing instance for tracking page navigation.
*/
exports.routing = new Routing();
/***/ }),
/* 13 */
/*!*********************************!*\
!*** ./src/Faction/Factions.ts ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Initialization and manipulation of the Factions object, which stores data
* about all Factions in the game
*/
const Faction_1 = __webpack_require__(/*! ./Faction */ 71);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 251);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
exports.Factions = {};
function loadFactions(saveString) {
exports.Factions = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadFactions = loadFactions;
function AddToFactions(faction) {
const name = faction.name;
exports.Factions[name] = faction;
}
exports.AddToFactions = AddToFactions;
function factionExists(name) {
return exports.Factions.hasOwnProperty(name);
}
exports.factionExists = factionExists;
function initFactions(bitNode = 1) {
for (const name in FactionInfo_1.FactionInfos) {
resetFaction(new Faction_1.Faction(name));
}
}
exports.initFactions = initFactions;
//Resets a faction during (re-)initialization. Saves the favor in the new
//Faction object and deletes the old Faction Object from "Factions". Then
//reinserts the new Faction object
function resetFaction(newFactionObject) {
if (!(newFactionObject instanceof Faction_1.Faction)) {
throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()");
}
const factionName = newFactionObject.name;
if (factionExists(factionName)) {
newFactionObject.favor = exports.Factions[factionName].favor;
delete exports.Factions[factionName];
}
AddToFactions(newFactionObject);
}
exports.resetFaction = resetFaction;
/***/ }),
/* 14 */
/*!************************!*\
!*** ./src/engine.jsx ***!
\************************/
/*! exports provided: Engine */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; });
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/LogBox */ 119);
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ActiveScriptsUI */ 92);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Augmentation/Augmentations */ 11);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Augmentation/AugmentationHelpers */ 78);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./BitNode/BitNode */ 85);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Bladeburner */ 39);
/* harmony import */ var _ui_React_CharacterOverview__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ui/React/CharacterOverview */ 257);
/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./CinematicText */ 169);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CodingContractGenerator */ 117);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Company/CompanyPositions */ 48);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Company/Companies */ 25);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Corporation/Corporation */ 31);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _DevMenu__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./DevMenu */ 200);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Faction/Factions */ 13);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 52);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Fconf/FconfSettings */ 34);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Hacknet/HacknetHelpers */ 24);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./InteractiveTutorial */ 40);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Literature */ 129);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Locations/data/LocationNames */ 37);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Locations/ui/Root */ 174);
/* harmony import */ var _Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Message/MessageHelpers */ 70);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Missions */ 74);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./NetscriptWorker */ 42);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Prestige */ 139);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Programs/ProgramHelpers */ 153);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./RedPill */ 83);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./SaveObject */ 98);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 67);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./Server/AllServers */ 21);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./Server/Server */ 105);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_Server_Server__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./SourceFile */ 100);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 18);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 45);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./Terminal */ 73);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./PersonObjects/Sleeve/Sleeve */ 118);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./PersonObjects/Sleeve/SleeveUI */ 173);
/* harmony import */ var _PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var _PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./PersonObjects/Resleeving/ResleevingUI */ 199);
/* harmony import */ var _PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./ui/createStatusText */ 103);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var _ui_displayCharacterInfo__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./ui/displayCharacterInfo */ 255);
/* harmony import */ var _ui_displayCharacterInfo__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_ui_displayCharacterInfo__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./ui/setSettingsLabels */ 254);
/* harmony import */ var _ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./ui/MainMenu/Headers */ 253);
/* harmony import */ var _ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./ui/MainMenu/Links */ 33);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ../utils/GameOptions */ 131);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 15);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_54__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 41);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_55__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 27);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_56__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 49);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ../utils/uiHelpers/removeLoadingScreen */ 198);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_59___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_59__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_61__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! react-dom */ 64);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_62___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_62__);
/**
* Shortcuts to navigate through the game
* Alt-t - Terminal
* Alt-c - Character
* Alt-e - Script editor
* Alt-s - Active scripts
* Alt-h - Hacknet Nodes
* Alt-w - City
* Alt-j - Job
* Alt-r - Travel Agency of current city
* Alt-p - Create program
* Alt-f - Factions
* Alt-a - Augmentations
* Alt-u - Tutorial
* Alt-o - Options
*/
$(document).keydown(function (e) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].DisableHotkeys === true) {
return;
} // These hotkeys should be disabled if the player is writing scripts
try {
if (Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__[/* getCurrentEditor */ "b"])().isFocused()) {
return;
}
} catch (e) {}
if (!_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].isWorking && !_RedPill__WEBPACK_IMPORTED_MODULE_31__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_25__[/* inMission */ "c"] && !_CinematicText__WEBPACK_IMPORTED_MODULE_9__[/* cinematicTextFlag */ "a"]) {
if (e.keyCode == 84 && e.altKey) {
e.preventDefault();
Engine.loadTerminalContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].C && e.altKey) {
e.preventDefault();
Engine.loadCharacterContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].E && e.altKey) {
e.preventDefault();
Engine.loadScriptEditorContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].S && e.altKey) {
e.preventDefault();
Engine.loadActiveScriptsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].H && e.altKey) {
e.preventDefault();
Engine.loadHacknetNodesContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].W && e.altKey) {
e.preventDefault();
Engine.loadLocationContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].J && e.altKey) {
e.preventDefault();
Engine.loadJobContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].R && e.altKey) {
e.preventDefault();
Engine.loadTravelContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].P && e.altKey) {
e.preventDefault();
Engine.loadCreateProgramContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].F && e.altKey) {
// Overriden by Fconf
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Terminal) && _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_18__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
return;
}
e.preventDefault();
Engine.loadFactionsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].A && e.altKey) {
e.preventDefault();
Engine.loadAugmentationsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].U && e.altKey) {
e.preventDefault();
Engine.loadTutorialContent();
}
}
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_60__["KEY"].O && e.altKey) {
e.preventDefault();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_53__[/* gameOptionsBoxOpen */ "b"])();
}
});
const Engine = {
version: "",
Debug: true,
// Clickable objects
Clickables: {
// Main menu buttons
saveMainMenuButton: null,
deleteMainMenuButton: null
},
// Display objects
// TODO-Refactor this into its own component
Display: {
// Progress bar
progress: null,
// Display for status text (such as "Saved" or "Loaded")
statusText: null,
hacking_skill: null,
// Main menu content
terminalContent: null,
characterContent: null,
scriptEditorContent: null,
activeScriptsContent: null,
hacknetNodesContent: null,
createProgramContent: null,
factionsContent: null,
factionContent: null,
augmentationsContent: null,
tutorialContent: null,
infiltrationContent: null,
stockMarketContent: null,
locationContent: null,
workInProgressContent: null,
redPillContent: null,
cinematicTextContent: null,
missionContent: null,
// Character info
characterInfo: null
},
// Time variables (milliseconds unix epoch time)
_lastUpdate: new Date().getTime(),
_idleSpeed: 200,
// Speed (in ms) at which the main loop is updated
loadTerminalContent: function () {
Engine.hideAllContent();
Engine.Display.terminalContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Terminal);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Terminal.classList.add("active");
},
loadCharacterContent: function () {
Engine.hideAllContent();
Engine.Display.characterContent.style.display = "block";
Engine.updateCharacterInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].CharacterInfo);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Stats.classList.add("active");
},
loadScriptEditorContent: function (filename = "", code = "") {
Engine.hideAllContent();
Engine.Display.scriptEditorContent.style.display = "block";
try {
Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__[/* getCurrentEditor */ "b"])().openScript(filename, code);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(e);
}
Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__[/* updateScriptEditorContent */ "e"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].ScriptEditor);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ScriptEditor.classList.add("active");
},
loadActiveScriptsContent: function () {
Engine.hideAllContent();
Engine.Display.activeScriptsContent.style.display = "block";
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_2__[/* updateActiveScriptsItems */ "c"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].ActiveScripts);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ActiveScripts.classList.add("active");
},
loadHacknetNodesContent: function () {
Engine.hideAllContent();
Engine.Display.hacknetNodesContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].HacknetNodes);
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* renderHacknetNodesUI */ "q"])();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].HacknetNodes.classList.add("active");
},
loadCreateProgramContent: function () {
Engine.hideAllContent();
Engine.Display.createProgramContent.style.display = "block";
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_30__[/* displayCreateProgramContent */ "a"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].CreateProgram);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].CreateProgram.classList.add("active");
},
loadFactionsContent: function () {
Engine.hideAllContent();
Engine.Display.factionsContent.style.display = "block";
Engine.displayFactionsInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Factions);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Factions.classList.add("active");
},
loadFactionContent: function () {
Engine.hideAllContent();
Engine.Display.factionContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Faction);
},
loadAugmentationsContent: function () {
Engine.hideAllContent();
Engine.Display.augmentationsContent.style.display = "block";
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__[/* displayAugmentationsContent */ "c"])(Engine.Display.augmentationsContent);
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Augmentations);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Augmentations.classList.add("active");
},
loadTutorialContent: function () {
Engine.hideAllContent();
Engine.Display.tutorialContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Tutorial);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Tutorial.classList.add("active");
},
loadDevMenuContent: function () {
Engine.hideAllContent();
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_15__[/* createDevMenu */ "b"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].DevMenu);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].DevMenu.classList.add("active");
},
loadLocationContent: function (initiallyInCity = true) {
Engine.hideAllContent();
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].City.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_61___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23__["LocationRoot"], {
initiallyInCity: initiallyInCity,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadTravelContent: function () {
// Same as loadLocationContent() except first set the location to the travel agency,
// and make sure that the 'City' main menu link doesnt become 'active'
Engine.hideAllContent();
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gotoLocation(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_22__["LocationName"].TravelAgency);
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Travel.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_61___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23__["LocationRoot"], {
initiallyInCity: false,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadJobContent: function () {
// Same as loadLocationContent(), except first set the location to the job.
// Make sure that the 'City' main menu link doesnt become 'active'
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].companyName == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_52__["dialogBoxCreate"])("You do not currently have a job! You can visit various companies " + "in the city and try to find a job.");
return;
}
Engine.hideAllContent();
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gotoLocation(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].companyName);
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Job.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_61___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_23__["LocationRoot"], {
initiallyInCity: false,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadWorkInProgressContent: function () {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].WorkInProgress);
},
loadRedPillContent: function () {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.redPillContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].RedPill);
},
loadCinematicTextContent: function () {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.cinematicTextContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].CinematicText);
},
loadInfiltrationContent: function () {
Engine.hideAllContent();
Engine.Display.infiltrationContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Infiltration);
},
loadStockMarketContent: function () {
Engine.hideAllContent();
Engine.Display.stockMarketContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].StockMarket);
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__[/* displayStockMarketContent */ "e"])();
},
loadGangContent: function () {
Engine.hideAllContent();
if (document.getElementById("gang-container") || _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gang.displayGangContent(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Gang);
} else {
Engine.loadTerminalContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Terminal);
}
},
loadMissionContent: function () {
Engine.hideAllContent();
document.getElementById("mainmenu-container").style.visibility = "hidden";
document.getElementById("character-overview-wrapper").style.visibility = "hidden";
Engine.Display.missionContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Mission);
},
loadCorporationContent: function () {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
Engine.hideAllContent();
document.getElementById("character-overview-wrapper").style.visibility = "hidden";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Corporation);
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation.createUI();
}
},
loadBladeburnerContent: function () {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Bladeburner);
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner.createContent();
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(e);
}
}
},
loadSleevesContent: function () {
// This is for Duplicate Sleeves page, not Re-sleeving @ Vita Life
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Sleeves);
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43__["createSleevesPage"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(e);
}
},
loadResleevingContent: function () {
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Resleeves);
Object(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_44__["createResleevesPage"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(e);
}
},
// Helper function that hides all content
hideAllContent: function () {
Engine.Display.terminalContent.style.display = "none";
Engine.Display.characterContent.style.display = "none";
Engine.Display.scriptEditorContent.style.display = "none";
Engine.Display.activeScriptsContent.style.display = "none";
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* clearHacknetNodesUI */ "a"])();
Engine.Display.createProgramContent.style.display = "none";
Engine.Display.factionsContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.unmountComponentAtNode(Engine.Display.factionContent);
Engine.Display.factionContent.style.display = "none";
Engine.Display.augmentationsContent.style.display = "none";
Engine.Display.tutorialContent.style.display = "none";
Engine.Display.locationContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.unmountComponentAtNode(Engine.Display.locationContent);
Engine.Display.workInProgressContent.style.display = "none";
Engine.Display.redPillContent.style.display = "none";
Engine.Display.cinematicTextContent.style.display = "none";
Engine.Display.infiltrationContent.style.display = "none";
Engine.Display.stockMarketContent.style.display = "none";
Engine.Display.missionContent.style.display = "none";
if (document.getElementById("gang-container")) {
document.getElementById("gang-container").style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gang.clearUI();
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation.clearUI();
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner.clearContent();
}
Object(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_44__["clearResleevesPage"])();
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43__["clearSleevesPage"])(); // Make nav menu tabs inactive
Engine.inactivateMainMenuLinks(); // Close dev menu
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_15__[/* closeDevMenu */ "a"])();
},
// Remove 'active' css class from all main menu links
inactivateMainMenuLinks: function () {
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Terminal.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ScriptEditor.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ActiveScripts.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].CreateProgram.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Stats.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Factions.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Augmentations.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].HacknetNodes.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Sleeves.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].City.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Travel.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Job.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].StockMarket.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Bladeburner.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Corporation.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Gang.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Tutorial.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Options.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].DevMenu.classList.remove("active");
},
displayCharacterOverviewInfo: function () {
react_dom__WEBPACK_IMPORTED_MODULE_62___default.a.render(react__WEBPACK_IMPORTED_MODULE_61___default.a.createElement(_ui_React_CharacterOverview__WEBPACK_IMPORTED_MODULE_8__[/* CharacterOverviewComponent */ "a"], null), document.getElementById('character-overview-text'));
const save = document.getElementById("character-overview-save-button");
const flashClass = "flashing-button";
if (!_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].AutosaveInterval) {
save.classList.add(flashClass);
} else {
save.classList.remove(flashClass);
}
},
/// Display character info
updateCharacterInfo: function () {
Object(_ui_displayCharacterInfo__WEBPACK_IMPORTED_MODULE_46__["displayCharacterInfo"])(Engine.Display.characterInfo, _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
},
// TODO Refactor this into Faction implementation
displayFactionsInfo: function () {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_55__["removeChildrenFromElement"])(Engine.Display.factionsContent); // Factions
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("h1", {
innerText: "Factions"
}));
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("p", {
innerText: "Lists all factions you have joined"
}));
var factionsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("ul");
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("br")); // Add a button for each faction you are a member of
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factions.length; ++i) {
(function () {
var factionName = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factions[i];
factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("a", {
class: "a-link-button",
innerText: factionName,
padding: "4px",
margin: "4px",
display: "inline-block",
clickListener: () => {
Engine.loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__["displayFactionContent"])(factionName);
return false;
}
}));
factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("br"));
})(); // Immediate invocation
}
Engine.Display.factionsContent.appendChild(factionsList);
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("br")); // Invited Factions
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("h1", {
innerText: "Outstanding Faction Invitations"
}));
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("p", {
width: "70%",
innerText: "Lists factions you have been invited to, as well as " + "factions you have previously rejected. You can accept " + "these faction invitations at any time."
}));
var invitationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("ul"); // Add a button to accept for each faction you have invitiations for
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations.length; ++i) {
(function () {
var factionName = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations[i];
var item = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("li", {
padding: "6px",
margin: "6px"
});
item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("p", {
innerText: factionName,
display: "inline",
margin: "4px",
padding: "4px"
}));
item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_57__["createElement"])("a", {
innerText: "Accept Faction Invitation",
class: "a-link-button",
display: "inline",
margin: "4px",
padding: "4px",
clickListener: e => {
if (!e.isTrusted) {
return false;
}
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__["joinFaction"])(_Faction_Factions__WEBPACK_IMPORTED_MODULE_16__["Factions"][factionName]);
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations[i] == factionName || _Faction_Factions__WEBPACK_IMPORTED_MODULE_16__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations[i]].isBanned) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].factionInvitations.splice(i, 1);
i--;
}
}
Engine.displayFactionsInfo();
return false;
}
}));
invitationsList.appendChild(item);
})();
}
Engine.Display.factionsContent.appendChild(invitationsList);
},
// Main Game Loop
idleTimer: function () {
// Get time difference
var _thisUpdate = new Date().getTime();
var diff = _thisUpdate - Engine._lastUpdate;
var offset = diff % Engine._idleSpeed; // Divide this by cycle time to determine how many cycles have elapsed since last update
diff = Math.floor(diff / Engine._idleSpeed);
if (diff > 0) {
// Update the game engine by the calculated number of cycles
Engine._lastUpdate = _thisUpdate - offset;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].lastUpdate = _thisUpdate - offset;
Engine.updateGame(diff);
}
window.requestAnimationFrame(Engine.idleTimer);
},
updateGame: function (numCycles = 1) {
var time = numCycles * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode = 0;
}
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode += time; // Start Manual hack
if (_Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].actionStarted === true) {
Engine._totalActionTime = _Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].actionTime;
Engine._actionTimeLeft = _Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].actionTime;
Engine._actionInProgress = true;
Engine._actionProgressBarCount = 1;
Engine._actionProgressStr = "[ ]";
Engine._actionTimeStr = "Time left: ";
_Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].actionStarted = false;
} // Working
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].isWorking) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workForFaction(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].createProgramWork(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].takeClass(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].commitCrime(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workPartTime(numCycles);
} else {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].work(numCycles);
}
} // Update stock prices
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__[/* processStockPrices */ "j"])(numCycles);
} // Gang, if applicable
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gang.process(numCycles, _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
} // Mission
if (_Missions__WEBPACK_IMPORTED_MODULE_25__[/* inMission */ "c"] && _Missions__WEBPACK_IMPORTED_MODULE_25__[/* currMission */ "b"]) {
_Missions__WEBPACK_IMPORTED_MODULE_25__[/* currMission */ "b"].process(numCycles);
} // Corporation
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
// Stores cycles in a "buffer". Processed separately using Engine Counters
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation.storeCycles(numCycles);
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner.storeCycles(numCycles);
} // Sleeves
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_42__["Sleeve"]) {
const expForOtherSleeves = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[i].process(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"], numCycles); // This sleeve earns experience for other sleeves
if (expForOtherSleeves == null) {
continue;
}
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves.length; ++j) {
if (j === i) {
continue;
}
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[j].gainExperience(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"], expForOtherSleeves, numCycles, true);
}
}
} // Counters
Engine.decrementAllCounters(numCycles);
Engine.checkCounters(); // Manual hacks
if (Engine._actionInProgress == true) {
Engine.updateHackProgress(numCycles);
} // Update the running time of all active scripts
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* updateOnlineScriptTimes */ "h"])(numCycles); // Hacknet Nodes
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* processHacknetEarnings */ "j"])(numCycles);
},
/**
* Counters for the main event loop. Represent the number of game cycles that
* are required for something to happen. These counters are in game cycles,
* which is once every 200ms
*/
Counters: {
autoSaveCounter: 300,
updateSkillLevelsCounter: 10,
updateDisplays: 3,
updateDisplaysMed: 9,
updateDisplaysLong: 15,
updateActiveScriptsDisplay: 5,
createProgramNotifications: 10,
checkFactionInvitations: 100,
passiveFactionGrowth: 600,
messages: 150,
sCr: 1500,
mechanicProcess: 5,
// Processes certain mechanics (Corporation, Bladeburner)
contractGeneration: 3000 // Generate Coding Contracts
},
decrementAllCounters: function (numCycles = 1) {
for (var counter in Engine.Counters) {
if (Engine.Counters.hasOwnProperty(counter)) {
Engine.Counters[counter] = Engine.Counters[counter] - numCycles;
}
}
},
/**
* Checks if any counters are 0. If they are, executes whatever
* is necessary and then resets the counter
*/
checkCounters: function () {
if (Engine.Counters.autoSaveCounter <= 0) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].AutosaveInterval == null) {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].AutosaveInterval = 60;
}
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].AutosaveInterval === 0) {
Engine.Counters.autoSaveCounter = Infinity;
} else {
Engine.Counters.autoSaveCounter = _Settings_Settings__WEBPACK_IMPORTED_MODULE_36__["Settings"].AutosaveInterval * 5;
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].saveGame(indexedDb);
}
}
if (Engine.Counters.updateSkillLevelsCounter <= 0) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].updateSkillLevels();
Engine.Counters.updateSkillLevelsCounter = 10;
}
if (Engine.Counters.updateActiveScriptsDisplay <= 0) {
// Always update, but make the interval longer if the page isn't active
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_2__[/* updateActiveScriptsItems */ "c"])();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].ActiveScripts)) {
Engine.Counters.updateActiveScriptsDisplay = 5;
} else {
Engine.Counters.updateActiveScriptsDisplay = 10;
}
}
if (Engine.Counters.updateDisplays <= 0) {
Engine.displayCharacterOverviewInfo();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].HacknetNodes)) {
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* renderHacknetNodesUI */ "q"])();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].CreateProgram)) {
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_30__[/* displayCreateProgramContent */ "a"])();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Sleeves)) {
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_43__["updateSleevesPage"])();
}
if (_utils_LogBox__WEBPACK_IMPORTED_MODULE_1__[/* logBoxOpened */ "b"]) {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_1__[/* logBoxUpdateText */ "c"])();
}
Engine.Counters.updateDisplays = 3;
}
if (Engine.Counters.updateDisplaysMed <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].CharacterInfo)) {
Engine.updateCharacterInfo();
}
Engine.Counters.updateDisplaysMed = 9;
}
if (Engine.Counters.updateDisplaysLong <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Gang) && _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gang.updateGangContent();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].ScriptEditor)) {
Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__[/* updateScriptEditorContent */ "e"])();
}
Engine.Counters.updateDisplaysLong = 15;
}
if (Engine.Counters.createProgramNotifications <= 0) {
var num = Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_30__[/* getNumAvailableCreateProgram */ "b"])();
var elem = document.getElementById("create-program-notification");
if (num > 0) {
elem.innerHTML = num;
elem.setAttribute("class", "notification-on");
} else {
elem.innerHTML = "";
elem.setAttribute("class", "notification-off");
}
Engine.Counters.createProgramNotifications = 10;
}
if (Engine.Counters.checkFactionInvitations <= 0) {
var invitedFactions = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].checkForFactionInvitations();
if (invitedFactions.length > 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstFacInvRecvd === false) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstFacInvRecvd = true;
document.getElementById("factions-tab").style.display = "list-item";
document.getElementById("character-menu-header").click();
document.getElementById("character-menu-header").click();
}
var randFaction = invitedFactions[Math.floor(Math.random() * invitedFactions.length)];
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__["inviteToFaction"])(randFaction);
}
Engine.Counters.checkFactionInvitations = 100;
}
if (Engine.Counters.passiveFactionGrowth <= 0) {
var adjustedCycles = Math.floor(600 - Engine.Counters.passiveFactionGrowth);
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__["processPassiveFactionRepGain"])(adjustedCycles);
Engine.Counters.passiveFactionGrowth = 600;
}
if (Engine.Counters.messages <= 0) {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_24__[/* checkForMessagesToSend */ "b"])();
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__["AugmentationNames"].TheRedPill].owned) {
Engine.Counters.messages = 4500; // 15 minutes for Red pill message
} else {
Engine.Counters.messages = 150;
}
}
if (Engine.Counters.sCr <= 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__[/* stockMarketCycle */ "k"])();
}
Engine.Counters.sCr = 1500;
}
if (Engine.Counters.mechanicProcess <= 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation.process();
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
try {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner.process();
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])("Exception caught in Bladeburner.process(): " + e);
}
}
Engine.Counters.mechanicProcess = 5;
}
if (Engine.Counters.contractGeneration <= 0) {
// X% chance of a contract being generated
if (Math.random() <= 0.25) {
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_10__[/* generateRandomContract */ "b"])();
}
Engine.Counters.contractGeneration = 3000;
}
},
// Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly
// TODO Refactor this into Terminal module
_totalActionTime: 0,
_actionTimeLeft: 0,
_actionTimeStr: "Time left: ",
_actionProgressStr: "[ ]",
_actionProgressBarCount: 1,
_actionInProgress: false,
updateHackProgress: function (numCycles = 1) {
var timeElapsedMilli = numCycles * Engine._idleSpeed;
Engine._actionTimeLeft -= timeElapsedMilli / 1000; // Substract idle speed (ms)
Engine._actionTimeLeft = Math.max(Engine._actionTimeLeft, 0); // Calculate percent filled
var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100); // Update progress bar
while (Engine._actionProgressBarCount * 2 <= percent) {
Engine._actionProgressStr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["replaceAt"])(Engine._actionProgressStr, Engine._actionProgressBarCount, "|");
Engine._actionProgressBarCount += 1;
} // Update hack time remaining
Engine._actionTimeStr = "Time left: " + Math.max(0, Math.round(Engine._actionTimeLeft)).toString() + "s";
document.getElementById("hack-progress").innerHTML = Engine._actionTimeStr; // Dynamically update progress bar
document.getElementById("hack-progress-bar").innerHTML = Engine._actionProgressStr.replace(/ /g, " "); // Once percent is 100, the hack is completed
if (percent >= 100) {
Engine._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].finishAction();
}
},
/**
* Collapses a main menu header. Used when initializing the game.
* @param elems {HTMLElement[]} Elements under header
*/
closeMainMenuHeader: function (elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = null;
elems[i].style.opacity = 0;
elems[i].style.pointerEvents = "none";
}
},
/**
* Expands a main menu header. Used when initializing the game.
* @param elems {HTMLElement[]} Elements under header
*/
openMainMenuHeader: function (elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = elems[i].scrollHeight + "px";
elems[i].style.display = "block";
}
},
/**
* Used in game when clicking on a main menu header (NOT used for initialization)
* @param open {boolean} Whether header is being opened or closed
* @param elems {HTMLElement[]} li Elements under header
* @param links {HTMLElement[]} a elements under header
*/
toggleMainMenuHeader: function (open, elems, links) {
for (var i = 0; i < elems.length; ++i) {
if (open) {
elems[i].style.opacity = 1;
elems[i].style.maxHeight = elems[i].scrollHeight + "px";
} else {
elems[i].style.opacity = 0;
elems[i].style.maxHeight = null;
}
}
for (var i = 0; i < links.length; ++i) {
if (open) {
links[i].style.opacity = 1;
links[i].style.maxHeight = links[i].scrollHeight + "px";
links[i].style.pointerEvents = "auto";
} else {
links[i].style.opacity = 0;
links[i].style.maxHeight = null;
links[i].style.pointerEvents = "none";
}
}
},
load: function (saveString) {
// Initialize main menu accordion panels to all start as "open"
const terminal = document.getElementById("terminal-tab");
const createScript = document.getElementById("create-script-tab");
const activeScripts = document.getElementById("active-scripts-tab");
const createProgram = document.getElementById("create-program-tab");
const stats = document.getElementById("stats-tab");
const factions = document.getElementById("factions-tab");
const augmentations = document.getElementById("augmentations-tab");
const hacknetnodes = document.getElementById("hacknet-nodes-tab");
const city = document.getElementById("city-tab");
const travel = document.getElementById("travel-tab");
const job = document.getElementById("job-tab");
const stockmarket = document.getElementById("stock-market-tab");
const bladeburner = document.getElementById("bladeburner-tab");
const corp = document.getElementById("corporation-tab");
const gang = document.getElementById("gang-tab");
const tutorial = document.getElementById("tutorial-tab");
const options = document.getElementById("options-tab");
const dev = document.getElementById("dev-tab"); // Load game from save or create new game
if (Object(_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* loadGame */ "a"])(saveString)) {
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__["initBitNodes"])();
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
Object(_SourceFile__WEBPACK_IMPORTED_MODULE_37__[/* initSourceFiles */ "c"])();
Engine.setDisplayElements(); // Sets variables for important DOM elements
Engine.init(); // Initialize buttons, work, etc.
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__[/* initAugmentations */ "d"])(); // Also calls Player.reapplyAllAugmentations()
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].reapplyAllSourceFiles();
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__[/* initSymbolToStockMap */ "g"])();
}
Object(_Literature__WEBPACK_IMPORTED_MODULE_21__[/* initLiterature */ "a"])();
Object(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__["updateSourceFileFlags"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]); // Calculate the number of cycles have elapsed while offline
Engine._lastUpdate = new Date().getTime();
var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].lastUpdate;
var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed); // Process offline progress
var offlineProductionFromScripts = Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* loadAllRunningScripts */ "d"])(); // This also takes care of offline production for those scripts
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].isWorking) {
console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds");
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workForFaction(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].createProgramWork(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].takeClass(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].commitCrime(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workPartTime(numCyclesOffline);
} else {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].work(numCyclesOffline);
}
} // Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* processHacknetEarnings */ "j"])(numCyclesOffline);
const hacknetProdInfo = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_19__[/* hasHacknetServers */ "h"])() ? `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48__["numeralWrapper"].format(offlineProductionFromHacknetNodes, "0.000a")} hashes` : `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48__["numeralWrapper"].formatMoney(offlineProductionFromHacknetNodes)}`; // Passive faction rep gain offline
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_17__["processPassiveFactionRepGain"])(numCyclesOffline); // Stock Market offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__[/* processStockPrices */ "j"])(numCyclesOffline);
} // Gang progress for BitNode 2
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].gang.process(numCyclesOffline, _Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
} // Corporation offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation.storeCycles(numCyclesOffline);
} // Bladeburner offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner.storeCycles(numCyclesOffline);
} // Sleeves offline progress
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_42__["Sleeve"]) {
const expForOtherSleeves = _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[i].process(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"], numCyclesOffline); // This sleeve earns experience for other sleeves
if (expForOtherSleeves == null) {
continue;
}
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves.length; ++j) {
if (j === i) {
continue;
}
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].sleeves[j].gainExperience(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"], expForOtherSleeves, numCyclesOffline, true);
}
}
} // Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode == null) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode = 0;
}
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].playtimeSinceLastBitnode += time;
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].lastUpdate = Engine._lastUpdate;
Engine.start(); // Run main game loop and Scripts loop
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_59__["removeLoadingScreen"])();
const timeOfflineString = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["convertTimeMsToTimeElapsedString"])(time);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_52__["dialogBoxCreate"])(`Offline for ${timeOfflineString}. While you were offline, your scripts ` + "generated " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_48__["numeralWrapper"].formatMoney(offlineProductionFromScripts) + " " + "and your Hacknet Nodes generated " + hacknetProdInfo + ""); // Close main menu accordions for loaded game
var visibleMenuTabs = [terminal, createScript, activeScripts, stats, hacknetnodes, city, tutorial, options, dev];
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstFacInvRecvd) {
visibleMenuTabs.push(factions);
} else {
factions.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstAugPurchased) {
visibleMenuTabs.push(augmentations);
} else {
augmentations.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].companyName !== "") {
visibleMenuTabs.push(job);
} else {
job.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstTimeTraveled) {
visibleMenuTabs.push(travel);
} else {
travel.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].firstProgramAvailable) {
visibleMenuTabs.push(createProgram);
} else {
createProgram.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].hasWseAccount) {
visibleMenuTabs.push(stockmarket);
} else {
stockmarket.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_7__[/* Bladeburner */ "a"]) {
visibleMenuTabs.push(bladeburner);
} else {
bladeburner.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_13__[/* Corporation */ "c"]) {
visibleMenuTabs.push(corp);
} else {
corp.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].inGang()) {
visibleMenuTabs.push(gang);
} else {
gang.style.display = "none";
}
Engine.closeMainMenuHeader(visibleMenuTabs);
} else {
// No save found, start new game
console.log("Initializing new game");
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__["initBitNodes"])();
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_6__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"]);
Object(_SourceFile__WEBPACK_IMPORTED_MODULE_37__[/* initSourceFiles */ "c"])();
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__["initSpecialServerIps"])();
Engine.setDisplayElements(); // Sets variables for important DOM elements
Engine.start(); // Run main game loop and Scripts loop
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].init();
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_34__["initForeignServers"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].getHomeComputer());
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_12__["initCompanies"])();
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_16__["initFactions"])();
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__[/* initAugmentations */ "d"])();
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_24__[/* initMessages */ "c"])();
Object(_Literature__WEBPACK_IMPORTED_MODULE_21__[/* initLiterature */ "a"])(); // Open main menu accordions for new game
const hackingHdr = document.getElementById("hacking-menu-header");
hackingHdr.classList.toggle("opened");
const characterHdr = document.getElementById("character-menu-header");
characterHdr.classList.toggle("opened");
const worldHdr = document.getElementById("world-menu-header");
worldHdr.classList.toggle("opened");
const helpHdr = document.getElementById("help-menu-header");
helpHdr.classList.toggle("opened"); // Hide tabs that wont be revealed until later
factions.style.display = "none";
augmentations.style.display = "none";
job.style.display = "none";
stockmarket.style.display = "none";
travel.style.display = "none";
createProgram.style.display = "none";
bladeburner.style.display = "none";
corp.style.display = "none";
gang.style.display = "none";
dev.style.display = "none";
Engine.openMainMenuHeader([terminal, createScript, activeScripts, stats, hacknetnodes, city, tutorial, options]); // Start interactive tutorial
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_20__[/* iTutorialStart */ "c"])();
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_59__["removeLoadingScreen"])();
} // Initialize labels on game settings
Object(_ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_49__[/* setSettingsLabels */ "a"])();
Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_33__[/* scriptEditorInit */ "d"])();
_Terminal__WEBPACK_IMPORTED_MODULE_41__[/* Terminal */ "a"].resetTerminalInput();
},
setDisplayElements: function () {
// Content elements
Engine.Display.terminalContent = document.getElementById("terminal-container");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_47__["Page"].Terminal);
Engine.Display.characterContent = document.getElementById("character-container");
Engine.Display.characterContent.style.display = "none";
Engine.Display.scriptEditorContent = document.getElementById("script-editor-container");
Engine.Display.scriptEditorContent.style.display = "none";
Engine.Display.activeScriptsContent = document.getElementById("active-scripts-container");
Engine.Display.activeScriptsContent.style.display = "none";
Engine.Display.hacknetNodesContent = document.getElementById("hacknet-nodes-container");
Engine.Display.hacknetNodesContent.style.display = "none";
Engine.Display.createProgramContent = document.getElementById("create-program-container");
Engine.Display.createProgramContent.style.display = "none";
Engine.Display.factionsContent = document.getElementById("factions-container");
Engine.Display.factionsContent.style.display = "none";
Engine.Display.factionContent = document.getElementById("faction-container");
Engine.Display.factionContent.style.display = "none";
Engine.Display.augmentationsContent = document.getElementById("augmentations-container");
Engine.Display.augmentationsContent.style.display = "none";
Engine.Display.tutorialContent = document.getElementById("tutorial-container");
Engine.Display.tutorialContent.style.display = "none";
Engine.Display.infiltrationContent = document.getElementById("infiltration-container");
Engine.Display.infiltrationContent.style.display = "none";
Engine.Display.stockMarketContent = document.getElementById("stock-market-container");
Engine.Display.stockMarketContent.style.display = "none";
Engine.Display.missionContent = document.getElementById("mission-container");
Engine.Display.missionContent.style.display = "none"; // Character info
Engine.Display.characterInfo = document.getElementById("character-content"); // Location page (page that shows up when you visit a specific location in World)
Engine.Display.locationContent = document.getElementById("location-container");
Engine.Display.locationContent.style.display = "none"; // Work In Progress
Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container");
Engine.Display.workInProgressContent.style.display = "none"; // Red Pill / Hack World Daemon
Engine.Display.redPillContent = document.getElementById("red-pill-container");
Engine.Display.redPillContent.style.display = "none"; // Cinematic Text
Engine.Display.cinematicTextContent = document.getElementById("cinematic-text-container");
Engine.Display.cinematicTextContent.style.display = "none"; // Initialize references to main menu links
if (!Object(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["initializeMainMenuLinks"])()) {
const errorMsg = "Failed to initialize Main Menu Links. Please try refreshing the page. " + "If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
},
// Initialization
init: function () {
// Import game link
document.getElementById("import-game-link").onclick = function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].importGame();
}; // Initialize Main Menu Headers (this must be done after initializing the links)
if (!Object(_ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_50__["initializeMainMenuHeaders"])(_Player__WEBPACK_IMPORTED_MODULE_27__["Player"], "development" === "development")) {
const errorMsg = "Failed to initialize Main Menu Headers. Please try refreshing the page. " + "If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_58__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Terminal.addEventListener("click", function () {
Engine.loadTerminalContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ScriptEditor.addEventListener("click", function () {
Engine.loadScriptEditorContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].ActiveScripts.addEventListener("click", function () {
Engine.loadActiveScriptsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].CreateProgram.addEventListener("click", function () {
Engine.loadCreateProgramContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Stats.addEventListener("click", function () {
Engine.loadCharacterContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Factions.addEventListener("click", function () {
Engine.loadFactionsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Augmentations.addEventListener("click", function () {
Engine.loadAugmentationsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].HacknetNodes.addEventListener("click", function () {
Engine.loadHacknetNodesContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Sleeves.addEventListener("click", function () {
Engine.loadSleevesContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Sleeves.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].City.addEventListener("click", function () {
Engine.loadLocationContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Travel.addEventListener("click", function () {
Engine.loadTravelContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Job.addEventListener("click", function () {
Engine.loadJobContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].StockMarket.addEventListener("click", function () {
Engine.loadStockMarketContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].StockMarket.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Bladeburner.addEventListener("click", function () {
Engine.loadBladeburnerContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Corporation.addEventListener("click", function () {
Engine.loadCorporationContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Corporation.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Gang.addEventListener("click", function () {
Engine.loadGangContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].Tutorial.addEventListener("click", function () {
Engine.loadTutorialContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_51__["MainMenuLinks"].DevMenu.addEventListener("click", function () {
if (true) {
Engine.loadDevMenuContent();
}
return false;
}); // Active scripts list
Engine.ActiveScriptsList = document.getElementById("active-scripts-list"); // Save, Delete, Import/Export buttons
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].saveGame(indexedDb);
return false;
});
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].deleteGame(indexedDb);
return false;
});
document.getElementById("export-game-link").addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].exportGame();
return false;
}); // Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].saveGame(indexedDb);
return false;
});
document.getElementById("character-overview-options-button").addEventListener("click", function () {
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_53__[/* gameOptionsBoxOpen */ "b"])();
return false;
}); // Create Program buttons
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_30__[/* initCreateProgramButtons */ "c"])(); // Message at the top of terminal
Object(_Terminal__WEBPACK_IMPORTED_MODULE_41__[/* postNetburnerText */ "b"])(); // Player was working cancel button
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].isWorking) {
var cancelButton = document.getElementById("work-in-progress-cancel-button");
cancelButton.addEventListener("click", function () {
if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeFaction) {
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_16__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].currentWorkFactionName];
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishFactionWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishCreateProgramWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishClass();
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishCrime(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_14__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishWorkPartTime();
} else {
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].finishWork(true);
}
});
Engine.loadWorkInProgressContent();
} // Character overview screen
document.getElementById("character-overview-container").style.display = "block"; // Remove classes from links (they might be set from tutorial)
document.getElementById("terminal-menu-link").removeAttribute("class");
document.getElementById("stats-menu-link").removeAttribute("class");
document.getElementById("create-script-menu-link").removeAttribute("class");
document.getElementById("active-scripts-menu-link").removeAttribute("class");
document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
document.getElementById("city-menu-link").removeAttribute("class");
document.getElementById("tutorial-menu-link").removeAttribute("class"); // Copy Save Data to Clipboard
document.getElementById("copy-save-to-clipboard-link").addEventListener("click", function () {
const saveString = _SaveObject__WEBPACK_IMPORTED_MODULE_32__[/* saveObject */ "b"].getSaveString();
if (!navigator.clipboard) {
// Async Clipboard API not supported, so we'll use this using the
// textarea and document.execCommand('copy') trick
const textArea = document.createElement("textarea");
textArea.value = saveString;
textArea.setAttribute("readonly", '');
textArea.style.position = 'absolute';
textArea.left = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand("copy");
if (successful) {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__["createStatusText"])("Copied save to clipboard");
} else {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__["createStatusText"])("Failed to copy save");
}
} catch (e) {
console.error("Unable to copy save data to clipboard using document.execCommand('copy')");
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__["createStatusText"])("Failed to copy save");
}
document.body.removeChild(textArea);
} else {
// Use the Async Clipboard API
navigator.clipboard.writeText(saveString).then(function () {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__["createStatusText"])("Copied save to clipboard");
}, function (e) {
console.error("Unable to copy save data to clipboard using Async API");
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_45__["createStatusText"])("Failed to copy save");
});
}
}); // DEBUG Delete active Scripts on home
document.getElementById("debug-delete-scripts-link").addEventListener("click", function () {
console.log("Deleting running scripts on home computer");
_Player__WEBPACK_IMPORTED_MODULE_27__["Player"].getHomeComputer().runningScripts = [];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_52__["dialogBoxCreate"])("Forcefully deleted all running scripts on home computer. Please save and refresh page");
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_53__[/* gameOptionsBoxClose */ "a"])();
return false;
}); // DEBUG Soft Reset
document.getElementById("debug-soft-reset").addEventListener("click", function () {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_52__["dialogBoxCreate"])("Soft Reset!");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_28__[/* prestigeAugmentation */ "a"])();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_53__[/* gameOptionsBoxClose */ "a"])();
return false;
});
},
start: function () {
// Run main loop
Engine.idleTimer(); // Script-processing loop
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* runScriptsLoop */ "g"])();
}
};
var indexedDb, indexedDbRequest;
window.onload = function () {
if (!window.indexedDB) {
return Engine.load(null); // Will try to load from localstorage
}
/**
* DB is called bitburnerSave
* Object store is called savestring
* key for the Object store is called save
*/
indexedDbRequest = window.indexedDB.open("bitburnerSave", 1);
indexedDbRequest.onerror = function (e) {
console.log("Error opening indexedDB: ");
console.log(e);
return Engine.load(null); // Try to load from localstorage
};
indexedDbRequest.onsuccess = function (e) {
console.log("Opening bitburnerSave database successful!");
indexedDb = e.target.result;
var transaction = indexedDb.transaction(["savestring"]);
var objectStore = transaction.objectStore("savestring");
var request = objectStore.get("save");
request.onerror = function (e) {
console.log("Error in Database request to get savestring: " + e);
return Engine.load(null); // Try to load from localstorage
};
request.onsuccess = function (e) {
Engine.load(request.result);
};
};
indexedDbRequest.onupgradeneeded = function (e) {
var db = e.target.result;
var objectStore = db.createObjectStore("savestring");
};
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 15 */
/*!***************************************!*\
!*** ./utils/helpers/getRandomInt.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Gets a random integer bounded by the values passed in.
* @param min The minimum value in the range.
* @param max The maximum value in the range.
*/
function getRandomInt(min, max) {
const lower = Math.min(min, max);
const upper = Math.max(min, max);
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
exports.getRandomInt = getRandomInt;
/***/ }),
/* 16 */
/*!******************************************!*\
!*** ./src/Augmentation/Augmentation.ts ***!
\******************************************/
/*! no static exports found */
/*! exports used: Augmentation */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Class definition for a single Augmentation object
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
const Factions_1 = __webpack_require__(/*! ../Faction/Factions */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
class Augmentation {
constructor(params = { info: "", moneyCost: 0, name: "", repCost: 0 }) {
// How much money this costs to buy
this.baseCost = 0;
// How much faction reputation is required to unlock this
this.baseRepRequirement = 0;
// Description of what this Aug is and what it does
this.info = "";
// Any Augmentation not immediately available in BitNode-1 is special (e.g. Bladeburner augs)
this.isSpecial = false;
// Augmentation level - for repeatable Augs like NeuroFlux Governor
this.level = 0;
// Name of Augmentation
this.name = "";
// Whether the player owns this Augmentation
this.owned = false;
// Array of names of all prerequisites
this.prereqs = [];
// Multipliers given by this Augmentation. Must match the property name in
// The Player/Person classes
this.mults = {};
// Initial cost. Doesn't change when you purchase multiple Augmentation
this.startingCost = 0;
this.name = params.name;
this.info = params.info;
this.prereqs = params.prereqs ? params.prereqs : [];
this.baseRepRequirement = params.repCost * Constants_1.CONSTANTS.AugmentationRepMultiplier * BitNodeMultipliers_1.BitNodeMultipliers.AugmentationRepCost;
this.baseCost = params.moneyCost * Constants_1.CONSTANTS.AugmentationCostMultiplier * BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost;
this.startingCost = this.baseCost;
if (params.isSpecial) {
this.isSpecial = true;
}
this.level = 0;
// Set multipliers
if (params.hacking_mult) {
this.mults.hacking_mult = params.hacking_mult;
}
if (params.strength_mult) {
this.mults.strength_mult = params.strength_mult;
}
if (params.defense_mult) {
this.mults.defense_mult = params.defense_mult;
}
if (params.dexterity_mult) {
this.mults.dexterity_mult = params.dexterity_mult;
}
if (params.agility_mult) {
this.mults.agility_mult = params.agility_mult;
}
if (params.charisma_mult) {
this.mults.charisma_mult = params.charisma_mult;
}
if (params.hacking_exp_mult) {
this.mults.hacking_exp_mult = params.hacking_exp_mult;
}
if (params.strength_exp_mult) {
this.mults.strength_exp_mult = params.strength_exp_mult;
}
if (params.defense_exp_mult) {
this.mults.defense_exp_mult = params.defense_exp_mult;
}
if (params.dexterity_exp_mult) {
this.mults.dexterity_exp_mult = params.dexterity_exp_mult;
}
if (params.agility_exp_mult) {
this.mults.agility_exp_mult = params.agility_exp_mult;
}
if (params.charisma_exp_mult) {
this.mults.charisma_exp_mult = params.charisma_exp_mult;
}
if (params.hacking_chance_mult) {
this.mults.hacking_chance_mult = params.hacking_chance_mult;
}
if (params.hacking_speed_mult) {
this.mults.hacking_speed_mult = params.hacking_speed_mult;
}
if (params.hacking_money_mult) {
this.mults.hacking_money_mult = params.hacking_money_mult;
}
if (params.hacking_grow_mult) {
this.mults.hacking_grow_mult = params.hacking_grow_mult;
}
if (params.company_rep_mult) {
this.mults.company_rep_mult = params.company_rep_mult;
}
if (params.faction_rep_mult) {
this.mults.faction_rep_mult = params.faction_rep_mult;
}
if (params.crime_money_mult) {
this.mults.crime_money_mult = params.crime_money_mult;
}
if (params.crime_success_mult) {
this.mults.crime_success_mult = params.crime_success_mult;
}
if (params.work_money_mult) {
this.mults.work_money_mult = params.work_money_mult;
}
if (params.hacknet_node_money_mult) {
this.mults.hacknet_node_money_mult = params.hacknet_node_money_mult;
}
if (params.hacknet_node_purchase_cost_mult) {
this.mults.hacknet_node_purchase_cost_mult = params.hacknet_node_purchase_cost_mult;
}
if (params.hacknet_node_ram_cost_mult) {
this.mults.hacknet_node_ram_cost_mult = params.hacknet_node_ram_cost_mult;
}
if (params.hacknet_node_core_cost_mult) {
this.mults.hacknet_node_core_cost_mult = params.hacknet_node_core_cost_mult;
}
if (params.hacknet_node_level_cost_mult) {
this.mults.hacknet_node_level_cost_mult = params.hacknet_node_level_cost_mult;
}
if (params.bladeburner_max_stamina_mult) {
this.mults.bladeburner_max_stamina_mult = params.bladeburner_max_stamina_mult;
}
if (params.bladeburner_stamina_gain_mult) {
this.mults.bladeburner_stamina_gain_mult = params.bladeburner_stamina_gain_mult;
}
if (params.bladeburner_analysis_mult) {
this.mults.bladeburner_analysis_mult = params.bladeburner_analysis_mult;
}
if (params.bladeburner_success_chance_mult) {
this.mults.bladeburner_success_chance_mult = params.bladeburner_success_chance_mult;
}
}
// Initiatizes a Augmentation object from a JSON save state.
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Augmentation, value.data);
}
// Adds this Augmentation to the specified Factions
addToFactions(factionList) {
for (let i = 0; i < factionList.length; ++i) {
const faction = Factions_1.Factions[factionList[i]];
if (faction == null) {
console.warn(`In Augmentation.addToFactions(), could not find faction with this name: ${factionList[i]}`);
continue;
}
faction.augmentations.push(this.name);
}
}
// Adds this Augmentation to all Factions
addToAllFactions() {
for (const fac in Factions_1.Factions) {
if (Factions_1.Factions.hasOwnProperty(fac)) {
const facObj = Factions_1.Factions[fac];
if (facObj == null) {
console.warn(`Invalid Faction object in addToAllFactions(). Key value: ${fac}`);
continue;
}
facObj.augmentations.push(this.name);
}
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("Augmentation", this);
}
}
exports.Augmentation = Augmentation;
JSONReviver_1.Reviver.constructors.Augmentation = Augmentation;
/***/ }),
/* 17 */
/*!******************************!*\
!*** ./utils/JSONReviver.js ***!
\******************************/
/*! exports provided: Reviver, Generic_toJSON, Generic_fromJSON */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reviver", function() { return Reviver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_toJSON", function() { return Generic_toJSON; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_fromJSON", function() { return Generic_fromJSON; });
/* Generic Reviver, toJSON, and fromJSON functions used for saving and loading objects */
// A generic "smart reviver" function.
// Looks for object values with a `ctor` property and
// a `data` property. If it finds them, and finds a matching
// constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value.
function Reviver(key, value) {
var ctor;
if (value == null) {
console.log("Reviver WRONGLY called with key: " + key + ", and value: " + value);
return 0;
}
if (typeof value === "object" &&
typeof value.ctor === "string" &&
typeof value.data !== "undefined") {
// Compatibility for version v0.43.1
// TODO Remove this eventually
if (value.ctor === "AllServersMap") {
console.log('Converting AllServersMap for v0.43.1');
return value.data;
}
ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
}
}
return value;
}
Reviver.constructors = {}; // A list of constructors the smart reviver should know about
// A generic "toJSON" function that creates the data expected
// by Reviver.
// `ctorName` The name of the constructor to use to revive it
// `obj` The object being serialized
// `keys` (Optional) Array of the properties to serialize,
// if not given then all of the objects "own" properties
// that don't have function values will be serialized.
// (Note: If you list a property in `keys`, it will be serialized
// regardless of whether it's an "own" property.)
// Returns: The structure (which will then be turned into a string
// as part of the JSON.stringify algorithm)
function Generic_toJSON(ctorName, obj, keys) {
var data, index, key;
if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included
}
data = {};
for (let index = 0; index < keys.length; ++index) {
key = keys[index];
data[key] = obj[key];
}
return {ctor: ctorName, data: data};
}
// A generic "fromJSON" function for use with Reviver: Just calls the
// constructor function with no arguments, then applies all of the
// key/value pairs from the raw data to the instance. Only useful for
// constructors that can be reasonably called without arguments!
// `ctor` The constructor to call
// `data` The data to apply
// Returns: The object
function Generic_fromJSON(ctor, data) {
var obj, name;
obj = new ctor();
for (name in data) {
obj[name] = data[name];
}
return obj;
}
/***/ }),
/* 18 */
/*!*******************************************!*\
!*** ./src/SourceFile/SourceFileFlags.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Contains an array containing information about the player's source files
// Array[n] returns what level the player has of Source-File N.
Object.defineProperty(exports, "__esModule", { value: true });
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
exports.SourceFileFlags = Array(Constants_1.CONSTANTS.TotalNumBitNodes + 1); // Skip index 0
function updateSourceFileFlags(p) {
for (let i = 0; i < exports.SourceFileFlags.length; ++i) {
exports.SourceFileFlags[i] = 0;
}
for (let i = 0; i < p.sourceFiles.length; ++i) {
const sf = p.sourceFiles[i];
exports.SourceFileFlags[sf.n] = sf.lvl;
}
}
exports.updateSourceFileFlags = updateSourceFileFlags;
/***/ }),
/* 19 */
/*!**********************************!*\
!*** ./src/Settings/Settings.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const SettingEnums_1 = __webpack_require__(/*! ./SettingEnums */ 53);
const defaultSettings = {
AutosaveInterval: 60,
CodeInstructionRunTime: 50,
DisableHotkeys: false,
Locale: "en",
MaxLogCapacity: 50,
MaxPortCapacity: 50,
SuppressBuyAugmentationConfirmation: false,
SuppressFactionInvites: false,
SuppressHospitalizationPopup: false,
SuppressMessages: false,
SuppressTravelConfirmation: false,
};
/**
* The current options the player has customized to their play style.
*/
// tslint:disable-next-line:variable-name
exports.Settings = {
AutosaveInterval: defaultSettings.AutosaveInterval,
CodeInstructionRunTime: 25,
DisableHotkeys: defaultSettings.DisableHotkeys,
Editor: SettingEnums_1.EditorSetting.Ace,
EditorKeybinding: SettingEnums_1.AceKeybindingSetting.Ace,
EditorTheme: "Monokai",
Locale: "en",
MaxLogCapacity: defaultSettings.MaxLogCapacity,
MaxPortCapacity: defaultSettings.MaxPortCapacity,
OwnedAugmentationsOrder: SettingEnums_1.OwnedAugmentationsOrderSetting.AcquirementTime,
PurchaseAugmentationsOrder: SettingEnums_1.PurchaseAugmentationsOrderSetting.Default,
SuppressBuyAugmentationConfirmation: defaultSettings.SuppressBuyAugmentationConfirmation,
SuppressFactionInvites: defaultSettings.SuppressFactionInvites,
SuppressHospitalizationPopup: defaultSettings.SuppressHospitalizationPopup,
SuppressMessages: defaultSettings.SuppressMessages,
SuppressTravelConfirmation: defaultSettings.SuppressTravelConfirmation,
init() {
Object.assign(exports.Settings, defaultSettings);
},
load(saveString) {
Object.assign(exports.Settings, JSON.parse(saveString));
},
};
/***/ }),
/* 20 */
/*!*******************************************!*\
!*** ./src/BitNode/BitNodeMultipliers.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The multipliers that are influenced by current Bitnode progression.
*/
// tslint:disable-next-line:variable-name
exports.BitNodeMultipliers = {
HackingLevelMultiplier: 1,
StrengthLevelMultiplier: 1,
DefenseLevelMultiplier: 1,
DexterityLevelMultiplier: 1,
AgilityLevelMultiplier: 1,
CharismaLevelMultiplier: 1,
ServerGrowthRate: 1,
ServerMaxMoney: 1,
ServerStartingMoney: 1,
ServerStartingSecurity: 1,
ServerWeakenRate: 1,
HomeComputerRamCost: 1,
PurchasedServerCost: 1,
PurchasedServerLimit: 1,
PurchasedServerMaxRam: 1,
CompanyWorkMoney: 1,
CrimeMoney: 1,
HacknetNodeMoney: 1,
ManualHackMoney: 1,
ScriptHackMoney: 1,
CodingContractMoney: 1,
ClassGymExpGain: 1,
CompanyWorkExpGain: 1,
CrimeExpGain: 1,
FactionWorkExpGain: 1,
HackExpGain: 1,
FactionPassiveRepGain: 1,
FactionWorkRepGain: 1,
RepToDonateToFaction: 1,
AugmentationMoneyCost: 1,
AugmentationRepCost: 1,
InfiltrationMoney: 1,
InfiltrationRep: 1,
FourSigmaMarketDataCost: 1,
FourSigmaMarketDataApiCost: 1,
CorporationValuation: 1,
BladeburnerRank: 1,
BladeburnerSkillCost: 1,
DaedalusAugsRequirement: 1,
};
/***/ }),
/* 21 */
/*!**********************************!*\
!*** ./src/Server/AllServers.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Server_1 = __webpack_require__(/*! ./Server */ 105);
const SpecialServerIps_1 = __webpack_require__(/*! ./SpecialServerIps */ 38);
const servers_1 = __webpack_require__(/*! ./data/servers */ 669);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 159);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 15);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/**
* Map of all Servers that exist in the game
* Key (string) = IP
* Value = Server object
*/
exports.AllServers = {};
function ipExists(ip) {
return (exports.AllServers[ip] != null);
}
exports.ipExists = ipExists;
function createUniqueRandomIp() {
const ip = IPAddress_1.createRandomIp();
// If the Ip already exists, recurse to create a new one
if (ipExists(ip)) {
return IPAddress_1.createRandomIp();
}
return ip;
}
exports.createUniqueRandomIp = createUniqueRandomIp;
// Saftely add a Server to the AllServers map
function AddToAllServers(server) {
var serverIp = server.ip;
if (ipExists(serverIp)) {
console.warn(`IP of server that's being added: ${serverIp}`);
console.warn(`Hostname of the server thats being added: ${server.hostname}`);
console.warn(`The server that already has this IP is: ${exports.AllServers[serverIp].hostname}`);
throw new Error("Error: Trying to add a server with an existing IP");
}
exports.AllServers[serverIp] = server;
}
exports.AddToAllServers = AddToAllServers;
function initForeignServers(homeComputer) {
/* Create a randomized network for all the foreign servers */
//Groupings for creating a randomized network
const networkLayers = [];
for (let i = 0; i < 15; i++) {
networkLayers.push([]);
}
// Essentially any property that is of type 'number | IMinMaxRange'
const propertiesToPatternMatch = [
"hackDifficulty",
"moneyAvailable",
"requiredHackingSkill",
"serverGrowth"
];
const toNumber = (value) => {
switch (typeof value) {
case 'number':
return value;
case 'object':
return getRandomInt_1.getRandomInt(value.min, value.max);
default:
throw Error(`Do not know how to convert the type '${typeof value}' to a number`);
}
};
for (const metadata of servers_1.serverMetadata) {
const serverParams = {
hostname: metadata.hostname,
ip: createUniqueRandomIp(),
numOpenPortsRequired: metadata.numOpenPortsRequired,
organizationName: metadata.organizationName
};
if (metadata.maxRamExponent !== undefined) {
serverParams.maxRam = Math.pow(2, toNumber(metadata.maxRamExponent));
}
for (const prop of propertiesToPatternMatch) {
if (metadata[prop] !== undefined) {
serverParams[prop] = toNumber(metadata[prop]);
}
}
const server = new Server_1.Server(serverParams);
for (const filename of (metadata.literature || [])) {
server.messages.push(filename);
}
if (metadata.specialName !== undefined) {
SpecialServerIps_1.SpecialServerIps.addIp(metadata.specialName, server.ip);
}
AddToAllServers(server);
if (metadata.networkLayer !== undefined) {
networkLayers[toNumber(metadata.networkLayer) - 1].push(server);
}
}
/* Create a randomized network for all the foreign servers */
const linkComputers = (server1, server2) => {
server1.serversOnNetwork.push(server2.ip);
server2.serversOnNetwork.push(server1.ip);
};
const getRandomArrayItem = (arr) => arr[Math.floor(Math.random() * arr.length)];
const linkNetworkLayers = (network1, selectServer) => {
for (const server of network1) {
linkComputers(server, selectServer());
}
};
// Connect the first tier of servers to the player's home computer
linkNetworkLayers(networkLayers[0], () => homeComputer);
for (let i = 1; i < networkLayers.length; i++) {
linkNetworkLayers(networkLayers[i], () => getRandomArrayItem(networkLayers[i - 1]));
}
}
exports.initForeignServers = initForeignServers;
function prestigeAllServers() {
for (var member in exports.AllServers) {
delete exports.AllServers[member];
}
exports.AllServers = {};
}
exports.prestigeAllServers = prestigeAllServers;
function loadAllServers(saveString) {
exports.AllServers = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadAllServers = loadAllServers;
/***/ }),
/* 22 */
/*!*************************************!*\
!*** ./src/Server/ServerHelpers.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const AllServers_1 = __webpack_require__(/*! ./AllServers */ 21);
const Server_1 = __webpack_require__(/*! ./Server */ 105);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
const Programs_1 = __webpack_require__(/*! ../Programs/Programs */ 30);
const isValidIPAddress_1 = __webpack_require__(/*! ../../utils/helpers/isValidIPAddress */ 148);
/**
* Constructs a new server, while also ensuring that the new server
* does not have a duplicate hostname/ip.
*/
function safetlyCreateUniqueServer(params) {
if (params.ip != null && AllServers_1.ipExists(params.ip)) {
params.ip = AllServers_1.createUniqueRandomIp();
}
if (GetServerByHostname(params.hostname) != null) {
// Use a for loop to ensure that we don't get suck in an infinite loop somehow
let hostname = params.hostname;
for (let i = 0; i < 200; ++i) {
hostname = `${params.hostname}-${i}`;
if (GetServerByHostname(hostname) == null) {
break;
}
}
params.hostname = hostname;
}
return new Server_1.Server(params);
}
exports.safetlyCreateUniqueServer = safetlyCreateUniqueServer;
// Returns the number of cycles needed to grow the specified server by the
// specified amount. 'growth' parameter is in decimal form, not percentage
function numCycleForGrowth(server, growth, p) {
let ajdGrowthRate = 1 + (Constants_1.CONSTANTS.ServerBaseGrowthRate - 1) / server.hackDifficulty;
if (ajdGrowthRate > Constants_1.CONSTANTS.ServerMaxGrowthRate) {
ajdGrowthRate = Constants_1.CONSTANTS.ServerMaxGrowthRate;
}
const serverGrowthPercentage = server.serverGrowth / 100;
const cycles = Math.log(growth) / (Math.log(ajdGrowthRate) * p.hacking_grow_mult * serverGrowthPercentage * BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate);
return cycles;
}
exports.numCycleForGrowth = numCycleForGrowth;
//Applied server growth for a single server. Returns the percentage growth
function processSingleServerGrowth(server, numCycles, p) {
//Server growth processed once every 450 game cycles
const numServerGrowthCycles = Math.max(Math.floor(numCycles / 450), 0);
//Get adjusted growth rate, which accounts for server security
const growthRate = Constants_1.CONSTANTS.ServerBaseGrowthRate;
var adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty;
if (adjGrowthRate > Constants_1.CONSTANTS.ServerMaxGrowthRate) {
adjGrowthRate = Constants_1.CONSTANTS.ServerMaxGrowthRate;
}
//Calculate adjusted server growth rate based on parameters
const serverGrowthPercentage = server.serverGrowth / 100;
const numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate;
//Apply serverGrowth for the calculated number of growth cycles
let serverGrowth = Math.pow(adjGrowthRate, numServerGrowthCyclesAdjusted * p.hacking_grow_mult);
if (serverGrowth < 1) {
console.log("WARN: serverGrowth calculated to be less than 1");
serverGrowth = 1;
}
const oldMoneyAvailable = server.moneyAvailable;
server.moneyAvailable *= serverGrowth;
// in case of data corruption
if (server.moneyMax && isNaN(server.moneyAvailable)) {
server.moneyAvailable = server.moneyMax;
}
// cap at max
if (server.moneyMax && server.moneyAvailable > server.moneyMax) {
server.moneyAvailable = server.moneyMax;
}
// if there was any growth at all, increase security
if (oldMoneyAvailable !== server.moneyAvailable) {
//Growing increases server security twice as much as hacking
let usedCycles = numCycleForGrowth(server, server.moneyAvailable / oldMoneyAvailable, p);
usedCycles = Math.max(0, usedCycles);
server.fortify(2 * Constants_1.CONSTANTS.ServerFortifyAmount * Math.ceil(usedCycles));
}
return server.moneyAvailable / oldMoneyAvailable;
}
exports.processSingleServerGrowth = processSingleServerGrowth;
function prestigeHomeComputer(homeComp) {
const hasBitflume = homeComp.programs.includes(Programs_1.Programs.BitFlume.name);
homeComp.programs.length = 0; //Remove programs
homeComp.runningScripts = [];
homeComp.serversOnNetwork = [];
homeComp.isConnectedTo = true;
homeComp.ramUsed = 0;
homeComp.programs.push(Programs_1.Programs.NukeProgram.name);
if (hasBitflume) {
homeComp.programs.push(Programs_1.Programs.BitFlume.name);
}
//Update RAM usage on all scripts
homeComp.scripts.forEach(function (script) {
script.updateRamUsage(homeComp.scripts);
});
homeComp.messages.length = 0; //Remove .lit and .msg files
homeComp.messages.push("hackers-starting-handbook.lit");
}
exports.prestigeHomeComputer = prestigeHomeComputer;
//Returns server object with corresponding hostname
// Relatively slow, would rather not use this a lot
function GetServerByHostname(hostname) {
for (var ip in AllServers_1.AllServers) {
if (AllServers_1.AllServers.hasOwnProperty(ip)) {
if (AllServers_1.AllServers[ip].hostname == hostname) {
return AllServers_1.AllServers[ip];
}
}
}
return null;
}
exports.GetServerByHostname = GetServerByHostname;
//Get server by IP or hostname. Returns null if invalid
function getServer(s) {
if (!isValidIPAddress_1.isValidIPAddress(s)) {
return GetServerByHostname(s);
}
if (AllServers_1.AllServers[s] !== undefined) {
return AllServers_1.AllServers[s];
}
return null;
}
exports.getServer = getServer;
// Returns the i-th server on the specified server's network
// A Server's serverOnNetwork property holds only the IPs. This function returns
// the actual Server object
function getServerOnNetwork(server, i) {
if (i > server.serversOnNetwork.length) {
console.error("Tried to get server on network that was out of range");
return;
}
return AllServers_1.AllServers[server.serversOnNetwork[i]];
}
exports.getServerOnNetwork = getServerOnNetwork;
/***/ }),
/* 23 */
/*!**********************************************!*\
!*** ./src/Corporation/EmployeePositions.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmployeePositions = {
Operations: "Operations",
Engineer: "Engineer",
Business: "Business",
Management: "Management",
RandD: "Research & Development",
Training: "Training",
Unassigned: "Unassigned",
};
/***/ }),
/* 24 */
/*!****************************************!*\
!*** ./src/Hacknet/HacknetHelpers.jsx ***!
\****************************************/
/*! exports provided: hasHacknetServers, purchaseHacknet, hasMaxNumberHacknetServers, getCostOfNextHacknetNode, getCostOfNextHacknetServer, getMaxNumberLevelUpgrades, getMaxNumberRamUpgrades, getMaxNumberCoreUpgrades, getMaxNumberCacheUpgrades, purchaseLevelUpgrade, purchaseRamUpgrade, purchaseCoreUpgrade, purchaseCacheUpgrade, renderHacknetNodesUI, clearHacknetNodesUI, processHacknetEarnings, updateHashManagerCapacity, purchaseHashUpgrade */
/*! exports used: clearHacknetNodesUI, getCostOfNextHacknetNode, getCostOfNextHacknetServer, getMaxNumberCacheUpgrades, getMaxNumberCoreUpgrades, getMaxNumberLevelUpgrades, getMaxNumberRamUpgrades, hasHacknetServers, hasMaxNumberHacknetServers, processHacknetEarnings, purchaseCacheUpgrade, purchaseCoreUpgrade, purchaseHacknet, purchaseHashUpgrade, purchaseLevelUpgrade, purchaseRamUpgrade, renderHacknetNodesUI, updateHashManagerCapacity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return hasHacknetServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return purchaseHacknet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return hasMaxNumberHacknetServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCostOfNextHacknetNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getCostOfNextHacknetServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getMaxNumberLevelUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getMaxNumberRamUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getMaxNumberCoreUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getMaxNumberCacheUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return purchaseLevelUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return purchaseRamUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return purchaseCoreUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return purchaseCacheUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return renderHacknetNodesUI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clearHacknetNodesUI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return processHacknetEarnings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return updateHashManagerCapacity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return purchaseHashUpgrade; });
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HacknetNode */ 54);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_HacknetNode__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _HacknetServer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./HacknetServer */ 35);
/* harmony import */ var _HacknetServer__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_HacknetServer__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./HashManager */ 107);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_HashManager__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./HashUpgrades */ 138);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_HashUpgrades__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../CodingContractGenerator */ 117);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../InteractiveTutorial */ 40);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Server/AllServers */ 21);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../SourceFile/SourceFileFlags */ 18);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 91);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! react-dom */ 64);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./ui/Root */ 170);
let hacknetNodesDiv;
function hacknetNodesInit() {
hacknetNodesDiv = document.getElementById("hacknet-nodes-container");
document.removeEventListener("DOMContentLoaded", hacknetNodesInit);
}
document.addEventListener("DOMContentLoaded", hacknetNodesInit); // Returns a boolean indicating whether the player has Hacknet Servers
// (the upgraded form of Hacknet Nodes)
function hasHacknetServers() {
return _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN === 9 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_9__["SourceFileFlags"][9] > 0;
}
function purchaseHacknet() {
/* INTERACTIVE TUTORIAL */
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_5__[/* ITutorial */ "a"].isRunning) {
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_5__[/* ITutorial */ "a"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_5__[/* iTutorialSteps */ "d"].HacknetNodesIntroduction) {
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_5__[/* iTutorialNextStep */ "b"])();
} else {
return;
}
}
/* END INTERACTIVE TUTORIAL */
const numOwned = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length;
if (hasHacknetServers()) {
const cost = getCostOfNextHacknetServer();
if (isNaN(cost)) {
throw new Error(`Calculated cost of purchasing HacknetServer is NaN`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return -1;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
const server = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].createHacknetServer();
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.updateCapacity(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes);
return numOwned;
} else {
const cost = getCostOfNextHacknetNode();
if (isNaN(cost)) {
throw new Error(`Calculated cost of purchasing HacknetNode is NaN`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return -1;
} // Auto generate a name for the Node
const name = "hacknet-node-" + numOwned;
const node = new _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"](name, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.push(node);
return numOwned;
}
}
function hasMaxNumberHacknetServers() {
return hasHacknetServers() && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length >= _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["MaxNumberHacknetServers"];
}
function getCostOfNextHacknetNode() {
// Cost increases exponentially based on how many you own
const numOwned = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length;
const mult = _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodePurchaseNextMult"];
return _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["BaseCostForHacknetNode"] * Math.pow(mult, numOwned) * _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult;
}
function getCostOfNextHacknetServer() {
const numOwned = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length;
const mult = _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerPurchaseMult"];
if (numOwned > _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["MaxNumberHacknetServers"]) {
return Infinity;
}
return _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["BaseCostForHacknetServer"] * Math.pow(mult, numOwned) * _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult;
} //Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node
function getMaxNumberLevelUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberLevelUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
let levelsToMax = maxLevel - nodeObj.level;
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult))) {
return levelsToMax;
}
while (min <= max) {
var curr = (min + max) / 2 | 0;
if (curr !== maxLevel && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult)) && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr + 1, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
function getMaxNumberRamUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberRamUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateRamUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult))) {
return 0;
}
let levelsToMax;
if (nodeObj instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"]) {
levelsToMax = Math.round(Math.log2(maxLevel / nodeObj.maxRam));
} else {
levelsToMax = Math.round(Math.log2(maxLevel / nodeObj.ram));
}
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateRamUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult))) {
return levelsToMax;
} //We'll just loop until we find the max
for (let i = levelsToMax - 1; i >= 0; --i) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateRamUpgradeCost(i, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult))) {
return i;
}
}
return 0;
}
function getMaxNumberCoreUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberCoreUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
const levelsToMax = maxLevel - nodeObj.cores;
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult))) {
return levelsToMax;
} //Use a binary search to find the max possible number of upgrades
while (min <= max) {
let curr = (min + max) / 2 | 0;
if (curr != maxLevel && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult)) && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(curr + 1, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
function getMaxNumberCacheUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberCacheUpgrades() called without maxLevel arg`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(1))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
const levelsToMax = maxLevel - nodeObj.cache;
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(levelsToMax))) {
return levelsToMax;
} // Use a binary search to find the max possible number of upgrades
while (min <= max) {
let curr = (min + max) / 2 | 0;
if (curr != maxLevel && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr)) && !_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr + 1))) {
return Math.min(levelsToMax, curr);
} else if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
function purchaseLevelUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateLevelUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"]; // If we're at max level, return false
if (node.level >= (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxLevel"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxLevel"])) {
return false;
} // If the number of specified upgrades would exceed the max level, calculate
// the maximum number of upgrades and use that
if (node.level + sanitizedLevels > (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxLevel"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxLevel"])) {
const diff = Math.max(0, (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxLevel"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxLevel"]) - node.level);
return purchaseLevelUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
node.upgradeLevel(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseRamUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateRamUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"]; // Fail if we're already at max
if (node.ram >= (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxRam"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxRam"])) {
return false;
} // If the number of specified upgrades would exceed the max RAM, calculate the
// max possible number of upgrades and use that
if (isServer) {
if (node.maxRam * Math.pow(2, sanitizedLevels) > _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxRam"]) {
const diff = Math.max(0, Math.log2(Math.round(_HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxRam"] / node.maxRam)));
return purchaseRamUpgrade(node, diff);
}
} else {
if (node.ram * Math.pow(2, sanitizedLevels) > _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxRam"]) {
const diff = Math.max(0, Math.log2(Math.round(_HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxRam"] / node.ram)));
return purchaseRamUpgrade(node, diff);
}
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
node.upgradeRam(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseCoreUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateCoreUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"]; // Fail if we're already at max
if (node.cores >= (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxCores"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxCores"])) {
return false;
} // If the specified number of upgrades would exceed the max Cores, calculate
// the max possible number of upgrades and use that
if (node.cores + sanitizedLevels > (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxCores"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxCores"])) {
const diff = Math.max(0, (isServer ? _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxCores"] : _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNodeMaxCores"]) - node.cores);
return purchaseCoreUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
node.upgradeCore(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseCacheUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateCoreUpgradeCost(sanitizedLevels);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
if (!(node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"])) {
console.warn(`purchaseCacheUpgrade() called for a non-HacknetNode`);
return false;
} // Fail if we're already at max
if (node.cache + sanitizedLevels > _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxCache"]) {
const diff = Math.max(0, _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServerMaxCache"] - node.cache);
return purchaseCacheUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].loseMoney(cost);
node.upgradeCache(sanitizedLevels);
} // Create/Refresh Hacknet Nodes UI
function renderHacknetNodesUI() {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].HacknetNodes)) {
return;
}
react_dom__WEBPACK_IMPORTED_MODULE_13___default.a.render(react__WEBPACK_IMPORTED_MODULE_12___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_14__[/* HacknetRoot */ "a"], null), hacknetNodesDiv);
}
function clearHacknetNodesUI() {
if (hacknetNodesDiv instanceof HTMLElement) {
react_dom__WEBPACK_IMPORTED_MODULE_13___default.a.unmountComponentAtNode(hacknetNodesDiv);
}
hacknetNodesDiv.style.display = "none";
}
function processHacknetEarnings(numCycles) {
// Determine if player has Hacknet Nodes or Hacknet Servers, then
// call the appropriate function
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length === 0) {
return 0;
}
if (hasHacknetServers()) {
return processAllHacknetServerEarnings(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes[0] instanceof _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"]) {
return processAllHacknetNodeEarnings(numCycles);
} else {
return 0;
}
}
function processAllHacknetNodeEarnings(numCycles) {
let total = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length; ++i) {
total += processSingleHacknetNodeEarnings(numCycles, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes[i]);
}
return total;
}
function processSingleHacknetNodeEarnings(numCycles, nodeObj) {
const totalEarnings = nodeObj.process(numCycles);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainMoney(totalEarnings);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].recordMoneySource(totalEarnings, "hacknetnode");
return totalEarnings;
}
function processAllHacknetServerEarnings(numCycles) {
if (!(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_2__["HashManager"])) {
throw new Error(`Player does not have a HashManager (should be in 'hashManager' prop)`);
}
let hashes = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes.length; ++i) {
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_7__["AllServers"][_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes[i]]; // hacknetNodes array only contains the IP addresses
hashes += hserver.process(numCycles);
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.storeHashes(hashes);
return hashes;
}
function updateHashManagerCapacity() {
if (!(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_2__["HashManager"])) {
console.error(`Player does not have a HashManager`);
return;
}
const nodes = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknetNodes;
if (nodes.length === 0) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.updateCapacity(0);
return;
}
let total = 0;
for (let i = 0; i < nodes.length; ++i) {
if (typeof nodes[i] !== "string") {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.updateCapacity(0);
return;
}
const h = _Server_AllServers__WEBPACK_IMPORTED_MODULE_7__["AllServers"][nodes[i]];
if (!(h instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_1__["HacknetServer"])) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.updateCapacity(0);
return;
}
total += h.hashCapacity;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.updateCapacity(total);
}
function purchaseHashUpgrade(upgName, upgTarget) {
if (!(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_2__["HashManager"])) {
console.error(`Player does not have a HashManager`);
return false;
} // HashManager handles the transaction. This just needs to actually implement
// the effects of the upgrade
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.upgrade(upgName)) {
const upg = _HashUpgrades__WEBPACK_IMPORTED_MODULE_3__["HashUpgrades"][upgName];
switch (upgName) {
case "Sell for Money":
{
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainMoney(upg.value);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].recordMoneySource(upg.value, "hacknetnode");
break;
}
case "Sell for Corporation Funds":
{
// This will throw if player doesn't have a corporation
try {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.funds = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.funds.plus(upg.value);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Reduce Minimum Security":
{
try {
const target = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__["GetServerByHostname"])(upgTarget);
if (target == null) {
console.error(`Invalid target specified in purchaseHashUpgrade(): ${upgTarget}`);
return false;
}
target.changeMinimumSecurity(upg.value, true);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Increase Maximum Money":
{
try {
const target = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__["GetServerByHostname"])(upgTarget);
if (target == null) {
console.error(`Invalid target specified in purchaseHashUpgrade(): ${upgTarget}`);
return false;
}
target.changeMaximumMoney(upg.value, true);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Improve Studying":
{
// Multiplier handled by HashManager
break;
}
case "Improve Gym Training":
{
// Multiplier handled by HashManager
break;
}
case "Exchange for Corporation Research":
{
// This will throw if player doesn't have a corporation
try {
for (const division of _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.divisions) {
division.sciResearch.qty += upg.value;
}
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Exchange for Bladeburner Rank":
{
// This will throw if player isnt in Bladeburner
try {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.changeRank(upg.value);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Exchange for Bladeburner SP":
{
// This will throw if player isn't in Bladeburner
try {
// As long as we don't change `Bladeburner.totalSkillPoints`, this
// shouldn't affect anything else
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.skillPoints += upg.value;
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Generate Coding Contract":
{
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_4__[/* generateRandomContract */ "b"])();
break;
}
default:
console.warn(`Unrecognized upgrade name ${upgName}. Upgrade has no effect`);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
return true;
}
return false;
}
/***/ }),
/* 25 */
/*!**********************************!*\
!*** ./src/Company/Companies.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Constructs all CompanyPosition objects using the metadata in data/companypositions.ts
const CompaniesMetadata_1 = __webpack_require__(/*! ./data/CompaniesMetadata */ 631);
const Company_1 = __webpack_require__(/*! ./Company */ 87);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
exports.Companies = {};
function addCompany(params) {
if (exports.Companies[params.name] != null) {
console.warn(`Duplicate Company Position being defined: ${params.name}`);
}
exports.Companies[params.name] = new Company_1.Company(params);
}
// Used to initialize new Company objects for the Companies map
// Called when creating new game or after a prestige/reset
function initCompanies() {
// Save Old Company data for 'favor'
const oldCompanies = exports.Companies;
// Re-construct all Companies
exports.Companies = {};
CompaniesMetadata_1.companiesMetadata.forEach((e) => {
addCompany(e);
});
// Reset data
for (const companyName in exports.Companies) {
const company = exports.Companies[companyName];
const oldCompany = oldCompanies[companyName];
if (!(oldCompany instanceof Company_1.Company)) {
// New game, so no OldCompanies data
company.favor = 0;
}
else {
company.favor = oldCompanies[companyName].favor;
if (isNaN(company.favor)) {
company.favor = 0;
}
}
}
}
exports.initCompanies = initCompanies;
// Used to load Companies map from a save
function loadCompanies(saveString) {
exports.Companies = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadCompanies = loadCompanies;
// Utility function to check if a string is valid company name
function companyExists(name) {
return exports.Companies.hasOwnProperty(name);
}
exports.companyExists = companyExists;
/***/ }),
/* 26 */
/*!*****************************************!*\
!*** ./src/Corporation/IndustryData.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const BaseResearchTree_1 = __webpack_require__(/*! ./data/BaseResearchTree */ 668);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 2);
// Map of official names for each Industry
exports.Industries = {
Energy: "Energy",
Utilities: "Water Utilities",
Agriculture: "Agriculture",
Fishing: "Fishing",
Mining: "Mining",
Food: "Food",
Tobacco: "Tobacco",
Chemical: "Chemical",
Pharmaceutical: "Pharmaceutical",
Computer: "Computer Hardware",
Robotics: "Robotics",
Software: "Software",
Healthcare: "Healthcare",
RealEstate: "RealEstate",
};
// Map of how much money it takes to start each industry
exports.IndustryStartingCosts = {
Energy: 225e9,
Utilities: 150e9,
Agriculture: 40e9,
Fishing: 80e9,
Mining: 300e9,
Food: 10e9,
Tobacco: 20e9,
Chemical: 70e9,
Pharmaceutical: 200e9,
Computer: 500e9,
Robotics: 1e12,
Software: 25e9,
Healthcare: 750e9,
RealEstate: 600e9,
};
// Map of description for each industry
exports.IndustryDescriptions = {
Energy: "Engage in the production and distribution of energy.
" +
"Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Utilities, "$0.000a") + " " +
"Recommended starting Industry: NO",
Agriculture: "Cultive crops and breed livestock to produce food.
" +
"Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Agriculture, "$0.000a") + " " +
"Recommended starting Industry: YES",
Fishing: "Produce food through the breeding and processing of fish and fish products
" +
"Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Fishing, "$0.000a") + " " +
"Recommended starting Industry: NO",
Mining: "Extract and process metals from the earth.
" +
"Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Mining, "$0.000a") + " " +
"Recommended starting Industry: NO",
Food: "Create your own restaurants all around the world.
" +
"Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.RealEstate, "$0.000a") + " " +
"Recommended starting Industry: NO",
};
// Map of available Research for each Industry. This data is held in a
// ResearchTree object
exports.IndustryResearchTrees = {
Energy: BaseResearchTree_1.getBaseResearchTreeCopy(),
Utilities: BaseResearchTree_1.getBaseResearchTreeCopy(),
Agriculture: BaseResearchTree_1.getBaseResearchTreeCopy(),
Fishing: BaseResearchTree_1.getBaseResearchTreeCopy(),
Mining: BaseResearchTree_1.getBaseResearchTreeCopy(),
Food: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Tobacco: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Chemical: BaseResearchTree_1.getBaseResearchTreeCopy(),
Pharmaceutical: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Computer: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Robotics: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Software: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Healthcare: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
RealEstate: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
};
function resetIndustryResearchTrees() {
exports.IndustryResearchTrees.Energy = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Utilities = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Agriculture = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Fishing = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Mining = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Food = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Tobacco = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Chemical = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Pharmaceutical = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Computer = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Robotics = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Software = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Healthcare = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.RealEstate = BaseResearchTree_1.getBaseResearchTreeCopy();
}
exports.resetIndustryResearchTrees = resetIndustryResearchTrees;
/***/ }),
/* 27 */
/*!************************************************!*\
!*** ./utils/uiHelpers/clearEventListeners.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 91);
/**
* Given an element by its ID, removes all event listeners from that element by cloning and
* replacing. Then returns the new cloned element.
* @param elemId The HTML ID to retrieve the element by.
*/
function clearEventListeners(elemId) {
try {
let elem;
if (typeof elemId === "string") {
elem = getElementById_1.getElementById(elemId);
}
else {
elem = elemId;
}
const newElem = elem.cloneNode(true);
if (elem.parentNode !== null) {
elem.parentNode.replaceChild(newElem, elem);
}
return newElem;
}
catch (e) {
// tslint:disable-next-line:no-console
console.error(e);
return null;
}
}
exports.clearEventListeners = clearEventListeners;
/***/ }),
/* 28 */
/*!*****************************************!*\
!*** ./src/Locations/data/CityNames.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* All possible Cities in the game. Names only, not actual "City" object
* Implemented as an enum for typing purposes
*/
var CityName;
(function (CityName) {
CityName["Aevum"] = "Aevum";
CityName["Chongqing"] = "Chongqing";
CityName["Ishima"] = "Ishima";
CityName["NewTokyo"] = "New Tokyo";
CityName["Sector12"] = "Sector-12";
CityName["Volhaven"] = "Volhaven";
})(CityName = exports.CityName || (exports.CityName = {}));
;
/***/ }),
/* 29 */
/*!**********************************************!*\
!*** ./utils/uiHelpers/removeElementById.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 91);
const removeElement_1 = __webpack_require__(/*! ./removeElement */ 76);
/**
* Given its id, this function removes an element AND its children
* @param id The HTML identifier to search for and remove.
*/
function removeElementById(id) {
try {
const elem = getElementById_1.getElementById(id);
removeElement_1.removeElement(elem);
}
catch (e) {
// Probably should log this as we're trying to remove elements that don't exist.
}
}
exports.removeElementById = removeElementById;
/***/ }),
/* 30 */
/*!**********************************!*\
!*** ./src/Programs/Programs.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Program_1 = __webpack_require__(/*! ./Program */ 625);
const programsMetadata_1 = __webpack_require__(/*! ./data/programsMetadata */ 624);
exports.Programs = {};
for (const params of programsMetadata_1.programsMetadata) {
exports.Programs[params.key] = new Program_1.Program(params.name, params.create);
}
/***/ }),
/* 31 */
/*!*****************************************!*\
!*** ./src/Corporation/Corporation.jsx ***!
\*****************************************/
/*! exports provided: INITIALSHARES, SHARESPERPRICEUPDATE, IssueNewSharesCooldown, SellSharesCooldown, CyclesPerMarketCycle, CyclesPerIndustryStateCycle, SecsPerMarketCycle, Cities, WarehouseInitialCost, WarehouseInitialSize, WarehouseUpgradeBaseCost, OfficeInitialCost, OfficeInitialSize, OfficeUpgradeBaseCost, BribeThreshold, BribeToRepRatio, ProductProductionCostRatio, DividendMaxPercentage, EmployeeSalaryMultiplier, CyclesPerEmployeeRaise, EmployeeRaiseAmount, BaseMaxProducts, Corporation, Industry, OfficeSpace, Warehouse */
/*! exports used: BribeThreshold, BribeToRepRatio, Corporation, DividendMaxPercentage, Industry, IssueNewSharesCooldown, OfficeInitialCost, OfficeInitialSize, OfficeSpace, ProductProductionCostRatio, SellSharesCooldown, Warehouse, WarehouseInitialCost, WarehouseInitialSize, WarehouseUpgradeBaseCost */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* unused harmony export INITIALSHARES */
/* unused harmony export SHARESPERPRICEUPDATE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return IssueNewSharesCooldown; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return SellSharesCooldown; });
/* unused harmony export CyclesPerMarketCycle */
/* unused harmony export CyclesPerIndustryStateCycle */
/* unused harmony export SecsPerMarketCycle */
/* unused harmony export Cities */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return WarehouseInitialCost; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return WarehouseInitialSize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return WarehouseUpgradeBaseCost; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return OfficeInitialCost; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return OfficeInitialSize; });
/* unused harmony export OfficeUpgradeBaseCost */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BribeThreshold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return BribeToRepRatio; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return ProductProductionCostRatio; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return DividendMaxPercentage; });
/* unused harmony export EmployeeSalaryMultiplier */
/* unused harmony export CyclesPerEmployeeRaise */
/* unused harmony export EmployeeRaiseAmount */
/* unused harmony export BaseMaxProducts */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Corporation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return Industry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return OfficeSpace; });
/* harmony import */ var _CorporationState__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CorporationState */ 203);
/* harmony import */ var _CorporationState__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_CorporationState__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _data_CorporationUnlockUpgrades__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./data/CorporationUnlockUpgrades */ 172);
/* harmony import */ var _data_CorporationUnlockUpgrades__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_data_CorporationUnlockUpgrades__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _data_CorporationUpgrades__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./data/CorporationUpgrades */ 171);
/* harmony import */ var _data_CorporationUpgrades__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_data_CorporationUpgrades__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./EmployeePositions */ 23);
/* harmony import */ var _EmployeePositions__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _IndustryData__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./IndustryData */ 26);
/* harmony import */ var _IndustryData__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_IndustryData__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _IndustryUpgrades__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./IndustryUpgrades */ 152);
/* harmony import */ var _IndustryUpgrades__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_IndustryUpgrades__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Material */ 149);
/* harmony import */ var _Material__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Material__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./MaterialSizes */ 95);
/* harmony import */ var _MaterialSizes__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_MaterialSizes__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Product__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Product */ 130);
/* harmony import */ var _Product__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Product__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _ResearchMap__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ResearchMap */ 164);
/* harmony import */ var _ResearchMap__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ResearchMap__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Warehouse__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Warehouse */ 89);
/* harmony import */ var _Warehouse__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Warehouse__WEBPACK_IMPORTED_MODULE_10__);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "l", function() { return _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]; });
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Faction/Factions */ 13);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Literature */ 129);
/* harmony import */ var _Locations_Cities__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Locations/Cities */ 106);
/* harmony import */ var _Locations_Cities__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Locations_Cities__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Locations/data/CityNames */ 28);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_calculateEffectWithFactors__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/calculateEffectWithFactors */ 297);
/* harmony import */ var _utils_calculateEffectWithFactors__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_calculateEffectWithFactors__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../utils/uiHelpers/clearSelector */ 196);
/* harmony import */ var _utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../utils/uiHelpers/appendLineBreaks */ 80);
/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../utils/uiHelpers/createPopup */ 36);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _utils_uiHelpers_createPopupCloseButton__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../utils/uiHelpers/createPopupCloseButton */ 58);
/* harmony import */ var _utils_uiHelpers_createPopupCloseButton__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopupCloseButton__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 15);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../../utils/helpers/isString */ 51);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../../utils/uiHelpers/removeElement */ 76);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../../utils/uiHelpers/removeElementById */ 29);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../../utils/YesNoBox */ 46);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! react-dom */ 64);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _ui_CorporationUIEventHandler__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./ui/CorporationUIEventHandler */ 296);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./ui/Root */ 295);
/* harmony import */ var _ui_Routing__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./ui/Routing */ 136);
/* harmony import */ var _ui_Routing__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_ui_Routing__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! decimal.js */ 44);
// UI Related Imports
/* Constants */
const INITIALSHARES = 1e9; //Total number of shares you have at your company
const SHARESPERPRICEUPDATE = 1e6; //When selling large number of shares, price is dynamically updated for every batch of this amount
const IssueNewSharesCooldown = 216e3; // 12 Hour in terms of game cycles
const SellSharesCooldown = 18e3; // 1 Hour in terms of game cycles
const CyclesPerMarketCycle = 50;
const CyclesPerIndustryStateCycle = CyclesPerMarketCycle / _CorporationState__WEBPACK_IMPORTED_MODULE_0__["AllCorporationStates"].length;
const SecsPerMarketCycle = CyclesPerMarketCycle / 5;
const Cities = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"];
const WarehouseInitialCost = 5e9; //Initial purchase cost of warehouse
const WarehouseInitialSize = 100;
const WarehouseUpgradeBaseCost = 1e9;
const OfficeInitialCost = 4e9;
const OfficeInitialSize = 3;
const OfficeUpgradeBaseCost = 1e9;
const BribeThreshold = 100e12; //Money needed to be able to bribe for faction rep
const BribeToRepRatio = 1e9; //Bribe Value divided by this = rep gain
const ProductProductionCostRatio = 5; //Ratio of material cost of a product to its production cost
const DividendMaxPercentage = 50;
const EmployeeSalaryMultiplier = 3; // Employee stats multiplied by this to determine initial salary
const CyclesPerEmployeeRaise = 400; // All employees get a raise every X market cycles
const EmployeeRaiseAmount = 50; // Employee salary increases by this (additive)
const BaseMaxProducts = 3; // Initial value for maximum number of products allowed
// Delete Research Popup Box when clicking outside of it
let researchTreeBoxOpened = false;
let researchTreeBox = null;
$(document).mousedown(function (event) {
const boxId = "corporation-research-popup-box";
const contentId = "corporation-research-popup-box-content";
if (researchTreeBoxOpened) {
if ($(event.target).closest("#" + contentId).get(0) == null) {
// Delete the box
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_32__["removeElement"])(researchTreeBox);
researchTreeBox = null;
researchTreeBoxOpened = false;
}
}
});
var empManualAssignmentModeActive = false;
function Industry(params = {}) {
this.offices = {
//Maps locations to offices. 0 if no office at that location
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Aevum]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Chongqing]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Sector12]: new OfficeSpace({
loc: _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Sector12,
size: OfficeInitialSize
}),
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].NewTokyo]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Ishima]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Volhaven]: 0
};
this.name = params.name ? params.name : 0;
this.type = params.type ? params.type : 0;
this.sciResearch = new _Material__WEBPACK_IMPORTED_MODULE_6__["Material"]({
name: "Scientific Research"
});
this.researched = {}; // Object of acquired Research. Keys = research name
//A map of the NAME of materials required to create produced materials to
//how many are needed to produce 1 unit of produced materials
this.reqMats = {}; //An array of the name of materials being produced
this.prodMats = [];
this.products = {};
this.makesProducts = false;
this.awareness = 0;
this.popularity = 0; //Should always be less than awareness
this.startingCost = 0;
/* The following are factors for how much production/other things are increased by
different factors. The production increase always has diminishing returns,
and they are all reprsented by exponentials of < 1 (e.g x ^ 0.5, x ^ 0.8)
The number for these represent the exponential. A lower number means more
diminishing returns */
this.reFac = 0; //Real estate Factor
this.sciFac = 0; //Scientific Research Factor, affects quality
this.hwFac = 0; //Hardware factor
this.robFac = 0; //Robotics Factor
this.aiFac = 0; //AI Cores factor;
this.advFac = 0; //Advertising factor, affects sales
this.prodMult = 0; //Production multiplier
//Financials
this.lastCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0); //Upgrades
var numUpgrades = Object.keys(_IndustryUpgrades__WEBPACK_IMPORTED_MODULE_5__["IndustryUpgrades"]).length;
this.upgrades = Array(numUpgrades).fill(0);
this.state = "START";
this.newInd = true;
this.warehouses = {
//Maps locations to warehouses. 0 if no warehouse at that location
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Aevum]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Chonqing]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Sector12]: new _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]({
corp: params.corp,
industry: this,
loc: _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Sector12,
size: WarehouseInitialSize
}),
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].NewTokyo]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Ishima]: 0,
[_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_16__["CityName"].Volhaven]: 0
};
this.init();
}
Industry.prototype.init = function () {
//Set the unique properties of an industry (how much its affected by real estate/scientific research, etc.)
this.startingCost = _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryStartingCosts"][this.type];
switch (this.type) {
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Energy:
this.reFac = 0.65;
this.sciFac = 0.7;
this.robFac = 0.05;
this.aiFac = 0.3;
this.advFac = 0.08;
this.reqMats = {
"Hardware": 0.1,
"Metal": 0.2
};
this.prodMats = ["Energy"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Utilities:
case "Utilities":
this.reFac = 0.5;
this.sciFac = 0.6;
this.robFac = 0.4;
this.aiFac = 0.4;
this.advFac = 0.08;
this.reqMats = {
"Hardware": 0.1,
"Metal": 0.1
};
this.prodMats = ["Water"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Agriculture:
this.reFac = 0.72;
this.sciFac = 0.5;
this.hwFac = 0.2;
this.robFac = 0.3;
this.aiFac = 0.3;
this.advFac = 0.04;
this.reqMats = {
"Water": 0.5,
"Energy": 0.5
};
this.prodMats = ["Plants", "Food"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Fishing:
this.reFac = 0.15;
this.sciFac = 0.35;
this.hwFac = 0.35;
this.robFac = 0.5;
this.aiFac = 0.2;
this.advFac = 0.08;
this.reqMats = {
"Energy": 0.5
};
this.prodMats = ["Food"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Mining:
this.reFac = 0.3;
this.sciFac = 0.26;
this.hwFac = 0.4;
this.robFac = 0.45;
this.aiFac = 0.45;
this.advFac = 0.06;
this.reqMats = {
"Energy": 0.8
};
this.prodMats = ["Metal"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Food:
//reFac is unique for this bc it diminishes greatly per city. Handle this separately in code?
this.sciFac = 0.12;
this.hwFac = 0.15;
this.robFac = 0.3;
this.aiFac = 0.25;
this.advFac = 0.25;
this.reFac = 0.05;
this.reqMats = {
"Food": 0.5,
"Water": 0.5,
"Energy": 0.2
};
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Tobacco:
this.reFac = 0.15;
this.sciFac = 0.75;
this.hwFac = 0.15;
this.robFac = 0.2;
this.aiFac = 0.15;
this.advFac = 0.2;
this.reqMats = {
"Plants": 1,
"Water": 0.2
};
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Chemical:
this.reFac = 0.25;
this.sciFac = 0.75;
this.hwFac = 0.2;
this.robFac = 0.25;
this.aiFac = 0.2;
this.advFac = 0.07;
this.reqMats = {
"Plants": 1,
"Energy": 0.5,
"Water": 0.5
};
this.prodMats = ["Chemicals"];
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Pharmaceutical:
this.reFac = 0.05;
this.sciFac = 0.8;
this.hwFac = 0.15;
this.robFac = 0.25;
this.aiFac = 0.2;
this.advFac = 0.16;
this.reqMats = {
"Chemicals": 2,
"Energy": 1,
"Water": 0.5
};
this.prodMats = ["Drugs"];
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Computer:
case "Computer":
this.reFac = 0.2;
this.sciFac = 0.62;
this.robFac = 0.36;
this.aiFac = 0.19;
this.advFac = 0.17;
this.reqMats = {
"Metal": 2,
"Energy": 1
};
this.prodMats = ["Hardware"];
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Robotics:
this.reFac = 0.32;
this.sciFac = 0.65;
this.aiFac = 0.36;
this.advFac = 0.18;
this.hwFac = 0.19;
this.reqMats = {
"Hardware": 5,
"Energy": 3
};
this.prodMats = ["Robots"];
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Software:
this.sciFac = 0.62;
this.advFac = 0.16;
this.hwFac = 0.25;
this.reFac = 0.15;
this.aiFac = 0.18;
this.robFac = 0.05;
this.reqMats = {
"Hardware": 0.5,
"Energy": 0.5
};
this.prodMats = ["AICores"];
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Healthcare:
this.reFac = 0.1;
this.sciFac = 0.75;
this.advFac = 0.11;
this.hwFac = 0.1;
this.robFac = 0.1;
this.aiFac = 0.1;
this.reqMats = {
"Robots": 10,
"AICores": 5,
"Energy": 5,
"Water": 5
};
this.makesProducts = true;
break;
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].RealEstate:
this.robFac = 0.6;
this.aiFac = 0.6;
this.advFac = 0.25;
this.sciFac = 0.05;
this.hwFac = 0.05;
this.reqMats = {
"Metal": 5,
"Energy": 5,
"Water": 2,
"Hardware": 4
};
this.prodMats = ["RealEstate"];
this.makesProducts = true;
break;
default:
console.log("ERR: Invalid Industry Type passed into Industry.init(): " + this.type);
return;
}
};
Industry.prototype.getProductDescriptionText = function () {
if (!this.makesProducts) {
return;
}
switch (this.type) {
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Food:
return "create and manage restaurants";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Tobacco:
return "create tobacco and tobacco-related products";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Pharmaceutical:
return "develop new pharmaceutical drugs";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Computer:
case "Computer":
return "create new computer hardware and networking infrastructures";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Robotics:
return "build specialized robots and robot-related products";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Software:
return "develop computer software";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Healthcare:
return "build and manage hospitals";
case _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].RealEstate:
return "develop and manage real estate properties";
default:
console.log("ERROR: Invalid industry type in Industry.getProductDescriptionText");
return "";
}
};
Industry.prototype.getMaximumNumberProducts = function () {
if (!this.makesProducts) {
return 0;
} // Calculate additional number of allowed Products from Research/Upgrades
let additional = 0;
if (this.hasResearch("uPgrade: Capacity.I")) {
++additional;
}
if (this.hasResearch("uPgrade: Capacity.II")) {
++additional;
}
return BaseMaxProducts + additional;
};
Industry.prototype.hasMaximumNumberProducts = function () {
return Object.keys(this.products).length >= this.getMaximumNumberProducts();
}; //Calculates the values that factor into the production and properties of
//materials/products (such as quality, etc.)
Industry.prototype.calculateProductionFactors = function () {
var multSum = 0;
for (var i = 0; i < Cities.length; ++i) {
var city = Cities[i];
var warehouse = this.warehouses[city];
if (!(warehouse instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"])) {
continue;
}
var materials = warehouse.materials,
office = this.offices[city];
var cityMult = Math.pow(0.002 * materials.RealEstate.qty + 1, this.reFac) * Math.pow(0.002 * materials.Hardware.qty + 1, this.hwFac) * Math.pow(0.002 * materials.Robots.qty + 1, this.robFac) * Math.pow(0.002 * materials.AICores.qty + 1, this.aiFac);
multSum += Math.pow(cityMult, 0.73);
}
multSum < 1 ? this.prodMult = 1 : this.prodMult = multSum;
};
Industry.prototype.updateWarehouseSizeUsed = function (warehouse) {
if (warehouse instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]) {
//This resets the size back to 0 and then accounts for materials
warehouse.updateMaterialSizeUsed();
}
for (var prodName in this.products) {
if (this.products.hasOwnProperty(prodName)) {
var prod = this.products[prodName];
warehouse.sizeUsed += prod.data[warehouse.loc][0] * prod.siz;
if (prod.data[warehouse.loc][0] > 0) {
warehouse.breakdown += prodName + ": " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(prod.data[warehouse.loc][0] * prod.siz, 0) + " ";
}
}
}
};
Industry.prototype.process = function (marketCycles = 1, state, company) {
this.state = state; //At the start of a cycle, store and reset revenue/expenses
//Then calculate salaries and processs the markets
if (state === "START") {
if (isNaN(this.thisCycleRevenue) || isNaN(this.thisCycleExpenses)) {
console.log("ERROR: NaN in Corporation's computed revenue/expenses");
console.log(this.thisCycleRevenue.toString());
console.log(this.thisCycleExpenses.toString());
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Something went wrong when compting Corporation's revenue/expenses. This is a bug. Please report to game developer");
this.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
}
this.lastCycleRevenue = this.thisCycleRevenue.dividedBy(marketCycles * SecsPerMarketCycle);
this.lastCycleExpenses = this.thisCycleExpenses.dividedBy(marketCycles * SecsPerMarketCycle);
this.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0); // Once you start making revenue, the player should no longer be
// considered new, and therefore no longer needs the 'tutorial' UI elements
if (this.lastCycleRevenue.gt(0)) {
this.newInd = false;
} // Process offices (and the employees in them)
var employeeSalary = 0;
for (var officeLoc in this.offices) {
if (this.offices[officeLoc] instanceof OfficeSpace) {
employeeSalary += this.offices[officeLoc].process(marketCycles, {
industry: this,
corporation: company
});
}
}
this.thisCycleExpenses = this.thisCycleExpenses.plus(employeeSalary); // Process change in demand/competition of materials/products
this.processMaterialMarket(marketCycles);
this.processProductMarket(marketCycles); // Process loss of popularity
this.popularity -= marketCycles * .0001;
this.popularity = Math.max(0, this.popularity); // Process Dreamsense gains
var popularityGain = company.getDreamSenseGain(),
awarenessGain = popularityGain * 4;
if (popularityGain > 0) {
this.popularity += popularityGain * marketCycles;
this.awareness += awarenessGain * marketCycles;
}
return;
} // Process production, purchase, and import/export of materials
var res = this.processMaterials(marketCycles, company);
this.thisCycleRevenue = this.thisCycleRevenue.plus(res[0]);
this.thisCycleExpenses = this.thisCycleExpenses.plus(res[1]); // Process creation, production & sale of products
res = this.processProducts(marketCycles, company);
this.thisCycleRevenue = this.thisCycleRevenue.plus(res[0]);
this.thisCycleExpenses = this.thisCycleExpenses.plus(res[1]);
}; // Process change in demand and competition for this industry's materials
Industry.prototype.processMaterialMarket = function (marketCycles = 1) {
//References to prodMats and reqMats
var reqMats = this.reqMats,
prodMats = this.prodMats; //Only 'process the market' for materials that this industry deals with
for (var i = 0; i < Cities.length; ++i) {
//If this industry has a warehouse in this city, process the market
//for every material this industry requires or produces
if (this.warehouses[Cities[i]] instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]) {
var wh = this.warehouses[Cities[i]];
for (var name in reqMats) {
if (reqMats.hasOwnProperty(name)) {
wh.materials[name].processMarket();
}
} //Produced materials are stored in an array
for (var foo = 0; foo < prodMats.length; ++foo) {
wh.materials[prodMats[foo]].processMarket();
} //Process these twice because these boost production
wh.materials["Hardware"].processMarket();
wh.materials["Robots"].processMarket();
wh.materials["AICores"].processMarket();
wh.materials["RealEstate"].processMarket();
}
}
}; // Process change in demand and competition for this industry's products
Industry.prototype.processProductMarket = function (marketCycles = 1) {
// Demand gradually decreases, and competition gradually increases
for (const name in this.products) {
if (this.products.hasOwnProperty(name)) {
const product = this.products[name];
let change = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(0, 3) * 0.0004;
if (change === 0) {
continue;
}
if (this.type === _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Pharmaceutical || this.type === _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Software || this.type === _IndustryData__WEBPACK_IMPORTED_MODULE_4__["Industries"].Robotics) {
change *= 3;
}
change *= marketCycles;
product.dmd -= change;
product.cmp += change;
product.cmp = Math.min(product.cmp, 99.99);
product.dmd = Math.max(product.dmd, 0.001);
}
}
}; //Process production, purchase, and import/export of materials
Industry.prototype.processMaterials = function (marketCycles = 1, company) {
var revenue = 0,
expenses = 0,
industry = this;
this.calculateProductionFactors(); //At the start of the export state, set the imports of everything to 0
if (this.state === "EXPORT") {
for (let i = 0; i < Cities.length; ++i) {
var city = Cities[i],
office = this.offices[city];
if (!(this.warehouses[city] instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"])) {
continue;
}
var warehouse = this.warehouses[city];
for (var matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
var mat = warehouse.materials[matName];
mat.imp = 0;
}
}
}
}
for (let i = 0; i < Cities.length; ++i) {
var city = Cities[i],
office = this.offices[city];
if (this.warehouses[city] instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]) {
var warehouse = this.warehouses[city];
switch (this.state) {
case "PURCHASE":
/* Process purchase of materials */
for (var matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
(function (matName, ind) {
var mat = warehouse.materials[matName];
var buyAmt, maxAmt;
if (warehouse.smartSupplyEnabled && Object.keys(ind.reqMats).includes(matName)) {
//Smart supply tracker is stored as per second rate
mat.buy = ind.reqMats[matName] * warehouse.smartSupplyStore;
buyAmt = mat.buy * SecsPerMarketCycle * marketCycles;
} else {
buyAmt = mat.buy * SecsPerMarketCycle * marketCycles;
}
if (matName == "RealEstate") {
maxAmt = buyAmt;
} else {
maxAmt = Math.floor((warehouse.size - warehouse.sizeUsed) / _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__["MaterialSizes"][matName]);
}
var buyAmt = Math.min(buyAmt, maxAmt);
if (buyAmt > 0) {
mat.qty += buyAmt;
expenses += buyAmt * mat.bCost;
}
})(matName, industry);
this.updateWarehouseSizeUsed(warehouse);
}
} //End process purchase of materials
break;
case "PRODUCTION":
warehouse.smartSupplyStore = 0; //Reset smart supply amount
/* Process production of materials */
if (this.prodMats.length > 0) {
var mat = warehouse.materials[this.prodMats[0]]; //Calculate the maximum production of this material based
//on the office's productivity
var maxProd = this.getOfficeProductivity(office) * this.prodMult // Multiplier from materials
* company.getProductionMultiplier() * this.getProductionMultiplier(); // Multiplier from Research
let prod;
if (mat.prdman[0]) {
//Production is manually limited
prod = Math.min(maxProd, mat.prdman[1]);
} else {
prod = maxProd;
}
prod *= SecsPerMarketCycle * marketCycles; //Convert production from per second to per market cycle
// Calculate net change in warehouse storage making the produced materials will cost
var totalMatSize = 0;
for (let tmp = 0; tmp < this.prodMats.length; ++tmp) {
totalMatSize += _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__["MaterialSizes"][this.prodMats[tmp]];
}
for (const reqMatName in this.reqMats) {
var normQty = this.reqMats[reqMatName];
totalMatSize -= _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__["MaterialSizes"][reqMatName] * normQty;
} // If not enough space in warehouse, limit the amount of produced materials
if (totalMatSize > 0) {
var maxAmt = Math.floor((warehouse.size - warehouse.sizeUsed) / totalMatSize);
prod = Math.min(maxAmt, prod);
}
if (prod < 0) {
prod = 0;
} // Keep track of production for smart supply (/s)
warehouse.smartSupplyStore += prod / (SecsPerMarketCycle * marketCycles); // Make sure we have enough resource to make our materials
var producableFrac = 1;
for (var reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
var req = this.reqMats[reqMatName] * prod;
if (warehouse.materials[reqMatName].qty < req) {
producableFrac = Math.min(producableFrac, warehouse.materials[reqMatName].qty / req);
}
}
}
if (producableFrac <= 0) {
producableFrac = 0;
prod = 0;
} // Make our materials if they are producable
if (producableFrac > 0 && prod > 0) {
for (const reqMatName in this.reqMats) {
var reqMatQtyNeeded = this.reqMats[reqMatName] * prod * producableFrac;
warehouse.materials[reqMatName].qty -= reqMatQtyNeeded;
warehouse.materials[reqMatName].prd = 0;
warehouse.materials[reqMatName].prd -= reqMatQtyNeeded / (SecsPerMarketCycle * marketCycles);
}
for (let j = 0; j < this.prodMats.length; ++j) {
warehouse.materials[this.prodMats[j]].qty += prod * producableFrac;
warehouse.materials[this.prodMats[j]].qlt = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Engineer] / 90 + Math.pow(this.sciResearch.qty, this.sciFac) + Math.pow(warehouse.materials["AICores"].qty, this.aiFac) / 10e3;
}
} else {
for (const reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
warehouse.materials[reqMatName].prd = 0;
}
}
} //Per second
const fooProd = prod * producableFrac / (SecsPerMarketCycle * marketCycles);
for (let fooI = 0; fooI < this.prodMats.length; ++fooI) {
warehouse.materials[this.prodMats[fooI]].prd = fooProd;
}
} else {
//If this doesn't produce any materials, then it only creates
//Products. Creating products will consume materials. The
//Production of all consumed materials must be set to 0
for (const reqMatName in this.reqMats) {
warehouse.materials[reqMatName].prd = 0;
}
}
break;
case "SALE":
/* Process sale of materials */
for (var matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
var mat = warehouse.materials[matName];
if (mat.sCost < 0 || mat.sllman[0] === false) {
mat.sll = 0;
continue;
} // Sale multipliers
const businessFactor = this.getBusinessFactor(office); //Business employee productivity
const advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
const marketFactor = this.getMarketFactor(mat); //Competition + demand
// Determine the cost that the material will be sold at
const markupLimit = mat.getMarkupLimit();
var sCost;
if (mat.marketTa2) {
const prod = mat.prd; // Reverse engineer the 'maxSell' formula
// 1. Set 'maxSell' = prod
// 2. Substitute formula for 'markup'
// 3. Solve for 'sCost'
const numerator = markupLimit;
const sqrtNumerator = prod;
const sqrtDenominator = (mat.qlt + .001) * marketFactor * businessFactor * company.getSalesMultiplier() * advertisingFactor * this.getSalesMultiplier();
const denominator = Math.sqrt(sqrtNumerator / sqrtDenominator);
let optimalPrice;
if (sqrtDenominator === 0 || denominator === 0) {
if (sqrtNumerator === 0) {
optimalPrice = 0; // No production
} else {
optimalPrice = mat.bCost + markupLimit;
console.warn(`In Corporation, found illegal 0s when trying to calculate MarketTA2 sale cost`);
}
} else {
optimalPrice = numerator / denominator + mat.bCost;
} // We'll store this "Optimal Price" in a property so that we don't have
// to re-calculate it for the UI
mat.marketTa2Price = optimalPrice;
sCost = optimalPrice;
} else if (mat.marketTa1) {
sCost = mat.bCost + markupLimit;
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__["isString"])(mat.sCost)) {
sCost = mat.sCost.replace(/MP/g, mat.bCost);
sCost = eval(sCost);
} else {
sCost = mat.sCost;
} // Calculate how much of the material sells (per second)
let markup = 1;
if (sCost > mat.bCost) {
//Penalty if difference between sCost and bCost is greater than markup limit
if (sCost - mat.bCost > markupLimit) {
markup = Math.pow(markupLimit / (sCost - mat.bCost), 2);
}
} else if (sCost < mat.bCost) {
if (sCost <= 0) {
markup = 1e12; //Sell everything, essentially discard
} else {
//Lower prices than market increases sales
markup = mat.bCost / sCost;
}
}
var maxSell = (mat.qlt + .001) * marketFactor * markup * businessFactor * company.getSalesMultiplier() * advertisingFactor * this.getSalesMultiplier();
var sellAmt;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__["isString"])(mat.sllman[1])) {
//Dynamically evaluated
var tmp = mat.sllman[1].replace(/MAX/g, maxSell);
tmp = tmp.replace(/PROD/g, mat.prd);
try {
sellAmt = eval(tmp);
} catch (e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Error evaluating your sell amount for material " + mat.name + " in " + this.name + "'s " + city + " office. The sell amount " + "is being set to zero");
sellAmt = 0;
}
sellAmt = Math.min(maxSell, sellAmt);
} else if (mat.sllman[1] === -1) {
//Backwards compatibility, -1 = MAX
sellAmt = maxSell;
} else {
//Player's input value is just a number
sellAmt = Math.min(maxSell, mat.sllman[1]);
}
sellAmt = sellAmt * SecsPerMarketCycle * marketCycles;
sellAmt = Math.min(mat.qty, sellAmt);
if (sellAmt < 0) {
console.log("sellAmt calculated to be negative");
mat.sll = 0;
continue;
}
if (sellAmt && sCost >= 0) {
mat.qty -= sellAmt;
revenue += sellAmt * sCost;
mat.sll = sellAmt / (SecsPerMarketCycle * marketCycles);
} else {
mat.sll = 0;
}
}
} //End processing of sale of materials
break;
case "EXPORT":
for (var matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
var mat = warehouse.materials[matName];
mat.totalExp = 0; //Reset export
for (var expI = 0; expI < mat.exp.length; ++expI) {
var exp = mat.exp[expI];
var amt = exp.amt.replace(/MAX/g, mat.qty / (SecsPerMarketCycle * marketCycles));
try {
amt = eval(amt);
} catch (e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Calculating export for " + mat.name + " in " + this.name + "'s " + city + " division failed with " + "error: " + e);
continue;
}
if (isNaN(amt)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Error calculating export amount for " + mat.name + " in " + this.name + "'s " + city + " division.");
continue;
}
amt = amt * SecsPerMarketCycle * marketCycles;
if (mat.qty < amt) {
amt = mat.qty;
}
if (amt === 0) {
break; //None left
}
for (var foo = 0; foo < company.divisions.length; ++foo) {
if (company.divisions[foo].name === exp.ind) {
var expIndustry = company.divisions[foo];
var expWarehouse = expIndustry.warehouses[exp.city];
if (!(expWarehouse instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"])) {
console.log("ERROR: Invalid export! " + expIndustry.name + " " + exp.city);
break;
} //Make sure theres enough space in warehouse
if (expWarehouse.sizeUsed >= expWarehouse.size) {
return; //Warehouse at capacity
} else {
var maxAmt = Math.floor((expWarehouse.size - expWarehouse.sizeUsed) / _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__["MaterialSizes"][matName]);
amt = Math.min(maxAmt, amt);
}
expWarehouse.materials[matName].imp += amt / (SecsPerMarketCycle * marketCycles);
expWarehouse.materials[matName].qty += amt;
expWarehouse.materials[matName].qlt = mat.qlt;
mat.qty -= amt;
mat.totalExp += amt;
expIndustry.updateWarehouseSizeUsed(expWarehouse);
break;
}
}
} //totalExp should be per second
mat.totalExp /= SecsPerMarketCycle * marketCycles;
}
}
break;
case "START":
break;
default:
console.log("ERROR: Invalid state: " + this.state);
break;
} //End switch(this.state)
this.updateWarehouseSizeUsed(warehouse);
} // End warehouse
//Produce Scientific Research based on R&D employees
//Scientific Research can be produced without a warehouse
if (office instanceof OfficeSpace) {
this.sciResearch.qty += .004 * Math.pow(office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].RandD], 0.5) * company.getScientificResearchMultiplier() * this.getScientificResearchMultiplier();
}
}
return [revenue, expenses];
}; //Process production & sale of this industry's FINISHED products (including all of their stats)
Industry.prototype.processProducts = function (marketCycles = 1, corporation) {
var revenue = 0,
expenses = 0; //Create products
if (this.state === "PRODUCTION") {
for (const prodName in this.products) {
const prod = this.products[prodName];
if (!prod.fin) {
const city = prod.createCity;
const office = this.offices[city]; // Designing/Creating a Product is based mostly off Engineers
const engrProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Engineer];
const mgmtProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Management];
const opProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Operations];
const total = engrProd + mgmtProd + opProd;
if (total <= 0) {
break;
} // Management is a multiplier for the production from Engineers
const mgmtFactor = 1 + mgmtProd / (1.2 * total);
const progress = (Math.pow(engrProd, 0.34) + Math.pow(opProd, 0.2)) * mgmtFactor;
prod.createProduct(marketCycles, progress);
if (prod.prog >= 100) {
prod.finishProduct(office.employeeProd, this);
}
break;
}
}
} //Produce Products
for (var prodName in this.products) {
if (this.products.hasOwnProperty(prodName)) {
var prod = this.products[prodName];
if (prod instanceof _Product__WEBPACK_IMPORTED_MODULE_8__["Product"] && prod.fin) {
revenue += this.processProduct(marketCycles, prod, corporation);
}
}
}
return [revenue, expenses];
}; //Processes FINISHED products
Industry.prototype.processProduct = function (marketCycles = 1, product, corporation) {
let totalProfit = 0;
for (let i = 0; i < Cities.length; ++i) {
let city = Cities[i],
office = this.offices[city],
warehouse = this.warehouses[city];
if (warehouse instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]) {
switch (this.state) {
case "PRODUCTION":
//Calculate the maximum production of this material based
//on the office's productivity
var maxProd = this.getOfficeProductivity(office, {
forProduct: true
}) * corporation.getProductionMultiplier() * this.prodMult // Multiplier from materials
* this.getProductionMultiplier() // Multiplier from research
* this.getProductProductionMultiplier(); // Multiplier from research
let prod; //Account for whether production is manually limited
if (product.prdman[city][0]) {
prod = Math.min(maxProd, product.prdman[city][1]);
} else {
prod = maxProd;
}
prod *= SecsPerMarketCycle * marketCycles; //Calculate net change in warehouse storage making the Products will cost
var netStorageSize = product.siz;
for (var reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
var normQty = product.reqMats[reqMatName];
netStorageSize -= _MaterialSizes__WEBPACK_IMPORTED_MODULE_7__["MaterialSizes"][reqMatName] * normQty;
}
} //If there's not enough space in warehouse, limit the amount of Product
if (netStorageSize > 0) {
var maxAmt = Math.floor((warehouse.size - warehouse.sizeUsed) / netStorageSize);
prod = Math.min(maxAmt, prod);
}
warehouse.smartSupplyStore += prod / (SecsPerMarketCycle * marketCycles); //Make sure we have enough resources to make our Products
var producableFrac = 1;
for (var reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
var req = product.reqMats[reqMatName] * prod;
if (warehouse.materials[reqMatName].qty < req) {
producableFrac = Math.min(producableFrac, warehouse.materials[reqMatName].qty / req);
}
}
} //Make our Products if they are producable
if (producableFrac > 0 && prod > 0) {
for (var reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
var reqMatQtyNeeded = product.reqMats[reqMatName] * prod * producableFrac;
warehouse.materials[reqMatName].qty -= reqMatQtyNeeded;
warehouse.materials[reqMatName].prd -= reqMatQtyNeeded / (SecsPerMarketCycle * marketCycles);
}
} //Quantity
product.data[city][0] += prod * producableFrac;
} //Keep track of production Per second
product.data[city][1] = prod * producableFrac / (SecsPerMarketCycle * marketCycles);
break;
case "SALE":
//Process sale of Products
product.pCost = 0; //Estimated production cost
for (var reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
product.pCost += product.reqMats[reqMatName] * warehouse.materials[reqMatName].bCost;
}
} // Since its a product, its production cost is increased for labor
product.pCost *= ProductProductionCostRatio; // Sale multipliers
const businessFactor = this.getBusinessFactor(office); //Business employee productivity
const advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
const marketFactor = this.getMarketFactor(product); //Competition + demand
// Calculate Sale Cost (sCost), which could be dynamically evaluated
const markupLimit = product.rat / product.mku;
var sCost;
if (product.marketTa2) {
const prod = product.data[city][1]; // Reverse engineer the 'maxSell' formula
// 1. Set 'maxSell' = prod
// 2. Substitute formula for 'markup'
// 3. Solve for 'sCost'roduct.pCost = sCost
const numerator = markupLimit;
const sqrtNumerator = prod;
const sqrtDenominator = 0.5 * Math.pow(product.rat, 0.65) * marketFactor * corporation.getSalesMultiplier() * businessFactor * advertisingFactor * this.getSalesMultiplier();
const denominator = Math.sqrt(sqrtNumerator / sqrtDenominator);
let optimalPrice;
if (sqrtDenominator === 0 || denominator === 0) {
if (sqrtNumerator === 0) {
optimalPrice = 0; // No production
} else {
optimalPrice = product.pCost + markupLimit;
console.warn(`In Corporation, found illegal 0s when trying to calculate MarketTA2 sale cost`);
}
} else {
optimalPrice = numerator / denominator + product.pCost;
} // Store this "optimal Price" in a property so we don't have to re-calculate for UI
product.marketTa2Price[city] = optimalPrice;
sCost = optimalPrice;
} else if (product.marketTa1) {
sCost = product.pCost + markupLimit;
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__["isString"])(product.sCost)) {
sCost = product.sCost.replace(/MP/g, product.pCost + product.rat / product.mku);
sCost = eval(sCost);
} else {
sCost = product.sCost;
}
var markup = 1;
if (sCost > product.pCost) {
if (sCost - product.pCost > markupLimit) {
markup = markupLimit / (sCost - product.pCost);
}
}
var maxSell = 0.5 * Math.pow(product.rat, 0.65) * marketFactor * corporation.getSalesMultiplier() * Math.pow(markup, 2) * businessFactor * advertisingFactor * this.getSalesMultiplier();
var sellAmt;
if (product.sllman[city][0] && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__["isString"])(product.sllman[city][1])) {
//Sell amount is dynamically evaluated
var tmp = product.sllman[city][1].replace(/MAX/g, maxSell);
tmp = tmp.replace(/PROD/g, product.data[city][1]);
try {
tmp = eval(tmp);
} catch (e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Error evaluating your sell price expression for " + product.name + " in " + this.name + "'s " + city + " office. Sell price is being set to MAX");
tmp = maxSell;
}
sellAmt = Math.min(maxSell, tmp);
} else if (product.sllman[city][0] && product.sllman[city][1] > 0) {
//Sell amount is manually limited
sellAmt = Math.min(maxSell, product.sllman[city][1]);
} else if (product.sllman[city][0] === false) {
sellAmt = 0;
} else {
sellAmt = maxSell;
}
if (sellAmt < 0) {
sellAmt = 0;
}
sellAmt = sellAmt * SecsPerMarketCycle * marketCycles;
sellAmt = Math.min(product.data[city][0], sellAmt); //data[0] is qty
if (sellAmt && sCost) {
product.data[city][0] -= sellAmt; //data[0] is qty
totalProfit += sellAmt * sCost;
product.data[city][2] = sellAmt / (SecsPerMarketCycle * marketCycles); //data[2] is sell property
} else {
product.data[city][2] = 0; //data[2] is sell property
}
break;
case "START":
case "PURCHASE":
case "EXPORT":
break;
default:
console.log("ERROR: Invalid State: " + this.state);
break;
} //End switch(this.state)
}
}
return totalProfit;
};
Industry.prototype.discontinueProduct = function (product) {
for (var productName in this.products) {
if (this.products.hasOwnProperty(productName)) {
if (product === this.products[productName]) {
delete this.products[productName];
}
}
}
};
Industry.prototype.upgrade = function (upgrade, refs) {
var corporation = refs.corporation,
division = refs.division,
office = refs.office;
var upgN = upgrade[0],
basePrice = upgrade[1],
priceMult = upgrade[2],
upgradeBenefit = upgrade[3];
while (this.upgrades.length <= upgN) {
this.upgrades.push(0);
}
++this.upgrades[upgN];
switch (upgN) {
case 0:
//Coffee, 5% energy per employee
for (let i = 0; i < office.employees.length; ++i) {
office.employees[i].ene = Math.min(office.employees[i].ene * 1.05, office.maxEne);
}
break;
case 1:
//AdVert.Inc,
var advMult = corporation.getAdvertisingMultiplier() * this.getAdvertisingMultiplier();
this.awareness += 3 * advMult;
this.popularity += 1 * advMult;
this.awareness *= 1.01 * advMult;
this.popularity *= (1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(1, 3) / 100) * advMult;
break;
default:
console.log("ERROR: Un-implemented function index: " + upgN);
break;
}
}; // Returns how much of a material can be produced based of office productivity (employee stats)
Industry.prototype.getOfficeProductivity = function (office, params) {
const opProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Operations];
const engrProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Engineer];
const mgmtProd = office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Management];
const total = opProd + engrProd + mgmtProd;
if (total <= 0) {
return 0;
} // Management is a multiplier for the production from Operations and Engineers
const mgmtFactor = 1 + mgmtProd / (1.2 * total); // For production, Operations is slightly more important than engineering
// Both Engineering and Operations have diminishing returns
const prod = (Math.pow(opProd, 0.4) + Math.pow(engrProd, 0.3)) * mgmtFactor; // Generic multiplier for the production. Used for game-balancing purposes
const balancingMult = 0.05;
if (params && params.forProduct) {
// Products are harder to create and therefore have less production
return 0.5 * balancingMult * prod;
} else {
return balancingMult * prod;
}
}; // Returns a multiplier based on the office' 'Business' employees that affects sales
Industry.prototype.getBusinessFactor = function (office) {
const businessProd = 1 + office.employeeProd[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Business];
return Object(_utils_calculateEffectWithFactors__WEBPACK_IMPORTED_MODULE_20__["calculateEffectWithFactors"])(businessProd, 0.26, 10e3);
}; //Returns a set of multipliers based on the Industry's awareness, popularity, and advFac. This
//multiplier affects sales. The result is:
// [Total sales mult, total awareness mult, total pop mult, awareness/pop ratio mult]
Industry.prototype.getAdvertisingFactors = function () {
var awarenessFac = Math.pow(this.awareness + 1, this.advFac);
var popularityFac = Math.pow(this.popularity + 1, this.advFac);
var ratioFac = this.awareness === 0 ? 0.01 : Math.max((this.popularity + .001) / this.awareness, 0.01);
var totalFac = Math.pow(awarenessFac * popularityFac * ratioFac, 0.85);
return [totalFac, awarenessFac, popularityFac, ratioFac];
}; //Returns a multiplier based on a materials demand and competition that affects sales
Industry.prototype.getMarketFactor = function (mat) {
return Math.max(0.1, mat.dmd * (100 - mat.cmp) / 100);
}; // Returns a boolean indicating whether this Industry has the specified Research
Industry.prototype.hasResearch = function (name) {
return this.researched[name] === true;
};
Industry.prototype.updateResearchTree = function () {
const researchTree = _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type]; // Since ResearchTree data isnt saved, we'll update the Research Tree data
// based on the stored 'researched' property in the Industry object
if (Object.keys(researchTree.researched).length !== Object.keys(this.researched).length) {
console.log("Updating Corporation Research Tree Data");
for (let research in this.researched) {
researchTree.research(research);
}
}
}; // Get multipliers from Research
Industry.prototype.getAdvertisingMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getAdvertisingMultiplier();
};
Industry.prototype.getEmployeeChaMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getEmployeeChaMultiplier();
};
Industry.prototype.getEmployeeCreMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getEmployeeCreMultiplier();
};
Industry.prototype.getEmployeeEffMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getEmployeeEffMultiplier();
};
Industry.prototype.getEmployeeIntMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getEmployeeIntMultiplier();
};
Industry.prototype.getProductionMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getProductionMultiplier();
};
Industry.prototype.getProductProductionMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getProductProductionMultiplier();
};
Industry.prototype.getSalesMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getSalesMultiplier();
};
Industry.prototype.getScientificResearchMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getScientificResearchMultiplier();
};
Industry.prototype.getStorageMultiplier = function () {
this.updateResearchTree();
return _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type].getStorageMultiplier();
}; // Create the Research Tree UI for this Industry
Industry.prototype.createResearchBox = function () {
const boxId = "corporation-research-popup-box";
if (researchTreeBoxOpened) {
// It's already opened, so delete it to refresh content
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])(boxId);
researchTreeBox = null;
}
const researchTree = _IndustryData__WEBPACK_IMPORTED_MODULE_4__["IndustryResearchTrees"][this.type]; // Create the popup first, so that the tree diagram can be added to it
// This is handled by Treant
researchTreeBox = Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])(boxId, [], {
backgroundColor: "black"
}); // Get the tree's markup (i.e. config) for Treant
const markup = researchTree.createTreantMarkup();
markup.chart.container = "#" + boxId + "-content";
markup.chart.nodeAlign = "BOTTOM";
markup.chart.rootOrientation = "WEST";
markup.chart.siblingSeparation = 40;
markup.chart.connectors = {
type: "step",
style: {
"arrow-end": "block-wide-long",
"stroke": "white",
"stroke-width": 2
} // Construct the tree with Treant
};
const treantTree = new Treant(markup); // Add Event Listeners for all Nodes
const allResearch = researchTree.getAllNodes();
for (let i = 0; i < allResearch.length; ++i) {
// If this is already Researched, skip it
if (this.researched[allResearch[i]] === true) {
continue;
} // Get the Research object
const research = _ResearchMap__WEBPACK_IMPORTED_MODULE_9__["ResearchMap"][allResearch[i]]; // Get the DOM Element to add a click listener to it
const sanitizedName = allResearch[i].replace(/\s/g, '');
const div = document.getElementById(sanitizedName + "-corp-research-click-listener");
if (div == null) {
console.warn(`Could not find Research Tree div for ${sanitizedName}`);
continue;
}
div.addEventListener("click", () => {
if (this.sciResearch.qty >= research.cost) {
this.sciResearch.qty -= research.cost; // Get the Node from the Research Tree and set its 'researched' property
researchTree.research(allResearch[i]);
this.researched[allResearch[i]] = true;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])(`Researched ${allResearch[i]}. It may take a market cycle ` + `(~${SecsPerMarketCycle} seconds) before the effects of ` + `the Research apply.`);
return this.createResearchBox();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])(`You do not have enough Scientific Research for ${research.name}`);
}
});
}
const boxContent = document.getElementById(`${boxId}-content`);
if (boxContent != null) {
// Add information about multipliers from research at the bottom of the popup
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(boxContent, 2);
boxContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", {
display: "block",
innerText: `Multipliers from research:\n` + ` * Advertising Multiplier: x${researchTree.getAdvertisingMultiplier()}\n` + ` * Employee Charisma Multiplier: x${researchTree.getEmployeeChaMultiplier()}\n` + ` * Employee Creativity Multiplier: x${researchTree.getEmployeeCreMultiplier()}\n` + ` * Employee Efficiency Multiplier: x${researchTree.getEmployeeEffMultiplier()}\n` + ` * Employee Intelligence Multiplier: x${researchTree.getEmployeeIntMultiplier()}\n` + ` * Production Multiplier: x${researchTree.getProductionMultiplier()}\n` + ` * Sales Multiplier: x${researchTree.getSalesMultiplier()}\n` + ` * Scientific Research Multiplier: x${researchTree.getScientificResearchMultiplier()}\n` + ` * Storage Multiplier: x${researchTree.getStorageMultiplier()}`
})); // Close button
boxContent.appendChild(Object(_utils_uiHelpers_createPopupCloseButton__WEBPACK_IMPORTED_MODULE_27__["createPopupCloseButton"])(researchTreeBox, {
class: "std-button",
display: "block",
innerText: "Close"
}));
}
researchTreeBoxOpened = true;
};
Industry.prototype.toJSON = function () {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_toJSON"])("Industry", this);
};
Industry.fromJSON = function (value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_fromJSON"])(Industry, value.data);
};
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Reviver"].constructors.Industry = Industry;
function Employee(params = {}) {
if (!(this instanceof Employee)) {
return new Employee(params);
}
this.name = params.name ? params.name : "Bobby"; //Morale, happiness, and energy are 0-100
this.mor = params.morale ? params.morale : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100);
this.hap = params.happiness ? params.happiness : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100);
this.ene = params.energy ? params.energy : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100);
this.int = params.intelligence ? params.intelligence : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(10, 50);
this.cha = params.charisma ? params.charisma : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(10, 50);
this.exp = params.experience ? params.experience : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(10, 50);
this.cre = params.creativity ? params.creativity : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(10, 50);
this.eff = params.efficiency ? params.efficiency : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(10, 50);
this.sal = params.salary ? params.salary : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(0.1, 5);
this.pro = 0; //Productivity, This is calculated
this.cyclesUntilRaise = CyclesPerEmployeeRaise;
this.loc = params.loc ? params.loc : "";
this.pos = _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Unassigned;
} //Returns the amount the employee needs to be paid
Employee.prototype.process = function (marketCycles = 1, office) {
var gain = 0.003 * marketCycles,
det = gain * Math.random();
this.exp += gain; // Employee salaries slowly go up over time
this.cyclesUntilRaise -= marketCycles;
if (this.cyclesUntilRaise <= 0) {
this.salary += EmployeeRaiseAmount;
this.cyclesUntilRaise += CyclesPerEmployeeRaise;
} //Training
var trainingEff = gain * Math.random();
if (this.pos === _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Training) {
//To increase creativity and intelligence special upgrades are needed
this.cha += trainingEff;
this.exp += trainingEff;
this.eff += trainingEff;
}
this.ene -= det;
this.hap -= det;
if (this.ene < office.minEne) {
this.ene = office.minEne;
}
if (this.hap < office.minHap) {
this.hap = office.minHap;
}
var salary = this.sal * marketCycles * SecsPerMarketCycle;
return salary;
};
Employee.prototype.calculateProductivity = function (corporation, industry) {
var effCre = this.cre * corporation.getEmployeeCreMultiplier() * industry.getEmployeeCreMultiplier(),
effCha = this.cha * corporation.getEmployeeChaMultiplier() * industry.getEmployeeChaMultiplier(),
effInt = this.int * corporation.getEmployeeIntMultiplier() * industry.getEmployeeIntMultiplier(),
effEff = this.eff * corporation.getEmployeeEffMultiplier() * industry.getEmployeeEffMultiplier();
const prodBase = this.mor * this.hap * this.ene * 1e-6;
let prodMult;
switch (this.pos) {
//Calculate productivity based on position. This is multipled by prodBase
//to get final value
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Operations:
prodMult = 0.6 * effInt + 0.1 * effCha + this.exp + 0.5 * effCre + effEff;
break;
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Engineer:
prodMult = effInt + 0.1 * effCha + 1.5 * this.exp + effEff;
break;
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Business:
prodMult = 0.4 * effInt + effCha + 0.5 * this.exp;
break;
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Management:
prodMult = 2 * effCha + this.exp + 0.2 * effCre + 0.7 * effEff;
break;
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].RandD:
prodMult = 1.5 * effInt + 0.8 * this.exp + effCre + 0.5 * effEff;
break;
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Unassigned:
case _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Training:
prodMult = 0;
break;
default:
console.log("ERROR: Invalid employee position: " + this.pos);
break;
}
return prodBase * prodMult;
}; //Process benefits from having an office party thrown
Employee.prototype.throwParty = function (money) {
var mult = 1 + money / 10e6;
this.mor *= mult;
this.mor = Math.min(100, this.mor);
this.hap *= mult;
this.hap = Math.min(100, this.hap);
return mult;
}; //'panel' is the DOM element on which to create the UI
Employee.prototype.createUI = function (panel, corporation, industry) {
var effCre = this.cre * corporation.getEmployeeCreMultiplier() * industry.getEmployeeCreMultiplier(),
effCha = this.cha * corporation.getEmployeeChaMultiplier() * industry.getEmployeeChaMultiplier(),
effInt = this.int * corporation.getEmployeeIntMultiplier() * industry.getEmployeeIntMultiplier(),
effEff = this.eff * corporation.getEmployeeEffMultiplier() * industry.getEmployeeEffMultiplier();
panel.style.color = "white";
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
id: "cmpy-mgmt-employee-" + this.name + "-panel-text",
innerHTML: "Morale: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(this.mor, 3) + " " + "Happiness: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(this.hap, 3) + " " + "Energy: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(this.ene, 3) + " " + "Intelligence: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(effInt, 3) + " " + "Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(effCha, 3) + " " + "Experience: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(this.exp, 3) + " " + "Creativity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(effCre, 3) + " " + "Efficiency: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(effEff, 3) + " " + "Salary: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(this.sal, "$0.000a") + "/ s "
})); //Selector for employee position
var selector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("select", {});
for (var key in _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"]) {
if (_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].hasOwnProperty(key)) {
selector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("option", {
text: _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"][key],
value: _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"][key]
}));
}
}
selector.addEventListener("change", () => {
this.pos = selector.options[selector.selectedIndex].value;
}); //Set initial value of selector
for (var i = 0; i < selector.length; ++i) {
if (selector.options[i].value === this.pos) {
selector.selectedIndex = i;
break;
}
}
panel.appendChild(selector);
};
Employee.prototype.toJSON = function () {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_toJSON"])("Employee", this);
};
Employee.fromJSON = function (value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_fromJSON"])(Employee, value.data);
};
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Reviver"].constructors.Employee = Employee;
var OfficeSpaceTiers = {
Basic: "Basic",
Enhanced: "Enhanced",
Luxurious: "Luxurious",
Extravagant: "Extravagant"
};
function OfficeSpace(params = {}) {
this.loc = params.loc ? params.loc : "";
this.cost = params.cost ? params.cost : 1;
this.size = params.size ? params.size : 1;
this.comf = params.comfort ? params.comfort : 1;
this.beau = params.beauty ? params.beauty : 1;
this.tier = OfficeSpaceTiers.Basic; // Min/max energy of employees
this.minEne = 0;
this.maxEne = 100; // Min/max Happiness of office
this.minHap = 0;
this.maxHap = 100; // Maximum Morale of office
this.maxMor = 100;
this.employees = [];
this.employeeProd = {
[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Operations]: 0,
[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Engineer]: 0,
[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Business]: 0,
[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Management]: 0,
[_EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].RandD]: 0,
total: 0
};
}
OfficeSpace.prototype.atCapacity = function () {
return this.employees.length >= this.size;
};
OfficeSpace.prototype.process = function (marketCycles = 1, parentRefs) {
var corporation = parentRefs.corporation,
industry = parentRefs.industry; // HRBuddy AutoRecruitment and training
if (industry.hasResearch("HRBuddy-Recruitment") && !this.atCapacity()) {
const emp = this.hireRandomEmployee();
if (industry.hasResearch("HRBuddy-Training")) {
emp.pos = _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Training;
}
} // Process Office properties
this.maxEne = 100;
this.maxHap = 100;
this.maxMor = 100;
if (industry.hasResearch("Go-Juice")) {
this.maxEne += 10;
}
if (industry.hasResearch("JoyWire")) {
this.maxHap += 10;
}
if (industry.hasResearch("Sti.mu")) {
this.maxMor += 10;
} // Calculate changes in Morale/Happiness/Energy for Employees
var perfMult = 1; //Multiplier for employee morale/happiness/energy based on company performance
if (industry.funds < 0 && industry.lastCycleRevenue < 0) {
perfMult = Math.pow(0.99, marketCycles);
} else if (industry.funds > 0 && industry.lastCycleRevenue > 0) {
perfMult = Math.pow(1.01, marketCycles);
}
const hasAutobrew = industry.hasResearch("AutoBrew");
const hasAutoparty = industry.hasResearch("AutoPartyManager");
var salaryPaid = 0;
for (let i = 0; i < this.employees.length; ++i) {
const emp = this.employees[i];
if (hasAutoparty) {
emp.mor = this.maxMor;
emp.hap = this.maxHap;
} else {
emp.mor *= perfMult;
emp.hap *= perfMult;
emp.mor = Math.min(emp.mor, this.maxMor);
emp.hap = Math.min(emp.hap, this.maxHap);
}
if (hasAutobrew) {
emp.ene = this.maxEne;
} else {
emp.ene *= perfMult;
emp.ene = Math.min(emp.ene, this.maxEne);
}
const salary = emp.process(marketCycles, this);
salaryPaid += salary;
}
this.calculateEmployeeProductivity(parentRefs);
return salaryPaid;
};
OfficeSpace.prototype.calculateEmployeeProductivity = function (parentRefs) {
var company = parentRefs.corporation,
industry = parentRefs.industry; //Reset
for (const name in this.employeeProd) {
this.employeeProd[name] = 0;
}
var total = 0;
for (let i = 0; i < this.employees.length; ++i) {
const employee = this.employees[i];
const prod = employee.calculateProductivity(company, industry);
this.employeeProd[employee.pos] += prod;
total += prod;
}
this.employeeProd["total"] = total;
}; //Takes care of UI as well
OfficeSpace.prototype.findEmployees = function (parentRefs) {
var company = parentRefs.corporation,
division = parentRefs.industry;
if (this.atCapacity()) {
return;
}
if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null) {
return;
} //Generate three random employees (meh, decent, amazing)
var mult1 = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(25, 50) / 100,
mult2 = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(51, 75) / 100,
mult3 = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(76, 100) / 100;
var int = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
cha = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
exp = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
cre = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
eff = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
sal = EmployeeSalaryMultiplier * (int + cha + exp + cre + eff);
var emp1 = new Employee({
intelligence: int * mult1,
charisma: cha * mult1,
experience: exp * mult1,
creativity: cre * mult1,
efficiency: eff * mult1,
salary: sal * mult1
});
var emp2 = new Employee({
intelligence: int * mult2,
charisma: cha * mult2,
experience: exp * mult2,
creativity: cre * mult2,
efficiency: eff * mult2,
salary: sal * mult2
});
var emp3 = new Employee({
intelligence: int * mult3,
charisma: cha * mult3,
experience: exp * mult3,
creativity: cre * mult3,
efficiency: eff * mult3,
salary: sal * mult3
});
var text = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h1", {
innerHTML: "Select one of the following candidates for hire:"
});
var createEmpDiv = function (employee, office) {
var div = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class: "cmpy-mgmt-find-employee-option",
innerHTML: "Intelligence: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(employee.int, 1) + " " + "Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(employee.cha, 1) + " " + "Experience: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(employee.exp, 1) + " " + "Creativity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(employee.cre, 1) + " " + "Efficiency: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["formatNumber"])(employee.eff, 1) + " " + "Salary: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(employee.sal, '$0.000a') + " \ s ",
clickListener: () => {
office.hireEmployee(employee, parentRefs);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])("cmpy-mgmt-hire-employee-popup");
return false;
}
});
return div;
};
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
class: "a-link-button",
innerText: "Cancel",
float: "right",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])("cmpy-mgmt-hire-employee-popup");
return false;
}
});
var elems = [text, createEmpDiv(emp1, this), createEmpDiv(emp2, this), createEmpDiv(emp3, this), cancelBtn];
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])("cmpy-mgmt-hire-employee-popup", elems);
};
OfficeSpace.prototype.hireEmployee = function (employee, parentRefs) {
var company = parentRefs.corporation,
division = parentRefs.industry;
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxGetYesButton"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxGetNoButton"])();
yesBtn.innerHTML = "Hire";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", () => {
var name = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxGetInput"])();
for (var i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("You already have an employee with this nickname! Please give every employee a unique nickname.");
return false;
}
}
employee.name = name;
this.employees.push(employee);
company.rerender();
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxClose"])();
});
noBtn.addEventListener("click", () => {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxClose"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoTxtInpBoxCreate"])("Give your employee a nickname!");
};
OfficeSpace.prototype.hireRandomEmployee = function () {
if (this.atCapacity()) {
return;
}
if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null) {
return;
} //Generate three random employees (meh, decent, amazing)
var mult = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(76, 100) / 100;
var int = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
cha = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
exp = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
cre = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
eff = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_29__["getRandomInt"])(50, 100),
sal = EmployeeSalaryMultiplier * (int + cha + exp + cre + eff);
var emp = new Employee({
intelligence: int * mult,
charisma: cha * mult,
experience: exp * mult,
creativity: cre * mult,
efficiency: eff * mult,
salary: sal * mult
});
var name = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_28__["generateRandomString"])(7);
for (let i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
return this.hireRandomEmployee();
}
}
emp.name = name;
this.employees.push(emp);
return emp;
}; //Finds the first unassigned employee and assigns its to the specified job
OfficeSpace.prototype.assignEmployeeToJob = function (job) {
for (var i = 0; i < this.employees.length; ++i) {
if (this.employees[i].pos === _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Unassigned) {
this.employees[i].pos = job;
return true;
}
}
return false;
}; //Finds the first employee with the given job and unassigns it
OfficeSpace.prototype.unassignEmployeeFromJob = function (job) {
for (var i = 0; i < this.employees.length; ++i) {
if (this.employees[i].pos === job) {
this.employees[i].pos = _EmployeePositions__WEBPACK_IMPORTED_MODULE_3__["EmployeePositions"].Unassigned;
return true;
}
}
return false;
};
OfficeSpace.prototype.toJSON = function () {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_toJSON"])("OfficeSpace", this);
};
OfficeSpace.fromJSON = function (value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_fromJSON"])(OfficeSpace, value.data);
};
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Reviver"].constructors.OfficeSpace = OfficeSpace;
function Corporation(params = {}) {
this.name = params.name ? params.name : "The Corporation"; //A division/business sector is represented by the object:
this.divisions = []; //Financial stats
this.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](150e9);
this.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.fundingRound = 0;
this.public = false; //Publicly traded
this.totalShares = INITIALSHARES; // Total existing shares
this.numShares = INITIALSHARES; // Total shares owned by player
this.shareSalesUntilPriceUpdate = SHARESPERPRICEUPDATE;
this.shareSaleCooldown = 0; // Game cycles until player can sell shares again
this.issueNewSharesCooldown = 0; // Game cycles until player can issue shares again
this.dividendPercentage = 0;
this.dividendTaxPercentage = 50;
this.issuedShares = 0;
this.sharePrice = 0;
this.storedCycles = 0;
var numUnlockUpgrades = Object.keys(_data_CorporationUnlockUpgrades__WEBPACK_IMPORTED_MODULE_1__["CorporationUnlockUpgrades"]).length,
numUpgrades = Object.keys(_data_CorporationUpgrades__WEBPACK_IMPORTED_MODULE_2__["CorporationUpgrades"]).length;
this.unlockUpgrades = Array(numUnlockUpgrades).fill(0);
this.upgrades = Array(numUpgrades).fill(0);
this.upgradeMultipliers = Array(numUpgrades).fill(1);
this.state = new _CorporationState__WEBPACK_IMPORTED_MODULE_0__["CorporationState"]();
}
Corporation.prototype.getState = function () {
return this.state.getState();
};
Corporation.prototype.storeCycles = function (numCycles = 1) {
this.storedCycles += numCycles;
};
Corporation.prototype.process = function () {
var corp = this;
if (this.storedCycles >= CyclesPerIndustryStateCycle) {
const state = this.getState();
const marketCycles = 1;
const gameCycles = marketCycles * CyclesPerIndustryStateCycle;
this.storedCycles -= gameCycles;
this.divisions.forEach(function (ind) {
ind.process(marketCycles, state, corp);
}); // Process cooldowns
if (this.shareSaleCooldown > 0) {
this.shareSaleCooldown -= gameCycles;
}
if (this.issueNewSharesCooldown > 0) {
this.issueNewSharesCooldown -= gameCycles;
} //At the start of a new cycle, calculate profits from previous cycle
if (state === "START") {
this.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](0);
this.divisions.forEach(ind => {
if (ind.lastCycleRevenue === -Infinity || ind.lastCycleRevenue === Infinity) {
return;
}
if (ind.lastCycleExpenses === -Infinity || ind.lastCycleExpenses === Infinity) {
return;
}
this.revenue = this.revenue.plus(ind.lastCycleRevenue);
this.expenses = this.expenses.plus(ind.lastCycleExpenses);
});
var profit = this.revenue.minus(this.expenses);
const cycleProfit = profit.times(marketCycles * SecsPerMarketCycle);
if (isNaN(this.funds)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("There was an error calculating your Corporations funds and they got reset to 0. " + "This is a bug. Please report to game developer.
" + "(Your funds have been set to $150b for the inconvenience)");
this.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_40__[/* default */ "a"](150e9);
} // Process dividends
if (this.dividendPercentage > 0 && cycleProfit > 0) {
// Validate input again, just to be safe
if (isNaN(this.dividendPercentage) || this.dividendPercentage < 0 || this.dividendPercentage > DividendMaxPercentage) {
console.error(`Invalid Corporation dividend percentage: ${this.dividendPercentage}`);
} else {
const totalDividends = this.dividendPercentage / 100 * cycleProfit;
const retainedEarnings = cycleProfit - totalDividends;
const dividendsPerShare = totalDividends / this.totalShares;
const profit = this.numShares * dividendsPerShare * (1 - this.dividendTaxPercentage / 100);
_Player__WEBPACK_IMPORTED_MODULE_17__["Player"].gainMoney(profit);
_Player__WEBPACK_IMPORTED_MODULE_17__["Player"].recordMoneySource(profit, "corporation");
this.funds = this.funds.plus(retainedEarnings);
}
} else {
this.funds = this.funds.plus(cycleProfit);
}
this.updateSharePrice();
}
this.state.nextState();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["Page"].Corporation)) {
this.rerender();
}
}
};
Corporation.prototype.determineValuation = function () {
var val,
profit = this.revenue.minus(this.expenses).toNumber();
if (this.public) {
// Account for dividends
if (this.dividendPercentage > 0) {
profit *= (100 - this.dividendPercentage) / 100;
}
val = this.funds.toNumber() + profit * 85e3;
val *= Math.pow(1.1, this.divisions.length);
val = Math.max(val, 0);
} else {
val = 10e9 + Math.max(this.funds.toNumber(), 0) / 3; //Base valuation
if (profit > 0) {
val += profit * 315e3;
val *= Math.pow(1.1, this.divisions.length);
} else {
val = 10e9 * Math.pow(1.1, this.divisions.length);
}
val -= val % 1e6; //Round down to nearest millionth
}
return val * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_11__["BitNodeMultipliers"].CorporationValuation;
};
Corporation.prototype.getInvestment = function () {
var val = this.determineValuation(),
percShares;
let roundMultiplier = 4;
switch (this.fundingRound) {
case 0:
//Seed
percShares = 0.10;
roundMultiplier = 4;
break;
case 1:
//Series A
percShares = 0.35;
roundMultiplier = 3;
break;
case 2:
//Series B
percShares = 0.25;
roundMultiplier = 3;
break;
case 3:
//Series C
percShares = 0.20;
roundMultiplier = 2.5;
break;
case 4:
return;
}
var funding = val * percShares * roundMultiplier,
investShares = Math.floor(INITIALSHARES * percShares),
yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoBoxGetYesButton"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoBoxGetNoButton"])();
yesBtn.innerHTML = "Accept";
noBtn.innerHML = "Reject";
yesBtn.addEventListener("click", () => {
++this.fundingRound;
this.funds = this.funds.plus(funding);
this.numShares -= investShares;
this.rerender();
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoBoxClose"])();
});
noBtn.addEventListener("click", () => {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoBoxClose"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_34__["yesNoBoxCreate"])("An investment firm has offered you " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(funding, '$0.000a') + " in funding in exchange for a " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(percShares * 100, "0.000a") + "% stake in the company (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(investShares, '0.000a') + " shares).
" + "Do you accept or reject this offer?
" + "Hint: Investment firms will offer more money if your corporation is turning a profit");
};
Corporation.prototype.goPublic = function () {
var goPublicPopupId = "cmpy-mgmt-go-public-popup";
var initialSharePrice = this.determineValuation() / this.totalShares;
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerHTML: "Enter the number of shares you would like to issue " + "for your IPO. These shares will be publicly sold " + "and you will no longer own them. Your Corporation will receive " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(initialSharePrice, '$0.000a') + " per share " + "(the IPO money will be deposited directly into your Corporation's funds).
" + "You have a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(this.numShares, "0.000a") + " of shares that you can issue."
});
var yesBtn;
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", {
type: "number",
placeholder: "Shares to issue",
onkeyup: e => {
e.preventDefault();
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_31__["KEY"].ENTER) {
yesBtn.click();
}
}
});
var br = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("br", {});
yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
class: "a-link-button",
innerText: "Go Public",
clickListener: () => {
var numShares = Math.round(input.value);
var initialSharePrice = this.determineValuation() / this.totalShares;
if (isNaN(numShares)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Invalid value for number of issued shares");
return false;
}
if (numShares > this.numShares) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("Error: You don't have that many shares to issue!");
return false;
}
this.public = true;
this.sharePrice = initialSharePrice;
this.issuedShares = numShares;
this.numShares -= numShares;
this.funds = this.funds.plus(numShares * initialSharePrice);
this.rerender();
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])(goPublicPopupId);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])(`You took your ${this.name} public and earned ` + `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].formatMoney(numShares * initialSharePrice)} in your IPO`);
return false;
}
});
var noBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
class: "a-link-button",
innerText: "Cancel",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])(goPublicPopupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])(goPublicPopupId, [txt, br, input, yesBtn, noBtn]);
};
Corporation.prototype.getTargetSharePrice = function () {
// Note: totalShares - numShares is not the same as issuedShares because
// issuedShares does not account for private investors
return this.determineValuation() / (2 * (this.totalShares - this.numShares) + 1);
};
Corporation.prototype.updateSharePrice = function () {
const targetPrice = this.getTargetSharePrice();
if (this.sharePrice <= targetPrice) {
this.sharePrice *= 1 + Math.random() * 0.01;
} else {
this.sharePrice *= 1 - Math.random() * 0.01;
}
if (this.sharePrice <= 0.01) {
this.sharePrice = 0.01;
}
};
Corporation.prototype.immediatelyUpdateSharePrice = function () {
this.sharePrice = this.getTargetSharePrice();
}; // Calculates how much money will be made and what the resulting stock price
// will be when the player sells his/her shares
// @return - [Player profit, final stock price, end shareSalesUntilPriceUpdate property]
Corporation.prototype.calculateShareSale = function (numShares) {
let sharesTracker = numShares;
let sharesUntilUpdate = this.shareSalesUntilPriceUpdate;
let sharePrice = this.sharePrice;
let sharesSold = 0;
let profit = 0;
const maxIterations = Math.ceil(numShares / SHARESPERPRICEUPDATE);
if (isNaN(maxIterations) || maxIterations > 10e6) {
console.error(`Something went wrong or unexpected when calculating share sale. Maxiterations calculated to be ${maxIterations}`);
return;
}
for (let i = 0; i < maxIterations; ++i) {
if (sharesTracker < sharesUntilUpdate) {
profit += sharePrice * sharesTracker;
sharesUntilUpdate -= sharesTracker;
break;
} else {
profit += sharePrice * sharesUntilUpdate;
sharesUntilUpdate = SHARESPERPRICEUPDATE;
sharesTracker -= sharesUntilUpdate;
sharesSold += sharesUntilUpdate; // Calculate what new share price would be
sharePrice = this.determineValuation() / (2 * (this.totalShares + sharesSold - this.numShares));
}
}
return [profit, sharePrice, sharesUntilUpdate];
};
Corporation.prototype.convertCooldownToString = function (cd) {
// The cooldown value is based on game cycles. Convert to a simple string
const CyclesPerSecond = 1000 / _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MilliPerCycle;
const seconds = cd / 5;
const SecondsPerMinute = 60;
const SecondsPerHour = 3600;
if (seconds > SecondsPerHour) {
return `${Math.floor(seconds / SecondsPerHour)} hour(s)`;
} else if (seconds > SecondsPerMinute) {
return `${Math.floor(seconds / SecondsPerMinute)} minute(s)`;
} else {
return `${Math.floor(seconds)} second(s)`;
}
}; //One time upgrades that unlock new features
Corporation.prototype.unlock = function (upgrade) {
const upgN = upgrade[0],
price = upgrade[1];
while (this.unlockUpgrades.length <= upgN) {
this.unlockUpgrades.push(0);
}
if (this.funds.lt(price)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("You don't have enough funds to unlock this!");
return;
}
this.unlockUpgrades[upgN] = 1;
this.funds = this.funds.minus(price); // Apply effects for one-time upgrades
if (upgN === 5) {
this.dividendTaxPercentage -= 5;
} else if (upgN === 6) {
this.dividendTaxPercentage -= 10;
}
}; //Levelable upgrades
Corporation.prototype.upgrade = function (upgrade) {
var upgN = upgrade[0],
basePrice = upgrade[1],
priceMult = upgrade[2],
upgradeAmt = upgrade[3]; //Amount by which the upgrade multiplier gets increased (additive)
while (this.upgrades.length <= upgN) {
this.upgrades.push(0);
}
while (this.upgradeMultipliers.length <= upgN) {
this.upgradeMultipliers.push(1);
}
var totalCost = basePrice * Math.pow(priceMult, this.upgrades[upgN]);
if (this.funds.lt(totalCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_21__["dialogBoxCreate"])("You don't have enough funds to purchase this!");
return;
}
++this.upgrades[upgN];
this.funds = this.funds.minus(totalCost); //Increase upgrade multiplier
this.upgradeMultipliers[upgN] = 1 + this.upgrades[upgN] * upgradeAmt; //If storage size is being updated, update values in Warehouse objects
if (upgN === 1) {
for (var i = 0; i < this.divisions.length; ++i) {
var industry = this.divisions[i];
for (var city in industry.warehouses) {
if (industry.warehouses.hasOwnProperty(city) && industry.warehouses[city] instanceof _Warehouse__WEBPACK_IMPORTED_MODULE_10__["Warehouse"]) {
industry.warehouses[city].updateSize(this, industry);
}
}
}
}
};
Corporation.prototype.getProductionMultiplier = function () {
var mult = this.upgradeMultipliers[0];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getStorageMultiplier = function () {
var mult = this.upgradeMultipliers[1];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getDreamSenseGain = function () {
var gain = this.upgradeMultipliers[2] - 1;
return gain <= 0 ? 0 : gain;
};
Corporation.prototype.getAdvertisingMultiplier = function () {
var mult = this.upgradeMultipliers[3];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getEmployeeCreMultiplier = function () {
var mult = this.upgradeMultipliers[4];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getEmployeeChaMultiplier = function () {
var mult = this.upgradeMultipliers[5];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getEmployeeIntMultiplier = function () {
var mult = this.upgradeMultipliers[6];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getEmployeeEffMultiplier = function () {
var mult = this.upgradeMultipliers[7];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getSalesMultiplier = function () {
var mult = this.upgradeMultipliers[8];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
};
Corporation.prototype.getScientificResearchMultiplier = function () {
var mult = this.upgradeMultipliers[9];
if (isNaN(mult) || mult < 1) {
return 1;
} else {
return mult;
}
}; // Adds the Corporation Handbook (Starter Guide) to the player's home computer.
// This is a lit file that gives introductory info to the player
// This occurs when the player clicks the "Getting Started Guide" button on the overview panel
Corporation.prototype.getStarterGuide = function () {
// Check if player already has Corporation Handbook
let homeComp = _Player__WEBPACK_IMPORTED_MODULE_17__["Player"].getHomeComputer(),
hasHandbook = false,
handbookFn = "corporation-management-handbook.lit";
for (let i = 0; i < homeComp.messages.length; ++i) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_30__["isString"])(homeComp.messages[i]) && homeComp.messages[i] === handbookFn) {
hasHandbook = true;
break;
}
}
if (!hasHandbook) {
homeComp.messages.push(handbookFn);
}
Object(_Literature__WEBPACK_IMPORTED_MODULE_14__[/* showLiterature */ "b"])(handbookFn);
return false;
};
let corpRouting;
let eventHandler;
let companyManagementDiv;
Corporation.prototype.createUI = function () {
companyManagementDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
id: "cmpy-mgmt-container",
position: "fixed",
class: "generic-menupage-container"
});
document.getElementById("entire-game-container").appendChild(companyManagementDiv);
corpRouting = new _ui_Routing__WEBPACK_IMPORTED_MODULE_39__["CorporationRouting"](this);
eventHandler = new _ui_CorporationUIEventHandler__WEBPACK_IMPORTED_MODULE_37__[/* CorporationEventHandler */ "a"](this, corpRouting);
this.rerender();
};
Corporation.prototype.rerender = function () {
if (companyManagementDiv == null || corpRouting == null || eventHandler == null) {
console.warn(`Corporation.rerender() called when companyManagementDiv, corpRouting, or eventHandler is null`);
return;
}
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["Page"].Corporation)) {
return;
}
react_dom__WEBPACK_IMPORTED_MODULE_36___default.a.render(react__WEBPACK_IMPORTED_MODULE_35___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_38__[/* CorporationRoot */ "a"], {
corp: this,
routing: corpRouting,
eventHandler: eventHandler
}), companyManagementDiv);
};
Corporation.prototype.clearUI = function () {
if (companyManagementDiv instanceof HTMLElement) {
react_dom__WEBPACK_IMPORTED_MODULE_36___default.a.unmountComponentAtNode(companyManagementDiv);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_33__["removeElementById"])(companyManagementDiv.id);
}
companyManagementDiv = null;
document.getElementById("character-overview-wrapper").style.visibility = "visible";
};
Corporation.prototype.toJSON = function () {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_toJSON"])("Corporation", this);
};
Corporation.fromJSON = function (value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Generic_fromJSON"])(Corporation, value.data);
};
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_23__["Reviver"].constructors.Corporation = Corporation;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 32 */
/*!***********************************!*\
!*** ./utils/helpers/keyCodes.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Keyboard key codes
*/
exports.KEY = {
A: 65,
B: 66,
C: 67,
CTRL: 17,
D: 68,
DOWNARROW: 40,
E: 69,
ENTER: 13,
ESC: 27,
F: 70,
H: 72,
J: 74,
K: 75,
L: 76,
M: 77,
N: 78,
O: 79,
P: 80,
R: 82,
S: 83,
TAB: 9,
U: 85,
UPARROW: 38,
W: 87,
"1": 49,
"2": 50,
};
/***/ }),
/* 33 */
/*!**********************************!*\
!*** ./src/ui/MainMenu/Links.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Get references to the Main Menu link DOM elements
// Does NOT include collapsible headers for the links
const clearEventListeners_1 = __webpack_require__(/*! ../../../utils/uiHelpers/clearEventListeners */ 27);
exports.MainMenuLinks = {
Terminal: null,
ScriptEditor: null,
ActiveScripts: null,
CreateProgram: null,
Stats: null,
Factions: null,
Augmentations: null,
HacknetNodes: null,
Sleeves: null,
City: null,
Travel: null,
Job: null,
StockMarket: null,
Bladeburner: null,
Corporation: null,
Gang: null,
Tutorial: null,
Options: null,
DevMenu: null,
};
function initializeMainMenuLinks() {
try {
function safeGetLink(id) {
const elem = clearEventListeners_1.clearEventListeners(id);
if (elem == null) {
throw new Error(`clearEventListeners() failed for element with id: ${id}`);
}
return elem;
}
exports.MainMenuLinks.Terminal = safeGetLink("terminal-menu-link");
exports.MainMenuLinks.ScriptEditor = safeGetLink("create-script-menu-link");
exports.MainMenuLinks.ActiveScripts = safeGetLink("active-scripts-menu-link");
exports.MainMenuLinks.CreateProgram = safeGetLink("create-program-menu-link");
exports.MainMenuLinks.Stats = safeGetLink("stats-menu-link");
exports.MainMenuLinks.Factions = safeGetLink("factions-menu-link");
exports.MainMenuLinks.Augmentations = safeGetLink("augmentations-menu-link");
exports.MainMenuLinks.HacknetNodes = safeGetLink("hacknet-nodes-menu-link");
exports.MainMenuLinks.Sleeves = safeGetLink("sleeves-menu-link");
exports.MainMenuLinks.City = safeGetLink("city-menu-link");
exports.MainMenuLinks.Travel = safeGetLink("travel-menu-link");
exports.MainMenuLinks.Job = safeGetLink("job-menu-link");
exports.MainMenuLinks.StockMarket = safeGetLink("stock-market-menu-link");
exports.MainMenuLinks.Bladeburner = safeGetLink("bladeburner-menu-link");
exports.MainMenuLinks.Corporation = safeGetLink("corporation-menu-link");
exports.MainMenuLinks.Gang = safeGetLink("gang-menu-link");
exports.MainMenuLinks.Tutorial = safeGetLink("tutorial-menu-link");
exports.MainMenuLinks.Options = document.getElementById("options-menu-link"); // This click listener is already set, so don't clear it
exports.MainMenuLinks.DevMenu = safeGetLink("dev-menu-link");
return true;
}
catch (e) {
console.error(`Failed to initialize Main Menu Links: ${e}`);
return false;
}
}
exports.initializeMainMenuLinks = initializeMainMenuLinks;
/***/ }),
/* 34 */
/*!************************************!*\
!*** ./src/Fconf/FconfSettings.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FconfSettings = {
ENABLE_BASH_HOTKEYS: false,
ENABLE_TIMESTAMPS: false,
MAIN_MENU_STYLE: "default",
THEME_BACKGROUND_COLOR: "#000000",
THEME_FONT_COLOR: "#66ff33",
THEME_HIGHLIGHT_COLOR: "#ffffff",
THEME_PROMPT_COLOR: "#f92672",
WRAP_INPUT: false,
};
/***/ }),
/* 35 */
/*!**************************************!*\
!*** ./src/Hacknet/HacknetServer.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Hacknet Servers - Reworked Hacknet Node mechanic for BitNode-9
*/
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
const BaseServer_1 = __webpack_require__(/*! ../Server/BaseServer */ 252);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 159);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
// Constants for Hacknet Server stats/production
exports.HacknetServerHashesPerLevel = 0.001;
// Constants for Hacknet Server purchase/upgrade costs
exports.BaseCostForHacknetServer = 50e3;
exports.BaseCostFor1GBHacknetServerRam = 200e3;
exports.BaseCostForHacknetServerCore = 1e6;
exports.BaseCostForHacknetServerCache = 10e6;
exports.HacknetServerPurchaseMult = 3.2; // Multiplier for puchasing an additional Hacknet Server
exports.HacknetServerUpgradeLevelMult = 1.1; // Multiplier for cost when upgrading level
exports.HacknetServerUpgradeRamMult = 1.4; // Multiplier for cost when upgrading RAM
exports.HacknetServerUpgradeCoreMult = 1.55; // Multiplier for cost when buying another core
exports.HacknetServerUpgradeCacheMult = 1.85; // Multiplier for cost when upgrading cache
exports.MaxNumberHacknetServers = 25; // Max number of Hacknet Servers you can own
// Constants for max upgrade levels for Hacknet Server
exports.HacknetServerMaxLevel = 300;
exports.HacknetServerMaxRam = 8192;
exports.HacknetServerMaxCores = 128;
exports.HacknetServerMaxCache = 15;
class HacknetServer extends BaseServer_1.BaseServer {
constructor(params = { hostname: "", ip: IPAddress_1.createRandomIp() }) {
super(params);
// Cache level. Affects hash Capacity
this.cache = 1;
// Number of cores. Improves hash production
this.cores = 1;
// Number of hashes that can be stored by this Hacknet Server
this.hashCapacity = 0;
// Hashes produced per second
this.hashRate = 0;
// Similar to Node level. Improves hash production
this.level = 1;
// How long this HacknetServer has existed, in seconds
this.onlineTimeSeconds = 0;
// Total number of hashes earned by this
this.totalHashesGenerated = 0;
this.maxRam = 1;
this.updateHashCapacity();
}
// Initializes a HacknetServer Object from a JSON save state
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(HacknetServer, value.data);
}
calculateCacheUpgradeCost(levels) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.cache >= exports.HacknetServerMaxCache) {
return Infinity;
}
const mult = exports.HacknetServerUpgradeCacheMult;
let totalCost = 0;
let currentCache = this.cache;
for (let i = 0; i < sanitizedLevels; ++i) {
totalCost += Math.pow(mult, currentCache - 1);
++currentCache;
}
totalCost *= exports.BaseCostForHacknetServerCache;
return totalCost;
}
calculateCoreUpgradeCost(levels, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.cores >= exports.HacknetServerMaxCores) {
return Infinity;
}
const mult = exports.HacknetServerUpgradeCoreMult;
let totalCost = 0;
let currentCores = this.cores;
for (let i = 0; i < sanitizedLevels; ++i) {
totalCost += Math.pow(mult, currentCores - 1);
++currentCores;
}
totalCost *= exports.BaseCostForHacknetServerCore;
totalCost *= costMult;
return totalCost;
}
calculateLevelUpgradeCost(levels, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.level >= exports.HacknetServerMaxLevel) {
return Infinity;
}
const mult = exports.HacknetServerUpgradeLevelMult;
let totalMultiplier = 0;
let currLevel = this.level;
for (let i = 0; i < sanitizedLevels; ++i) {
totalMultiplier += Math.pow(mult, currLevel);
++currLevel;
}
return 10 * exports.BaseCostForHacknetServer * totalMultiplier * costMult;
}
calculateRamUpgradeCost(levels, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.maxRam >= exports.HacknetServerMaxRam) {
return Infinity;
}
let totalCost = 0;
let numUpgrades = Math.round(Math.log2(this.maxRam));
let currentRam = this.maxRam;
for (let i = 0; i < sanitizedLevels; ++i) {
let baseCost = currentRam * exports.BaseCostFor1GBHacknetServerRam;
let mult = Math.pow(exports.HacknetServerUpgradeRamMult, numUpgrades);
totalCost += (baseCost * mult);
currentRam *= 2;
++numUpgrades;
}
totalCost *= costMult;
return totalCost;
}
// Process this Hacknet Server in the game loop.
// Returns the number of hashes generated
process(numCycles = 1) {
const seconds = numCycles * Constants_1.CONSTANTS.MilliPerCycle / 1000;
return this.hashRate * seconds;
}
// Returns a boolean indicating whether the cache was successfully upgraded
upgradeCache(levels) {
this.cache = Math.min(exports.HacknetServerMaxCache, Math.round(this.cache + levels));
this.updateHashCapacity();
}
// Returns a boolean indicating whether the number of cores was successfully upgraded
upgradeCore(levels, prodMult) {
this.cores = Math.min(exports.HacknetServerMaxCores, Math.round(this.cores + levels));
this.updateHashRate(prodMult);
}
// Returns a boolean indicating whether the level was successfully upgraded
upgradeLevel(levels, prodMult) {
this.level = Math.min(exports.HacknetServerMaxLevel, Math.round(this.level + levels));
this.updateHashRate(prodMult);
}
// Returns a boolean indicating whether the RAM was successfully upgraded
upgradeRam(levels, prodMult) {
for (let i = 0; i < levels; ++i) {
this.maxRam *= 2;
}
this.maxRam = Math.min(exports.HacknetServerMaxRam, Math.round(this.maxRam));
this.updateHashRate(prodMult);
return true;
}
/**
* Whenever a script is run, we must update this server's hash rate
*/
runScript(script, prodMult) {
super.runScript(script);
if (prodMult != null && typeof prodMult === "number") {
this.updateHashRate(prodMult);
}
}
updateHashCapacity() {
this.hashCapacity = 32 * Math.pow(2, this.cache);
}
updateHashRate(prodMult) {
const baseGain = exports.HacknetServerHashesPerLevel * this.level;
const ramMultiplier = Math.pow(1.07, Math.log2(this.maxRam));
const coreMultiplier = 1 + (this.cores - 1) / 5;
const ramRatio = (1 - this.ramUsed / this.maxRam);
const hashRate = baseGain * ramMultiplier * coreMultiplier * ramRatio;
this.hashRate = hashRate * prodMult * BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney;
if (isNaN(this.hashRate)) {
this.hashRate = 0;
console.error(`Error calculating Hacknet Server hash production. This is a bug. Please report to game dev`, false);
}
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("HacknetServer", this);
}
}
exports.HacknetServer = HacknetServer;
JSONReviver_1.Reviver.constructors.HacknetServer = HacknetServer;
/***/ }),
/* 36 */
/*!****************************************!*\
!*** ./utils/uiHelpers/createPopup.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const createElement_1 = __webpack_require__(/*! ./createElement */ 3);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 91);
/**
* Creates the necessary DOM elements to present an in-game popup to the player.
* @param id The (hopefully) unique identifier for the popup container.
* @param elems The collection of HTML Elements to show within the popup.
*/
function createPopup(id, elems, options = {}) {
const container = createElement_1.createElement("div", {
class: "popup-box-container",
display: "flex",
id: id,
});
const content = createElement_1.createElement("div", {
class: "popup-box-content",
id: `${id}-content`,
});
for (const elem of elems) {
content.appendChild(elem);
}
// Configurable Options
if (options.backgroundColor) {
content.style.backgroundColor = options.backgroundColor;
}
container.appendChild(content);
getElementById_1.getElementById("entire-game-container").appendChild(container);
return container;
}
exports.createPopup = createPopup;
/***/ }),
/* 37 */
/*!*********************************************!*\
!*** ./src/Locations/data/LocationNames.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Names of all locations
*/
var LocationName;
(function (LocationName) {
// Cities
LocationName["Aevum"] = "Aevum";
LocationName["Chongqing"] = "Chongqing";
LocationName["Ishima"] = "Ishima";
LocationName["NewTokyo"] = "New Tokyo";
LocationName["Sector12"] = "Sector-12";
LocationName["Volhaven"] = "Volhaven";
// Aevum Locations
LocationName["AevumAeroCorp"] = "AeroCorp";
LocationName["AevumBachmanAndAssociates"] = "Bachman & Associates";
LocationName["AevumClarkeIncorporated"] = "Clarke Incorporated";
LocationName["AevumCrushFitnessGym"] = "Crush Fitness Gym";
LocationName["AevumECorp"] = "ECorp";
LocationName["AevumFulcrumTechnologies"] = "Fulcrum Technologies";
LocationName["AevumGalacticCybersystems"] = "Galactic Cybersystems";
LocationName["AevumNetLinkTechnologies"] = "NetLink Technologies";
LocationName["AevumPolice"] = "Aevum Police Headquarters";
LocationName["AevumRhoConstruction"] = "Rho Construction";
LocationName["AevumSnapFitnessGym"] = "Snap Fitness Gym";
LocationName["AevumSummitUniversity"] = "Summit University";
LocationName["AevumWatchdogSecurity"] = "Watchdog Security";
// Chongqing locations
LocationName["ChongqingKuaiGongInternational"] = "KuaiGong International";
LocationName["ChongqingSolarisSpaceSystems"] = "Solaris Space Systems";
// Sector 12
LocationName["Sector12AlphaEnterprises"] = "Alpha Enterprises";
LocationName["Sector12BladeIndustries"] = "Blade Industries";
LocationName["Sector12CIA"] = "Central Intelligence Agency";
LocationName["Sector12CarmichaelSecurity"] = "Carmichael Security";
LocationName["Sector12CityHall"] = "Sector-12 City Hall";
LocationName["Sector12DeltaOne"] = "DeltaOne";
LocationName["Sector12FoodNStuff"] = "FoodNStuff";
LocationName["Sector12FourSigma"] = "Four Sigma";
LocationName["Sector12IcarusMicrosystems"] = "Icarus Microsystems";
LocationName["Sector12IronGym"] = "Iron Gym";
LocationName["Sector12JoesGuns"] = "Joe's Guns";
LocationName["Sector12MegaCorp"] = "MegaCorp";
LocationName["Sector12NSA"] = "National Security Agency";
LocationName["Sector12PowerhouseGym"] = "Powerhouse Gym";
LocationName["Sector12RothmanUniversity"] = "Rothman University";
LocationName["Sector12UniversalEnergy"] = "Universal Energy";
// New Tokyo
LocationName["NewTokyoDefComm"] = "DefComm";
LocationName["NewTokyoGlobalPharmaceuticals"] = "Global Pharmaceuticals";
LocationName["NewTokyoNoodleBar"] = "Noodle Bar";
LocationName["NewTokyoVitaLife"] = "VitaLife";
// Ishima
LocationName["IshimaNovaMedical"] = "Nova Medical";
LocationName["IshimaOmegaSoftware"] = "Omega Software";
LocationName["IshimaStormTechnologies"] = "Storm Technologies";
// Volhaven
LocationName["VolhavenCompuTek"] = "CompuTek";
LocationName["VolhavenHeliosLabs"] = "Helios Labs";
LocationName["VolhavenLexoCorp"] = "LexoCorp";
LocationName["VolhavenMilleniumFitnessGym"] = "Millenium Fitness Gym";
LocationName["VolhavenNWO"] = "NWO";
LocationName["VolhavenOmniTekIncorporated"] = "OmniTek Incorporated";
LocationName["VolhavenOmniaCybersystems"] = "Omnia Cybersystems";
LocationName["VolhavenSysCoreSecurities"] = "SysCore Securities";
LocationName["VolhavenZBInstituteOfTechnology"] = "ZB Institute of Technology";
// Generic locations
LocationName["Hospital"] = "Hospital";
LocationName["Slums"] = "The Slums";
LocationName["TravelAgency"] = "Travel Agency";
LocationName["WorldStockExchange"] = "World Stock Exchange";
// Default name for Location objects
LocationName["Void"] = "The Void";
})(LocationName = exports.LocationName || (exports.LocationName = {}));
;
/***/ }),
/* 38 */
/*!****************************************!*\
!*** ./src/Server/SpecialServerIps.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* Holds IP of Special Servers */
exports.SpecialServerNames = {
FulcrumSecretTechnologies: "Fulcrum Secret Technologies Server",
CyberSecServer: "CyberSec Server",
NiteSecServer: "NiteSec Server",
TheBlackHandServer: "The Black Hand Server",
BitRunnersServer: "BitRunners Server",
TheDarkArmyServer: "The Dark Army Server",
DaedalusServer: "Daedalus Server",
WorldDaemon: "w0r1d_d43m0n",
};
class SpecialServerIpsMap {
// Initializes a SpecialServerIpsMap Object from a JSON save state
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(SpecialServerIpsMap, value.data);
}
constructor() { }
addIp(name, ip) {
this[name] = ip;
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("SpecialServerIpsMap", this);
}
}
exports.SpecialServerIpsMap = SpecialServerIpsMap;
JSONReviver_1.Reviver.constructors.SpecialServerIpsMap = SpecialServerIpsMap;
exports.SpecialServerIps = new SpecialServerIpsMap();
function prestigeSpecialServerIps() {
for (var member in exports.SpecialServerIps) {
delete exports.SpecialServerIps[member];
}
exports.SpecialServerIps = new SpecialServerIpsMap();
}
exports.prestigeSpecialServerIps = prestigeSpecialServerIps;
function loadSpecialServerIps(saveString) {
exports.SpecialServerIps = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadSpecialServerIps = loadSpecialServerIps;
function initSpecialServerIps() {
exports.SpecialServerIps = new SpecialServerIpsMap();
}
exports.initSpecialServerIps = initSpecialServerIps;
/***/ }),
/* 39 */
/*!****************************!*\
!*** ./src/Bladeburner.js ***!
\****************************/
/*! exports provided: Bladeburner */
/*! exports used: Bladeburner */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Bladeburner; });
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentation/Augmentations */ 11);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Faction/Faction */ 71);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Faction/Factions */ 13);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 52);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./RedPill */ 83);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/JSONReviver */ 17);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 68);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 88);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/helpers/clearObject */ 111);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/helpers/createProgressBarText */ 101);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 49);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 15);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 147);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 41);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../utils/uiHelpers/appendLineBreaks */ 80);
/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/uiHelpers/removeElement */ 76);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 29);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__);
const stealthIcon = ` `
const killIcon = ``
const CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"];
const CyclesPerSecond = 5; // Game cycle is 200 ms
const StaminaGainPerSecond = 0.0085;
const BaseStaminaLoss = 0.285; // Base stamina loss per action. Increased based on difficulty
const MaxStaminaToGainFactor = 70000; // Max Stamina is divided by this to get bonus stamina gain
const DifficultyToTimeFactor = 10; // Action Difficulty divided by this to get base action time
/**
* The difficulty multiplier affects stamina loss and hp loss of an action. Also affects
* experience gain. Its formula is:
* difficulty ^ exponentialFactor + difficulty / linearFactor
*/
const DiffMultExponentialFactor = 0.28;
const DiffMultLinearFactor = 650;
/**
* These factors are used to calculate action time.
* They affect how much action time is reduced based on your agility and dexterity
*/
const EffAgiLinearFactor = 10e3;
const EffDexLinearFactor = 10e3;
const EffAgiExponentialFactor = 0.04;
const EffDexExponentialFactor = 0.035;
const BaseRecruitmentTimeNeeded = 300; // Base time needed (s) to complete a Recruitment action
const PopulationThreshold = 1e9; // Population which determines baseline success rate
const PopulationExponent = 0.7; // Exponent that influences how different populations affect success rate
const ChaosThreshold = 50; // City chaos level after which it starts making tasks harder
const BaseStatGain = 1; // Base stat gain per second
const BaseIntGain = 0.001; // Base intelligence stat gain
const ActionCountGrowthPeriod = 480; // Time (s) it takes for action count to grow by its specified value
const RankToFactionRepFactor = 2; // Delta Faction Rep = this * Delta Rank
const RankNeededForFaction = 25;
const ContractSuccessesPerLevel = 3; // How many successes you need to level up a contract
const OperationSuccessesPerLevel = 2.5; // How many successes you need to level up an op
const RanksPerSkillPoint = 3; // How many ranks needed to get 1 Skill Point
const ContractBaseMoneyGain = 250e3; // Base Money Gained per contract
const HrcHpGain = 2; // HP Gained from Hyperbolic Regeneration chamber
const HrcStaminaGain = 1; // Percentage Stamina gained from Hyperbolic Regeneration Chamber
// DOM related variables
const ActiveActionCssClass = "bladeburner-active-action";
// Console related stuff
let consoleHistoryIndex = 0;
const consoleHelpText = {
helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.
" +
"automate [var] [val] [hi/low] Configure simple automation for Bladeburner tasks " +
"clear/cls Clear the console " +
"help [cmd] Display this help text, or help text for a specific command " +
"log [en/dis] [type] Enable or disable logging for events and actions " +
"skill [action] [name] Level or display info about your Bladeburner skills " +
"start [type] [name] Start a Bladeburner action/task " +
"stop Stops your current Bladeburner action/task ",
automate:"automate [var] [val] [hi/low]
" +
"A simple way to automate your Bladeburner actions. This console command can be used " +
"to automatically start an action when your stamina rises above a certain threshold, and " +
"automatically switch to another action when your stamina drops below another threshold.
" +
"automate status - Check the current status of your automation and get a brief description of what it'll do " +
"automate en - Enable the automation feature " +
"automate dis - Disable the automation feature
" +
"There are four properties that must be set for this automation to work properly. Here is how to set them:
" +
"automate stamina 100 high " +
"automate contract Tracking high " +
"automate stamina 50 low " +
'automate general "Field Analysis" low
' +
"Using the four console commands above will set the automation to perform Tracking contracts " +
"if your stamina is 100 or higher, and then switch to Field Analysis if your stamina drops below " +
"50. Note that when setting the action, the name of the action is CASE-SENSITIVE. It must " +
"exactly match whatever the name is in the UI.",
clear:"clear
Clears the console",
cls:"cls
Clears the console",
help:"help [command]
" +
"Running 'help' with no arguments displays the general help text, which lists all console commands " +
"and a brief description of what they do. A command can be specified to get more specific help text " +
"about that particular command. For example:
" +
"help automate
" +
"will display specific information about using the automate console command",
log:"log [en/dis] [type]
" +
"Enable or disable logging. By default, the results of completing actions such as contracts/operations are logged " +
"in the console. There are also random events that are logged in the console as well. The five categories of " +
"things that get logged are:
" +
"[general, contracts, ops, blackops, events]
" +
"The logging for these categories can be enabled or disabled like so:
" +
"log dis contracts - Disables logging that occurs when contracts are completed " +
"log en contracts - Enables logging that occurs when contracts are completed " +
"log dis events - Disables logging for Bladeburner random events
" +
"Logging can be universally enabled/disabled using the 'all' keyword:
" +
"log dis all " +
"log en all",
skill:"skill [action] [name]
" +
"Level or display information about your skills.
" +
"To display information about all of your skills and your multipliers, use:
" +
"skill list
" +
"To display information about a specific skill, specify the name of the skill afterwards. " +
"Note that the name of the skill is case-sensitive. Enter it exactly as seen in the UI. If " +
"the name of the skill has whitespace, enclose the name of the skill in double quotation marks:
" +
"skill list Reaper " +
'skill list "Digital Observer"
' +
"This console command can also be used to level up skills:
" +
"Start an action. An action is specified by its type and its name. The " +
"name is case-sensitive. It must appear exactly as it does in the UI. If " +
"the name of the action has whitespace, enclose it in double quotation marks. " +
"Valid action types include:
" +
"Stop your current action and go idle",
}
// Keypresses for Console
$(document).keydown(function(event) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner)) {
if (!(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner instanceof Bladeburner)) { return; }
let consoleHistory = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner.consoleHistory;
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22__["KEY"].ENTER) {
event.preventDefault();
var command = DomElems.consoleInput.value;
if (command.length > 0) {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner.postToConsole("> " + command);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner.resetConsoleInput();
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner.executeConsoleCommands(command);
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22__["KEY"].UPARROW) {
if (DomElems.consoleInput == null) {return;}
var i = consoleHistoryIndex;
var len = consoleHistory.length;
if (len === 0) {return;}
if (i < 0 || i > len) {
consoleHistoryIndex = len;
}
if (i !== 0) {
--consoleHistoryIndex;
}
var prevCommand = consoleHistory[consoleHistoryIndex];
DomElems.consoleInput.value = prevCommand;
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_14__["setTimeoutRef"])(function(){DomElems.consoleInput.selectionStart = DomElems.consoleInput.selectionEnd = 10000; }, 0);
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_22__["KEY"].DOWNARROW) {
if (DomElems.consoleInput == null) {return;}
var i = consoleHistoryIndex;
var len = consoleHistory.length;
if (len == 0) {return;}
if (i < 0 || i > len) {
consoleHistoryIndex = len;
}
// Latest command, put nothing
if (i == len || i == len-1) {
consoleHistoryIndex = len;
DomElems.consoleInput.value = "";
} else {
++consoleHistoryIndex;
var prevCommand = consoleHistory[consoleHistoryIndex];
DomElems.consoleInput.value = prevCommand;
}
}
}
});
function City(params={}) {
this.name = params.name ? params.name : CityNames[2]; // Sector-12
// Synthoid population and estimate
this.pop = params.pop ? params.pop : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(PopulationThreshold, 1.5 * PopulationThreshold);
this.popEst = this.pop * (Math.random() + 0.5);
// Number of Synthoid communities population and estimate
this.comms = params.comms ? params.comms : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 150);
this.commsEst = this.comms + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(-5, 5);
if (this.commsEst < 0) {this.commsEst = 0;}
this.chaos = 0;
}
City.prototype.improvePopulationEstimateByCount = function(n) {
if (isNaN(n)) {throw new Error("NaN passeed into City.improvePopulationEstimateByCount()");}
if (this.popEst < this.pop) {
this.popEst += n;
if (this.popEst > this.pop) {this.popEst = this.pop;}
} else if (this.popEst > this.pop) {
this.popEst -= n;
if (this.popEst < this.pop) {this.popEst = this.pop;}
}
}
// @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 *= (1 + (p/100));
if (this.popEst > this.pop) {this.popEst = this.pop;}
} else if (this.popEst > this.pop) {
this.popEst *= (1 - (p/100));
if (this.popEst < this.pop) {this.popEst = this.pop;}
}
}
City.prototype.improveCommunityEstimate = function(n=1) {
if (isNaN(n)) {throw new Error("NaN passed into City.improveCommunityEstimate()");}
if (this.commsEst < this.comms) {
this.commsEst += n;
if (this.commsEst > this.comms) {this.commsEst = this.comms;}
} else if (this.commsEst > this.comms) {
this.commsEst -= n;
if (this.commsEst < this.comms) {this.commsEst = this.comms;}
}
}
/**
* @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;
if (params.estChange && !isNaN(params.estChange)) {this.popEst += params.estChange;}
if (params.estOffset) {
this.popEst = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(this.popEst, params.estOffset);
}
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
*/
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
if (params.nonZero && change === 0) {
p > 0 ? change = 1 : change = -1;
}
this.pop += change;
if (params.changeEstEqually) {
this.popEst += change;
if (this.popEst < 0) {this.popEst = 0;}
}
return change;
}
City.prototype.changeChaosByCount = function(n) {
if (isNaN(n)) {throw new Error("NaN passed into City.changeChaosByCount()");}
if (n === 0) {return;}
this.chaos += n;
if (this.chaos < 0) {this.chaos = 0;}
}
// @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;}
var change = this.chaos * (p/100);
this.chaos += change;
if (this.chaos < 0) {this.chaos = 0;}
}
City.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("City", this);
}
City.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(City, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.City = City;
function Skill(params={name:"foo", desc:"foo"}) {
if (params.name) {
this.name = params.name;
} else {
throw new Error("Failed to initialize Bladeburner Skill. No name was specified in ctor");
}
if (params.desc) {
this.desc = params.desc;
} 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
if (params.maxLvl) {this.maxLvl = params.maxLvl;}
/**
* 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
*/
if (params.successChanceEstimate) {this.successChanceEstimate = params.successChanceEstimate;}
if (params.actionTime) {this.actionTime = params.actionTime;}
if (params.effHack) {this.effHack = params.effHack;}
if (params.effStr) {this.effStr = params.effStr;}
if (params.effDef) {this.effDef = params.effDef;}
if (params.effDex) {this.effDex = params.effDex;}
if (params.effAgi) {this.effAgi = params.effAgi;}
if (params.effCha) {this.effCha = params.effCha;}
if (params.stamina) {this.stamina = params.stamina;}
if (params.money) {this.money = params.money;}
if (params.expGain) {this.expGain = params.expGain;}
//Equipment
if (params.weaponAbility) {this.weaponAbility = params.weaponAbility;}
if (params.gunAbility) {this.gunAbility = params.gunAbility;}
}
Skill.prototype.calculateCost = function(currentLevel) {
return Math.floor((this.baseCost + (currentLevel * this.costInc)) * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerSkillCost);
}
const Skills = {};
const SkillNames = {
BladesIntuition: "Blade's Intuition",
Cloak: "Cloak",
Marksman: "Marksman",
WeaponProficiency: "Weapon Proficiency",
ShortCircuit: "Short-Circuit",
DigitalObserver: "Digital Observer",
Tracer: "Tracer",
Overclock: "Overclock",
Reaper: "Reaper",
EvasiveSystem: "Evasive System",
Datamancer: "Datamancer",
CybersEdge: "Cyber's Edge",
HandsOfMidas: "Hands of Midas",
Hyperdrive: "Hyperdrive",
}
// 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. See getDifficulty() method
this.level = 1;
this.maxLevel = 1;
this.autoLevel = true;
this.baseDifficulty = params.baseDifficulty ? Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(params.baseDifficulty, 10) : 100;
this.difficultyFac = params.difficultyFac ? params.difficultyFac : 1.01;
// 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
this.rankGain = params.rankGain ? params.rankGain : 0;
if (params.rankLoss) {this.rankLoss = params.rankLoss;}
if (params.hpLoss) {
this.hpLoss = params.hpLoss;
this.hpLost = 0;
}
// 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"
*/
this.count = params.count ? params.count : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1e3, 25e3);
this.countGrowth = params.countGrowth ? params.countGrowth : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 5);
// 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
let sum = 0;
for (const weight in this.weights) {
if (this.weights.hasOwnProperty(weight)) {
sum += this.weights[weight];
}
}
if (sum - 1 >= 10 * Number.EPSILON) {
throw new Error("Invalid weights when constructing Action " + this.name +
". The weights should sum up to 1. They sum up to :" + 1);
}
// 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 " +
"Action " + this.name + ". " +
"Decay value cannot be greater than 1");
}
}
}
}
Action.prototype.getDifficulty = function() {
var difficulty = this.baseDifficulty * Math.pow(this.difficultyFac, this.level-1);
if (isNaN(difficulty)) {throw new Error("Calculated NaN in Action.getDifficulty()");}
return difficulty;
}
/**
* @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();
var competence = 0;
for (var stat in this.weights) {
if (this.weights.hasOwnProperty(stat)) {
var playerStatLvl = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queryStatFromString(stat);
var key = "eff" + stat.charAt(0).toUpperCase() + stat.slice(1);
var effMultiplier = inst.skillMultipliers[key];
if (effMultiplier == null) {
console.log("ERROR: Failed to find Bladeburner Skill multiplier for: " + stat);
effMultiplier = 1;
}
competence += (this.weights[stat] * Math.pow(effMultiplier*playerStatLvl, this.decays[stat]));
}
}
competence *= inst.calculateStaminaPenalty();
// 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);
var teamMultiplier = Math.pow(this.teamCount, 0.05);
competence *= teamMultiplier;
}
}
// Lower city population results in lower chances
if (!(this instanceof BlackOperation)) {
var city = inst.getCurrentCity();
if (params.est) {
competence *= Math.pow((city.popEst / PopulationThreshold), PopulationExponent);
} else {
competence *= Math.pow((city.pop / PopulationThreshold), PopulationExponent);
}
// 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
if (this instanceof Operation && this.name === "Raid") {
if (city.comms <= 0) {return 0;}
}
}
// Factor skill multipliers into success chance
competence *= inst.skillMultipliers.successChanceAll;
if (this instanceof Operation || this instanceof BlackOperation) {
competence *= inst.skillMultipliers.successChanceOperation;
}
if (this instanceof Contract) {
competence *= inst.skillMultipliers.successChanceContract;
}
if (this.isStealth) {
competence *= inst.skillMultipliers.successChanceStealth;
}
if (this.isKill) {
competence *= inst.skillMultipliers.successChanceKill;
}
// Augmentation multiplier
competence *= _Player__WEBPACK_IMPORTED_MODULE_8__["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
* @param inst {Bladeburner} - Bladeburner instance
*/
Action.prototype.attempt = function(inst) {
return (Math.random() < this.getSuccessChance(inst));
}
Action.prototype.getActionTime = function(inst) {
var difficulty = this.getDifficulty();
var baseTime = difficulty / DifficultyToTimeFactor;
var skillFac = inst.skillMultipliers.actionTime; // Always < 1
var effAgility = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility * inst.skillMultipliers.effAgi;
var effDexterity = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].dexterity * inst.skillMultipliers.effDex;
var statFac = 0.5 * (Math.pow(effAgility, EffAgiExponentialFactor) +
Math.pow(effDexterity, EffDexExponentialFactor) +
(effAgility / EffAgiLinearFactor) +
(effDexterity / EffDexLinearFactor)); // Always > 1
baseTime = Math.max(1, baseTime * skillFac / statFac);
if (this instanceof Contract) {
return Math.ceil(baseTime);
} else if (this instanceof Operation) {
return Math.ceil(baseTime);
} else if (this instanceof BlackOperation) {
return Math.ceil(baseTime * 1.5);
} else {
throw new Error("Unrecognized Action Type in Action.getActionTime(this). Must be either Contract, Operation, or BlackOperation");
}
}
Action.prototype.getSuccessesNeededForNextLevel = function(baseSuccessesPerLevel) {
return Math.ceil((0.5) * (this.maxLevel) * (2 * baseSuccessesPerLevel + (this.maxLevel-1)));
}
Action.prototype.setMaxLevel = function(baseSuccessesPerLevel) {
if (this.successes >= this.getSuccessesNeededForNextLevel(baseSuccessesPerLevel)) {
++this.maxLevel;
}
}
Action.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("Action", this);
}
Action.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(Action, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.Action = Action;
const GeneralActions = {}; // Training, Field Analysis, Recruitment, etc.
// Action Identifier enum
const ActionTypes = Object.freeze({
"Idle": 1,
"Contract": 2,
"Operation": 3,
"BlackOp": 4,
"BlackOperation": 4,
"Training": 5,
"Recruitment": 6,
"FieldAnalysis": 7,
"Field Analysis": 7,
"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 Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("ActionIdentifier", this);
}
ActionIdentifier.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(ActionIdentifier, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.ActionIdentifier = ActionIdentifier;
// Contracts
function Contract(params={}) {
Action.call(this, params);
}
Contract.prototype = Object.create(Action.prototype);
Contract.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("Contract", this);
}
Contract.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(Contract, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.Contract = Contract;
// 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 Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("Operation", this);
}
Operation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(Operation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.Operation = Operation;
// Black Operations
function BlackOperation(params={}) {
Operation.call(this, params);
// Black ops are one time missions
this.count = 1;
this.countGrowth = 0;
}
BlackOperation.prototype = Object.create(Action.prototype);
BlackOperation.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("BlackOperation", this);
}
BlackOperation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(BlackOperation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.BlackOperation = BlackOperation;
const BlackOperations = {};
function Bladeburner(params={}) {
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.skillPoints = 0;
this.totalSkillPoints = 0;
this.teamSize = 0; // Number of team members
this.teamLost = 0; // Number of team members lost
this.storedCycles = 0;
this.randomEventCounter = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(240, 600); // 4-10 minutes
// These times are in seconds
this.actionTimeToComplete = 0; // 0 or -1 is an infinite running action (like training)
this.actionTimeCurrent = 0;
// ActionIdentifier Object
var idleActionType = ActionTypes["Idle"];
this.action = new ActionIdentifier({type:idleActionType});
this.cities = {};
for (var i = 0; i < CityNames.length; ++i) {
this.cities[CityNames[i]] = new City({name:CityNames[i]});
}
this.city = CityNames[2]; // Sector-12
// Map of SkillNames -> level
this.skills = {};
this.skillMultipliers = {};
this.updateSkillMultipliers(); // Calls resetSkillMultipliers()
// 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.
*/
this.contracts = {};
this.operations = {};
// Object that contains name of all Black Operations that have been completed
this.blackops = {};
// Flags for whether these actions should be logged to console
this.logging = {
general:true,
contracts:true,
ops:true,
blackops:true,
events:true,
}
// 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
this.consoleHistory = [];
this.consoleLogs = [];
// Initialization
initBladeburner();
this.initializeDomElementRefs();
if (params.new) {this.create();}
}
Bladeburner.prototype.prestige = function() {
this.resetAction();
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"]["Bladeburners"];
if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_7__["joinFaction"])(bladeburnerFac);
}
}
Bladeburner.prototype.create = function() {
this.contracts["Tracking"] = new Contract({
name:"Tracking",
desc:"Identify and locate Synthoids. This contract involves reconnaissance " +
"and information-gathering ONLY. Do NOT engage. Stealth is of the utmost importance.
" +
"Successfully completing Tracking contracts will slightly improve your Synthoid population estimate for " +
"whatever city you are currently in.",
baseDifficulty:125,difficultyFac:1.02,rewardFac:1.041,
rankGain:0.3, hpLoss:0.5,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(25, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 75)/10,
weights:{hack:0,str:0.05,def:0.05,dex:0.35,agi:0.35,cha:0.1, int:0.05},
decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.9, int:1},
isStealth:true
});
this.contracts["Bounty Hunter"] = new Contract({
name:"Bounty Hunter",
desc:"Hunt down and capture fugitive Synthoids. These Synthoids are wanted alive.
" +
"Successfully completing a Bounty Hunter contract will lower the population in your " +
"current city, and will also increase its chaos level.",
baseDifficulty:250, difficultyFac:1.04,rewardFac:1.085,
rankGain:0.9, hpLoss:1,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 75)/10,
weights:{hack:0,str:0.15,def:0.15,dex:0.25,agi:0.25,cha:0.1, int:0.1},
decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9},
isKill:true
});
this.contracts["Retirement"] = new Contract({
name:"Retirement",
desc:"Hunt down and retire (kill) rogue Synthoids.
" +
"Successfully completing a Retirement contract will lower the population in your current " +
"city, and will also increase its chaos level.",
baseDifficulty:200, difficultyFac:1.03, rewardFac:1.065,
rankGain:0.6, hpLoss:1,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(5, 75)/10,
weights:{hack:0,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0.1, int:0.1},
decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9},
isKill:true
});
this.operations["Investigation"] = new Operation({
name:"Investigation",
desc:"As a field agent, investigate and identify Synthoid " +
"populations, movements, and operations.
Successful " +
"Investigation ops will increase the accuracy of your " +
"synthoid data.
" +
"You will NOT lose HP from failed Investigation ops.",
baseDifficulty:400, difficultyFac:1.03,rewardFac:1.07,reqdRank:25,
rankGain:2.2, rankLoss:0.2,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 100), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(10, 40)/10,
weights:{hack:0.25,str:0.05,def:0.05,dex:0.2,agi:0.1,cha:0.25, int:0.1},
decays:{hack:0.85,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9},
isStealth:true
});
this.operations["Undercover Operation"] = new Operation({
name:"Undercover Operation",
desc:"Conduct undercover operations to identify hidden " +
"and underground Synthoid communities and organizations.
" +
"Successful Undercover ops will increase the accuracy of your synthoid " +
"data.",
baseDifficulty:500, difficultyFac:1.04, rewardFac:1.09, reqdRank:100,
rankGain:4.4, rankLoss:0.4, hpLoss:2,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 100), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(10, 40)/10,
weights:{hack:0.2,str:0.05,def:0.05,dex:0.2,agi:0.2,cha:0.2, int:0.1},
decays:{hack:0.8,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9},
isStealth:true
});
this.operations["Sting Operation"] = new Operation({
name:"Sting Operation",
desc:"Conduct a sting operation to bait and capture particularly " +
"notorious Synthoid criminals.",
baseDifficulty:650, difficultyFac:1.04, rewardFac:1.095, reqdRank:500,
rankGain:5.5, rankLoss:0.5, hpLoss:2.5,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(3, 40)/10,
weights:{hack:0.25,str:0.05,def:0.05,dex:0.25,agi:0.1,cha:0.2, int:0.1},
decays:{hack:0.8,str:0.85,def:0.85,dex:0.85,agi:0.85,cha:0.7, int:0.9},
isStealth:true
});
this.operations["Raid"] = new Operation({
name:"Raid",
desc:"Lead an assault on a known Synthoid community. Note that " +
"there must be an existing Synthoid community in your current city " +
"in order for this Operation to be successful",
baseDifficulty:800, difficultyFac:1.045, rewardFac:1.1, reqdRank:3000,
rankGain:55,rankLoss:2.5,hpLoss:50,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(2, 40)/10,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9},
isKill:true
});
this.operations["Stealth Retirement Operation"] = new Operation({
name:"Stealth Retirement Operation",
desc:"Lead a covert operation to retire Synthoids. The " +
"objective is to complete the task without " +
"drawing any attention. Stealth and discretion are key.",
baseDifficulty:1000, difficultyFac:1.05, rewardFac:1.11, reqdRank:20e3,
rankGain:22, rankLoss:2, hpLoss:10,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 20)/10,
weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1},
decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9},
isStealth:true, isKill:true
});
this.operations["Assassination"] = new Operation({
name:"Assassination",
desc:"Assassinate Synthoids that have been identified as " +
"important, high-profile social and political leaders " +
"in the Synthoid communities.",
baseDifficulty:1500, difficultyFac:1.06, rewardFac:1.14, reqdRank:50e3,
rankGain:44, rankLoss:4, hpLoss:5,
count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 150), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 20)/10,
weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.8},
isStealth:true, isKill:true
});
}
Bladeburner.prototype.storeCycles = function(numCycles=1) {
this.storedCycles += numCycles;
}
Bladeburner.prototype.process = function() {
// Edge case condition...if Operation Daedalus is complete trigger the BitNode
if (_RedPill__WEBPACK_IMPORTED_MODULE_9__[/* redPillFlag */ "b"] === false && this.blackops.hasOwnProperty("Operation Daedalus")) {
return Object(_RedPill__WEBPACK_IMPORTED_MODULE_9__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bitNodeN);
}
// If the Player starts doing some other actions, set action to idle and alert
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_1__["AugmentationNames"].BladesSimulacrum].owned === false && _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].isWorking) {
if (this.action.type !== ActionTypes["Idle"]) {
let msg = "Your Bladeburner action was cancelled because you started doing something else.";
if (this.automateEnabled) {
msg += `
Your automation was disabled as well. You will have to re-enable it through the Bladeburner console`
this.automateEnabled = false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])(msg);
}
this.resetAction();
}
// If the Player has no Stamina, set action to idle
if (this.stamina <= 0) {
this.log("Your Bladeburner action was cancelled because your stamina hit 0");
this.resetAction();
}
// 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'
this.storedCycles -= seconds * CyclesPerSecond;
// Stamina
this.calculateMaxStamina();
this.stamina += (this.calculateStaminaGainPerSecond() * seconds);
this.stamina = Math.min(this.maxStamina, this.stamina);
// Count increase for contracts/operations
for (var contractName in this.contracts) {
if (this.contracts.hasOwnProperty(contractName)) {
var contract = this.contracts[contractName];
contract.count += (seconds * contract.countGrowth/ActionCountGrowthPeriod);
}
}
for (var operationName in this.operations) {
if (this.operations.hasOwnProperty(operationName)) {
var op = this.operations[operationName];
op.count += (seconds * op.countGrowth/ActionCountGrowthPeriod);
}
}
// 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");}
city.chaos -= (0.0001 * seconds);
city.chaos = Math.max(0, city.chaos);
}
// Random Events
this.randomEventCounter -= seconds;
if (this.randomEventCounter <= 0) {
this.randomEvent();
this.randomEventCounter = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(240, 600);
}
this.processAction(seconds);
// Automation
if (this.automateEnabled) {
// Note: Do NOT set this.action = this.automateActionHigh/Low since it creates a reference
if (this.stamina <= this.automateThreshLow) {
if (this.action.name !== this.automateActionLow.name || this.action.type !== this.automateActionLow.type) {
this.action = new ActionIdentifier({type: this.automateActionLow.type, name: this.automateActionLow.name});
this.startAction(this.action);
}
} else if (this.stamina >= this.automateThreshHigh) {
if (this.action.name !== this.automateActionHigh.name || this.action.type !== this.automateActionHigh.type) {
this.action = new ActionIdentifier({type: this.automateActionHigh.type, name: this.automateActionHigh.name});
this.startAction(this.action);
}
}
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner)) {
this.updateContent();
}
}
}
Bladeburner.prototype.calculateMaxStamina = function() {
var effAgility = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility * this.skillMultipliers.effAgi;
var maxStamina = (Math.pow(effAgility, 0.8) + this.staminaBonus);
maxStamina *= this.skillMultipliers.stamina;
maxStamina *= _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_max_stamina_mult;
if (isNaN(maxStamina)) {throw new Error("Max Stamina calculated to be NaN in Bladeburner.calculateMaxStamina()");}
this.maxStamina = maxStamina;
}
Bladeburner.prototype.calculateStaminaGainPerSecond = function() {
var effAgility = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility * this.skillMultipliers.effAgi;
var maxStaminaBonus = this.maxStamina / MaxStaminaToGainFactor;
var gain = (StaminaGainPerSecond + maxStaminaBonus) * Math.pow(effAgility, 0.17);
return gain * (this.skillMultipliers.stamina * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_stamina_gain_mult);
}
Bladeburner.prototype.calculateStaminaPenalty = function() {
return Math.min(1, this.stamina / (0.5 * this.maxStamina));
}
Bladeburner.prototype.changeRank = function(change) {
if (isNaN(change)) {throw new Error("NaN passed into Bladeburner.changeRank()");}
this.rank += change;
if (this.rank < 0) {this.rank = 0;}
this.maxRank = Math.max(this.rank, this.maxRank);
var bladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["factionExists"])(bladeburnersFactionName)) {
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"][bladeburnersFactionName];
if (!(bladeburnerFac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_5__["Faction"])) {
throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button");
}
if (bladeburnerFac.isMember) {
var favorBonus = 1 + (bladeburnerFac.favor / 100);
bladeburnerFac.playerReputation += (RankToFactionRepFactor * change * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].faction_rep_mult * favorBonus);
}
}
// Gain skill points
var rankNeededForSp = (this.totalSkillPoints+1) * RanksPerSkillPoint;
if (this.maxRank >= rankNeededForSp) {
// Calculate how many skill points to gain
var gainedSkillPoints = Math.floor((this.maxRank - rankNeededForSp) / RanksPerSkillPoint + 1);
this.skillPoints += gainedSkillPoints;
this.totalSkillPoints += gainedSkillPoints;
}
}
Bladeburner.prototype.getCurrentCity = function() {
var city = this.cities[this.city];
if (!(city instanceof City)) {
throw new Error("Bladeburner.getCurrentCity() did not properly return a City object");
}
return city;
}
Bladeburner.prototype.resetSkillMultipliers = function() {
this.skillMultipliers = {
successChanceAll: 1,
successChanceStealth: 1,
successChanceKill: 1,
successChanceContract: 1,
successChanceOperation: 1,
successChanceEstimate: 1,
actionTime: 1,
effHack: 1,
effStr: 1,
effDef: 1,
effDex: 1,
effAgi: 1,
effCha: 1,
effInt: 1,
stamina: 1,
money: 1,
expGain: 1,
weaponAbility: 1,
gunAbility: 1,
};
}
Bladeburner.prototype.updateSkillMultipliers = function() {
this.resetSkillMultipliers();
for (var skillName in this.skills) {
if (this.skills.hasOwnProperty(skillName)) {
var skill = Skills[skillName];
if (skill == null) {
throw new Error("Could not find Skill Object for: " + skillName);
}
var level = this.skills[skillName];
if (level == null || level <= 0) {continue;} //Not upgraded
var multiplierNames = Object.keys(this.skillMultipliers);
for (var i = 0; i < multiplierNames.length; ++i) {
var multiplierName = multiplierNames[i];
if (skill[multiplierName] != null && !isNaN(skill[multiplierName])) {
var value = skill[multiplierName] * level;
var multiplierValue = 1 + (value / 100);
if (multiplierName === "actionTime") {
multiplierValue = 1 - (value / 100);
}
this.skillMultipliers[multiplierName] *= multiplierValue;
}
}
}
}
}
Bladeburner.prototype.upgradeSkill = function(skill) {
// This does NOT handle deduction of skill points
var skillName = skill.name;
if (this.skills[skillName]) {
++this.skills[skillName];
} else {
this.skills[skillName] = 1;
}
if (isNaN(this.skills[skillName]) || this.skills[skillName] < 0) {
throw new Error("Level of Skill " + skillName + " is invalid: " + this.skills[skillName]);
}
this.updateSkillMultipliers();
}
Bladeburner.prototype.getActionObject = function(actionId) {
/**
* Given an ActionIdentifier object, returns the corresponding
* GeneralAction, Contract, Operation, or BlackOperation object
*/
switch (actionId.type) {
case ActionTypes["Contract"]:
return this.contracts[actionId.name];
case ActionTypes["Operation"]:
return this.operations[actionId.name];
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
return BlackOperations[actionId.name];
case ActionTypes["Training"]:
return GeneralActions["Training"];
case ActionTypes["Field Analysis"]:
return GeneralActions["Field Analysis"];
case ActionTypes["Recruitment"]:
return GeneralActions["Recruitment"];
default:
return null;
}
}
// Sets the player to the "IDLE" action
Bladeburner.prototype.resetAction = function() {
this.action = new ActionIdentifier({type:ActionTypes.Idle});
}
Bladeburner.prototype.startAction = function(actionId) {
if (actionId == null) {return;}
this.action = actionId;
this.actionTimeCurrent = 0;
switch (actionId.type) {
case ActionTypes["Idle"]:
this.actionTimeToComplete = 0;
break;
case ActionTypes["Contract"]:
try {
var action = this.getActionObject(actionId);
if (action == null) {
throw new Error("Failed to get Contract Object for: " + actionId.name);
}
if (action.count < 1) {return this.resetAction();}
this.actionTimeToComplete = action.getActionTime(this);
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
break;
case ActionTypes["Operation"]:
try {
var action = this.getActionObject(actionId);
if (action == null) {
throw new Error ("Failed to get Operation Object for: " + actionId.name);
}
if (action.count < 1) {return this.resetAction();}
if (actionId.name === "Raid" && this.getCurrentCity().commsEst === 0) {return this.resetAction();}
this.actionTimeToComplete = action.getActionTime(this);
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
break;
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
try {
// Safety measure - don't repeat BlackOps that are already done
if (this.blackops[actionId.name] != null) {
this.resetAction();
this.log("Error: Tried to start a Black Operation that had already been completed");
break;
}
var action = this.getActionObject(actionId);
if (action == null) {
throw new Error("Failed to get BlackOperation object for: " + actionId.name);
}
this.actionTimeToComplete = action.getActionTime(this);
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
break;
case ActionTypes["Recruitment"]:
this.actionTimeToComplete = this.getRecruitmentTime();
break;
case ActionTypes["Training"]:
case ActionTypes["FieldAnalysis"]:
case ActionTypes["Field Analysis"]:
this.actionTimeToComplete = 30;
break;
case ActionTypes["Diplomacy"]:
case ActionTypes["Hyperbolic Regeneration Chamber"]:
this.actionTimeToComplete = 60;
break;
default:
throw new Error("Invalid Action Type in Bladeburner.startAction(): " + actionId.type);
break;
}
}
Bladeburner.prototype.processAction = function(seconds) {
if (this.action.type === ActionTypes["Idle"]) {return;}
if (this.actionTimeToComplete <= 0) {
console.log("action.type: " + this.action.type);
throw new Error("Invalid actionTimeToComplete value: " + this.actionTimeToComplete);
}
if (!(this.action instanceof ActionIdentifier)) {
throw new Error("Bladeburner.action is not an ActionIdentifier Object");
}
this.actionTimeCurrent += seconds;
if (this.actionTimeCurrent >= this.actionTimeToComplete) {
return this.completeAction();
}
}
Bladeburner.prototype.completeAction = function() {
switch (this.action.type) {
case ActionTypes["Contract"]:
case ActionTypes["Operation"]:
try {
var isOperation = (this.action.type === ActionTypes["Operation"]);
var action = this.getActionObject(this.action);
if (action == null) {
throw new Error("Failed to get Contract/Operation Object for: " + this.action.name);
}
var difficulty = action.getDifficulty();
var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
var rewardMultiplier = Math.pow(action.rewardFac, action.level-1);
// Stamina loss is based on difficulty
this.stamina -= (BaseStaminaLoss * difficultyMultiplier);
if (this.stamina < 0) {this.stamina = 0;}
// Process Contract/Operation success/failure
if (action.attempt(this)) {
this.gainActionStats(action, true);
++action.successes;
--action.count;
// Earn money for contracts
var moneyGain = 0;
if (!isOperation) {
moneyGain = ContractBaseMoneyGain * rewardMultiplier * this.skillMultipliers.money;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainMoney(moneyGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].recordMoneySource(moneyGain, "bladeburner");
}
if (isOperation) {
action.setMaxLevel(OperationSuccessesPerLevel);
} else {
action.setMaxLevel(ContractSuccessesPerLevel);
}
if (action.rankGain) {
var gain = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(action.rankGain * rewardMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerRank, 10);
this.changeRank(gain);
if (isOperation && this.logging.ops) {
this.log(action.name + " successfully completed! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(gain, 3) + " rank");
} else if (!isOperation && this.logging.contracts) {
this.log(action.name + " contract successfully completed! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(gain, 3) + " rank and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__["numeralWrapper"].format(moneyGain, "$0.000a"));
}
}
isOperation ? this.completeOperation(true) : this.completeContract(true);
} else {
this.gainActionStats(action, false);
++action.failures;
var loss = 0, damage = 0;
if (action.rankLoss) {
loss = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(action.rankLoss * rewardMultiplier, 10);
this.changeRank(-1 * loss);
}
if (action.hpLoss) {
damage = action.hpLoss * difficultyMultiplier;
damage = Math.ceil(Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(damage, 10));
this.hpLost += damage;
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].takeDamage(damage)) {
++this.numHosp;
this.moneyLost += (_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].max_hp);
}
}
var logLossText = "";
if (loss > 0) {logLossText += "Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(loss, 3) + " rank.";}
if (damage > 0) {logLossText += "Took " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(damage, 0) + " damage.";}
if (isOperation && this.logging.ops) {
this.log(action.name + " failed! " + logLossText);
} else if (!isOperation && this.logging.contracts) {
this.log(action.name + " contract failed! " + logLossText);
}
isOperation ? this.completeOperation(false) : this.completeContract(false);
}
if (action.autoLevel) {action.level = action.maxLevel;} // Autolevel
this.startAction(this.action); // Repeat action
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
break;
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
try {
var action = this.getActionObject(this.action);
if (action == null || !(action instanceof BlackOperation)) {
throw new Error("Failed to get BlackOperation Object for: " + this.action.name);
}
var difficulty = action.getDifficulty();
var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
// Stamina loss is based on difficulty
this.stamina -= (BaseStaminaLoss * difficultyMultiplier);
if (this.stamina < 0) {this.stamina = 0;}
// Team loss variables
var teamCount = action.teamCount, teamLossMax;
if (action.attempt(this)) {
this.gainActionStats(action, true);
action.count = 0;
this.blackops[action.name] = true;
var rankGain = 0;
if (action.rankGain) {
rankGain = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(action.rankGain * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerRank, 10);
this.changeRank(rankGain);
}
teamLossMax = Math.ceil(teamCount/2);
// Operation Daedalus
if (action.name === "Operation Daedalus") {
this.resetAction();
return Object(_RedPill__WEBPACK_IMPORTED_MODULE_9__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bitNodeN);
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner)) {
this.createActionAndSkillsContent();
}
if (this.logging.blackops) {
this.log(action.name + " successful! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(rankGain, 1) + " rank");
}
} else {
this.gainActionStats(action, false);
var rankLoss = 0, damage = 0;
if (action.rankLoss) {
rankLoss = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(action.rankLoss, 10);
this.changeRank(-1 * rankLoss);
}
if (action.hpLoss) {
damage = action.hpLoss * difficultyMultiplier;
damage = Math.ceil(Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__["addOffset"])(damage, 10));
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].takeDamage(damage)) {
++this.numHosp;
this.moneyLost += (_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].max_hp);
}
}
teamLossMax = Math.floor(teamCount);
if (this.logging.blackops) {
this.log(action.name + " failed! Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(rankLoss, 1) + " rank and took " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(damage, 0) + " damage");
}
}
this.resetAction(); // Stop regardless of success or fail
// Calculate team lossses
if (teamCount >= 1) {
var losses = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, teamLossMax);
this.teamSize -= losses;
this.teamLost += losses;
if (this.logging.blackops) {
this.log("You lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(losses, 0) + " team members during " + action.name);
}
}
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
break;
case ActionTypes["Training"]:
this.stamina -= (0.5 * BaseStaminaLoss);
var strExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].strength_exp_mult,
defExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].defense_exp_mult,
dexExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].dexterity_exp_mult,
agiExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility_exp_mult,
staminaGain = 0.04 * this.skillMultipliers.stamina;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainStrengthExp(strExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainDefenseExp(defExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainDexterityExp(dexExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainAgilityExp(agiExpGain);
this.staminaBonus += (staminaGain);
if (this.logging.general) {
this.log("Training completed. Gained: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(strExpGain, 1) + " str exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(defExpGain, 1) + " def exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(dexExpGain, 1) + " dex exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(agiExpGain, 1) + " agi exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(staminaGain, 3) + " max stamina");
}
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
var eff = 0.04 * Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hacking_skill, 0.3) +
0.04 * Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].intelligence, 0.9) +
0.02 * Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma, 0.3);
eff *= _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_analysis_mult;
if (isNaN(eff) || eff < 0) {
throw new Error("Field Analysis Effectiveness calculated to be NaN or negative");
}
var hackingExpGain = 20 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hacking_exp_mult,
charismaExpGain = 20 * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma_exp_mult;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainHackingExp(hackingExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainIntelligenceExp(BaseIntGain);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainCharismaExp(charismaExpGain);
this.changeRank(0.1 * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerRank);
this.getCurrentCity().improvePopulationEstimateByPercentage(eff * this.skillMultipliers.successChanceEstimate);
if (this.logging.general) {
this.log("Field analysis completed. Gained 0.1 rank, " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(hackingExpGain, 1) + " hacking exp, and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(charismaExpGain, 1) + " charisma exp");
}
this.startAction(this.action); // Repeat action
break;
case ActionTypes["Recruitment"]:
var successChance = this.getRecruitmentSuccessChance();
if (Math.random() < successChance) {
var expGain = 2 * BaseStatGain * this.actionTimeToComplete;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainCharismaExp(expGain);
++this.teamSize;
if (this.logging.general) {
this.log("Successfully recruited a team member! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(expGain, 1) + " charisma exp");
}
} else {
var expGain = BaseStatGain * this.actionTimeToComplete;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainCharismaExp(expGain);
if (this.logging.general) {
this.log("Failed to recruit a team member. Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(expGain, 1) + " charisma exp");
}
}
this.startAction(this.action); // Repeat action
break;
case ActionTypes["Diplomacy"]:
var eff = this.getDiplomacyEffectiveness();
this.getCurrentCity().chaos *= eff;
if (this.getCurrentCity().chaos < 0) { this.getCurrentCity().chaos = 0; }
if (this.logging.general) {
this.log(`Diplomacy completed. Chaos levels in the current city fell by ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__["numeralWrapper"].formatPercentage(1 - eff)}`);
}
this.startAction(this.action); // Repeat Action
break;
case ActionTypes["Hyperbolic Regeneration Chamber"]: {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].regenerateHp(HrcHpGain);
const staminaGain = this.maxStamina * (HrcStaminaGain / 100);
this.stamina = Math.min(this.maxStamina, this.stamina + staminaGain);
this.startAction(this.action);
if (this.logging.general) {
this.log(`Rested in Hyperbolic Regeneration Chamber. Restored ${HrcHpGain} HP and gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__["numeralWrapper"].format(staminaGain, "0.0")} stamina`);
}
break;
}
default:
console.error(`Bladeburner.completeAction() called for invalid action: ${this.action.type}`);
break;
}
}
Bladeburner.prototype.completeContract = function(success) {
if (this.action.type !== ActionTypes.Contract) {
throw new Error("completeContract() called even though current action is not a Contract");
}
var city = this.getCurrentCity();
if (success) {
switch (this.action.name) {
case "Tracking":
// Increase estimate accuracy by a relatively small amount
city.improvePopulationEstimateByCount(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(100, 1e3));
break;
case "Bounty Hunter":
city.changePopulationByCount(-1, {estChange:-1});
city.changeChaosByCount(0.02);
break;
case "Retirement":
city.changePopulationByCount(-1, {estChange:-1});
city.changeChaosByCount(0.04);
break;
default:
throw new Error("Invalid Action name in completeContract: " + this.action.name);
}
}
}
Bladeburner.prototype.completeOperation = function(success) {
if (this.action.type !== ActionTypes.Operation) {
throw new Error("completeOperation() called even though current action is not an Operation");
}
var action = this.getActionObject(this.action);
if (action == null) {
throw new Error("Failed to get Contract/Operation Object for: " + this.action.name);
}
// Calculate team losses
var teamCount = action.teamCount, max;
if (teamCount >= 1) {
if (success) {
max = Math.ceil(teamCount/2);
} else {
max = Math.floor(teamCount)
}
var losses = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, max);
this.teamSize -= losses;
this.teamLost += losses;
if (this.logging.ops && losses > 0) {
this.log("Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(losses, 0) + " team members during this " + action.name);
}
}
var city = this.getCurrentCity();
switch (action.name) {
case "Investigation":
if (success) {
city.improvePopulationEstimateByPercentage(0.4 * this.skillMultipliers.successChanceEstimate);
if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) {
city.improveCommunityEstimate(1);
}
} else {
this.triggerPotentialMigration(this.city, 0.1);
}
break;
case "Undercover Operation":
if (success) {
city.improvePopulationEstimateByPercentage(0.8 * this.skillMultipliers.successChanceEstimate);
if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) {
city.improveCommunityEstimate(1);
}
} else {
this.triggerPotentialMigration(this.city, 0.15);
}
break;
case "Sting Operation":
if (success) {
city.changePopulationByPercentage(-0.1, {changeEstEqually:true, nonZero:true});
}
city.changeChaosByCount(0.1);
break;
case "Raid":
if (success) {
city.changePopulationByPercentage(-1, {changeEstEqually:true, nonZero:true});
--city.comms;
--city.commsEst;
} else {
var change = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(-10, -5) / 10;
city.changePopulationByPercentage(change, {nonZero:true});
}
city.changeChaosByPercentage(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(1, 5));
break;
case "Stealth Retirement Operation":
if (success) {
city.changePopulationByPercentage(-0.5, {changeEstEqually:true,nonZero:true});
}
city.changeChaosByPercentage(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(-3, -1));
break;
case "Assassination":
if (success) {
city.changePopulationByCount(-1, {estChange:-1});
}
city.changeChaosByPercentage(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(-5, 5));
break;
default:
throw new Error("Invalid Action name in completeOperation: " + this.action.name);
}
}
Bladeburner.prototype.getRecruitmentTime = function() {
var effCharisma = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma * this.skillMultipliers.effCha;
var charismaFactor = Math.pow(effCharisma, 0.81) + effCharisma / 90;
return Math.max(10, Math.round(BaseRecruitmentTimeNeeded - charismaFactor));
}
Bladeburner.prototype.getRecruitmentSuccessChance = function() {
return Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma, 0.45) / (this.teamSize + 1);
}
Bladeburner.prototype.getDiplomacyEffectiveness = function() {
// Returns a decimal by which the city's chaos level should be multiplied (e.g. 0.98)
const CharismaLinearFactor = 1e3;
const CharismaExponentialFactor = 0.045;
const charismaEff = Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma, CharismaExponentialFactor) + _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma / CharismaLinearFactor;
return (100 - charismaEff) / 100;
}
/**
* 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
*/
var difficultyMult = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
var time = this.actionTimeToComplete;
var successMult = success ? 1 : 0.5;
var unweightedGain = time * BaseStatGain * successMult * difficultyMult;
var unweightedIntGain = time * BaseIntGain * successMult * difficultyMult;
const skillMult = this.skillMultipliers.expGain;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainHackingExp(unweightedGain * action.weights.hack * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hacking_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainStrengthExp(unweightedGain * action.weights.str * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].strength_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainDefenseExp(unweightedGain * action.weights.def * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].defense_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainDexterityExp(unweightedGain * action.weights.dex * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].dexterity_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainAgilityExp(unweightedGain * action.weights.agi * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainCharismaExp(unweightedGain * action.weights.cha * _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].charisma_exp_mult * skillMult);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainIntelligenceExp(unweightedIntGain * action.weights.int * skillMult);
}
Bladeburner.prototype.randomEvent = function() {
var chance = Math.random();
// Choose random source/destination city for events
var sourceCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, 5)];
var sourceCity = this.cities[sourceCityName];
if (!(sourceCity instanceof City)) {
throw new Error("sourceCity was not a City object in Bladeburner.randomEvent()");
}
var destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, 5)];
while (destCityName === sourceCityName) {
destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, 5)];
}
var destCity = this.cities[destCityName];
if (!(sourceCity instanceof City) || !(destCity instanceof City)) {
throw new Error("sourceCity/destCity was not a City object in Bladeburner.randomEvent()");
}
if (chance <= 0.05) {
// New Synthoid Community, 5%
++sourceCity.comms;
var percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop += count;
if (this.logging.events) {
this.log("Intelligence indicates that a new Synthoid community was formed in a city");
}
} else if (chance <= 0.1) {
// Synthoid Community Migration, 5%
if (sourceCity.comms <= 0) {
// If no comms in source city, then instead trigger a new Synthoid community event
++sourceCity.comms;
var percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop += count;
if (this.logging.events) {
this.log("Intelligence indicates that a new Synthoid community was formed in a city");
}
} else {
--sourceCity.comms;
++destCity.comms;
// Change pop
var percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
destCity.pop += count;
if (this.logging.events) {
this.log("Intelligence indicates that a Synthoid community migrated from " + sourceCityName + " to some other city");
}
}
} else if (chance <= 0.3) {
// New Synthoids (non community), 20%
var percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(8, 24) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop += count;
if (this.logging.events) {
this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly");
}
} else if (chance <= 0.5) {
// 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%
sourceCity.chaos += 1;
sourceCity.chaos *= (1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["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%
var percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(8, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
if (this.logging.events) {
this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly");
}
}
// 10% chance of nothing happening
}
Bladeburner.prototype.triggerPotentialMigration = function(sourceCityName, chance) {
if (chance == null || isNaN(chance)) {
console.log("ERROR: Invalid 'chance' parameter passed into Bladeburner.triggerPotentialMigration()");
}
if (chance > 1) {chance /= 100;}
if (Math.random() < chance) {this.triggerMigration(sourceCityName);}
}
Bladeburner.prototype.triggerMigration = function(sourceCityName) {
var destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, 5)];
while (destCityName === sourceCityName) {
destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(0, 5)];
}
var destCity = this.cities[destCityName];
var sourceCity = this.cities[sourceCityName];
if (destCity == null || sourceCity == null) {
throw new Error("Failed to find City with name: " + destCityName);
}
var rand = Math.random(), percentage = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(3, 15) / 100;
if (rand < 0.05 && sourceCity.comms > 0) { // 5% chance for community migration
percentage *= Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_20__["getRandomInt"])(2, 4); // Migration increases population change
--sourceCity.comms;
++destCity.comms;
}
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
destCity.pop += count;
}
let DomElems = {};
Bladeburner.prototype.initializeDomElementRefs = function() {
DomElems = {
bladeburnerDiv: null,
// 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
consoleDiv: null,
consoleTable: null,
consoleInputRow: null, // tr
consoleInputCell: null, // td
consoleInputHeader: null, // "> "
consoleInput: null, // Actual input element
// Overview Content
overviewRank: null,
overviewStamina: null,
overviewStaminaHelpTip: null,
overviewGen1: null, // Stamina Penalty, Team, Hospitalized stats, current city
overviewEstPop: null,
overviewEstPopHelpTip: null,
overviewEstComms: null,
overviewChaos: null,
overviewSkillPoints: null,
overviewBonusTime: null,
overviewAugSuccessMult: null,
overviewAugMaxStaminaMult: null,
overviewAugStaminaGainMult: null,
overviewAugAnalysisMult: null,
// Actions and Skills Content
actionsAndSkillsDesc: null,
actionsAndSkillsList: null, // ul element of all UI elements in this panel
generalActions: {},
contracts: {},
operations: {},
blackops: {},
skills: {},
skillPointsDisplay: null,
};
}
Bladeburner.prototype.createContent = function() {
DomElems.bladeburnerDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
id:"bladeburner-container", position:"fixed", class:"generic-menupage-container",
});
// Parent Div for Overview and Console
DomElems.overviewConsoleParentDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
height:"60%", display:"block", position:"relative",
});
// Overview and Action/Skill pane
DomElems.overviewDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
width:"30%", display:"inline-block", border:"1px solid white",
});
DomElems.actionAndSkillsDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
height:"60%", width:"70%", display:"block",
border:"1px solid white", margin:"6px", padding:"6px",
});
DomElems.currentTab = "general";
this.createOverviewContent();
this.createActionAndSkillsContent();
// Console
DomElems.consoleDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-console-div",
clickListener:()=>{
if (DomElems.consoleInput instanceof Element) {
DomElems.consoleInput.focus();
}
return false;
}
});
DomElems.consoleTable = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("table", {class:"bladeburner-console-table"});
DomElems.consoleInputRow = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("tr", {class:"bladeburner-console-input-row", id:"bladeubrner-console-input-row"});
DomElems.consoleInputCell = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("td", {class:"bladeburner-console-input-cell"});
DomElems.consoleInputHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", {innerText:"> "});
DomElems.consoleInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", {
type:"text", class:"bladeburner-console-input", tabIndex:1,
onfocus:()=>{DomElems.consoleInput.value = DomElems.consoleInput.value}
});
DomElems.consoleInputCell.appendChild(DomElems.consoleInputHeader);
DomElems.consoleInputCell.appendChild(DomElems.consoleInput);
DomElems.consoleInputRow.appendChild(DomElems.consoleInputCell);
DomElems.consoleTable.appendChild(DomElems.consoleInputRow);
DomElems.consoleDiv.appendChild(DomElems.consoleTable);
DomElems.overviewConsoleParentDiv.appendChild(DomElems.overviewDiv);
DomElems.overviewConsoleParentDiv.appendChild(DomElems.consoleDiv);
DomElems.bladeburnerDiv.appendChild(DomElems.overviewConsoleParentDiv);
DomElems.bladeburnerDiv.appendChild(DomElems.actionAndSkillsDiv);
// legend
const legend = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div")
legend.innerHTML = `${stealthIcon}= This action requires stealth, ${killIcon} = This action involves retirement`
DomElems.bladeburnerDiv.appendChild(legend);
document.getElementById("entire-game-container").appendChild(DomElems.bladeburnerDiv);
if (this.consoleLogs.length === 0) {
this.postToConsole("Bladeburner Console BETA");
this.postToConsole("Type 'help' to see console commands");
} else {
for (let i = 0; i < this.consoleLogs.length; ++i) {
this.postToConsole(this.consoleLogs[i], false);
}
}
DomElems.consoleInput.focus();
}
Bladeburner.prototype.clearContent = function() {
if (DomElems.bladeburnerDiv instanceof Element) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(DomElems.bladeburnerDiv);
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_27__["removeElement"])(DomElems.bladeburnerDiv);
}
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems);
this.initializeDomElementRefs();
}
Bladeburner.prototype.createOverviewContent = function() {
if (DomElems.overviewDiv == null) {
throw new Error("Bladeburner.createOverviewContent() called with DomElems.overviewDiv = null");
}
DomElems.overviewRank = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerText:"Rank: ",
display:"inline-block",
tooltip:"Your rank within the Bladeburner division",
});
DomElems.overviewStamina = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
display:"inline-block",
});
DomElems.overviewStaminaHelpTip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"help-tip",
innerText:"?",
clickListener: ()=> {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("Performing actions will use up your stamina.
" +
"Your max stamina is determined primarily by your agility stat.
" +
"Your stamina gain rate is determined by both your agility and your " +
"max stamina. Higher max stamina leads to a higher gain rate.
" +
"Once your " +
"stamina falls below 50% of its max value, it begins to negatively " +
"affect the success rate of your contracts/operations. This penalty " +
"is shown in the overview panel. If the penalty is 15%, then this means " +
"your success rate would be multipled by 85% (100 - 15).
" +
"Your max stamina and stamina gain rate can also be increased by " +
"training, or through skills and Augmentation upgrades.");
},
});
DomElems.overviewGen1 = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
display:"block",
});
DomElems.overviewEstPop = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerText:"Est. Synthoid Population: ",
display:"inline-block",
tooltip:"This is your Bladeburner division's estimate of how many Synthoids exist " +
"in your current city."
});
DomElems.overviewEstPopHelpTip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
innerText:"?", class:"help-tip",
clickListener:()=>{
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("The success rate of your contracts/operations depends on " +
"the population of Synthoids in your current city. " +
"The success rate that is shown to you is only an estimate, " +
"and it is based on your Synthoid population estimate.
" +
"Therefore, it is important that this Synthoid population estimate " +
"is accurate so that you have a better idea of your " +
"success rate for contracts/operations. Certain " +
"actions will increase the accuracy of your population " +
"estimate.
" +
"The Synthoid populations of cities can change due to your " +
"actions or random events. If random events occur, they will " +
"be logged in the Bladeburner Console.");
}
});
DomElems.overviewEstComms = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerText:"Est. Synthoid Communities: ",
display:"inline-block",
tooltip:"This is your Bladeburner divison's estimate of how many Synthoid " +
"communities exist in your current city.",
});
DomElems.overviewChaos = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerText:"City Chaos: ",
display:"inline-block",
tooltip:"The city's chaos level due to tensions and conflicts between humans and Synthoids. " +
"Having too high of a chaos level can make contracts and operations harder."
});
DomElems.overviewBonusTime = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerText: "Bonus time: ",
display: "inline-block",
tooltip: "You gain bonus time while offline or when the game is inactive (e.g. when the tab is throttled by browser). " +
"Bonus time makes the Bladeburner mechanic progress faster, up to 5x the normal speed."
});
DomElems.overviewSkillPoints = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {display:"block"});
DomElems.overviewAugSuccessMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {display:"block"});
DomElems.overviewAugMaxStaminaMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {display:"block"});
DomElems.overviewAugStaminaGainMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {display:"block"});
DomElems.overviewAugAnalysisMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {display:"block"});
DomElems.overviewDiv.appendChild(DomElems.overviewRank);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewStamina);
DomElems.overviewDiv.appendChild(DomElems.overviewStaminaHelpTip);
DomElems.overviewDiv.appendChild(DomElems.overviewGen1);
DomElems.overviewDiv.appendChild(DomElems.overviewEstPop);
DomElems.overviewDiv.appendChild(DomElems.overviewEstPopHelpTip);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewEstComms);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewChaos);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 2);
DomElems.overviewDiv.appendChild(DomElems.overviewBonusTime);
DomElems.overviewDiv.appendChild(DomElems.overviewSkillPoints);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewAugSuccessMult);
DomElems.overviewDiv.appendChild(DomElems.overviewAugMaxStaminaMult);
DomElems.overviewDiv.appendChild(DomElems.overviewAugStaminaGainMult);
DomElems.overviewDiv.appendChild(DomElems.overviewAugAnalysisMult);
// Travel to new city button
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
innerHTML:"Travel", class:"a-link-button", display:"inline-block",
clickListener:()=>{
var popupId = "bladeburner-travel-popup-cancel-btn";
var popupArguments = [];
popupArguments.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { // Cancel Button
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId); return false;
}
}))
popupArguments.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["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 " +
"your location in the game otherwise",
}));
for (var i = 0; i < CityNames.length; ++i) {
(function(inst, i) {
popupArguments.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
/**
* 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:()=>{
inst.city = CityNames[i];
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId);
inst.updateOverviewContent();
return false;
}
}));
})(this, i);
}
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])(popupId, popupArguments);
}
}));
// Faction button
const bladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["factionExists"])(bladeburnersFactionName)) {
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"][bladeburnersFactionName];
if (!(bladeburnerFac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_5__["Faction"])) {
throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button");
}
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
innerText:"Faction", class:"a-link-button", display:"inline-block",
tooltip:"Apply to the Bladeburner Faction, or go to the faction page if you are already a member",
clickListener:()=>{
if (bladeburnerFac.isMember) {
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_7__["displayFactionContent"])(bladeburnersFactionName);
} else {
if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_7__["joinFaction"])(bladeburnerFac);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("Congratulations! You were accepted into the Bladeburners faction");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(DomElems.overviewDiv);
this.createOverviewContent();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You need a rank of 25 to join the Bladeburners Faction!")
}
}
return false;
}
}));
}
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("br"));
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("br"));
this.updateOverviewContent();
}
Bladeburner.prototype.createActionAndSkillsContent = function() {
if (DomElems.currentTab == null) {DomElems.currentTab = "general";}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(DomElems.actionAndSkillsDiv);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems.generalActions);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems.contracts);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems.operations);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems.blackops);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(DomElems.skills);
//Navigation buttons
var currTab = DomElems.currentTab.toLowerCase();
var buttons = ["General", "Contracts", "Operations", "BlackOps", "Skills"];
for (var i = 0; i < buttons.length; ++i) {
(function(buttons, i, inst, currTab) {
DomElems.actionAndSkillsDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", {
innerText:buttons[i],
class:currTab === buttons[i].toLowerCase() ? "bladeburner-nav-button-inactive" : "bladeburner-nav-button",
clickListener:()=>{
DomElems.currentTab = buttons[i].toLowerCase();
inst.createActionAndSkillsContent();
return false;
}
}));
}) (buttons, i, this, currTab);
}
// General info/description for each action
DomElems.actionsAndSkillsDesc = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
display:"block", margin:"4px", padding:"4px"
});
// List for actions/skills
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(DomElems.actionsAndSkillsList);
DomElems.actionsAndSkillsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("ul");
switch(currTab) {
case "general":
this.createGeneralActionsContent();
break;
case "contracts":
this.createContractsContent();
break;
case "operations":
this.createOperationsContent();
break;
case "blackops":
this.createBlackOpsContent();
break;
case "skills":
this.createSkillsContent();
break;
default:
throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent");
}
this.updateContent();
DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsDesc);
DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsList);
}
Bladeburner.prototype.createGeneralActionsContent = function() {
if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) {
throw new Error("Bladeburner.createGeneralActionsContent called with either " +
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
DomElems.actionsAndSkillsDesc.innerText =
"These are generic actions that will assist you in your Bladeburner " +
"duties. They will not affect your Bladeburner rank in any way."
for (var actionName in GeneralActions) {
if (GeneralActions.hasOwnProperty(actionName)) {
DomElems.generalActions[actionName] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-action", name:actionName
});
DomElems.actionsAndSkillsList.appendChild(DomElems.generalActions[actionName]);
}
}
}
Bladeburner.prototype.createContractsContent = function() {
if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) {
throw new Error("Bladeburner.createContractsContent called with either " +
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
DomElems.actionsAndSkillsDesc.innerHTML =
"Complete contracts in order to increase your Bladeburner rank and earn money. " +
"Failing a contract will cause you to lose HP, which can lead to hospitalization.
" +
"You can unlock higher-level contracts by successfully completing them. " +
"Higher-level contracts are more difficult, but grant more rank, experience, and money.";
for (var contractName in this.contracts) {
if (this.contracts.hasOwnProperty(contractName)) {
DomElems.contracts[contractName] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-action", name:contractName
});
DomElems.actionsAndSkillsList.appendChild(DomElems.contracts[contractName]);
}
}
}
Bladeburner.prototype.createOperationsContent = function() {
if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) {
throw new Error("Bladeburner.createOperationsContent called with either " +
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
DomElems.actionsAndSkillsDesc.innerHTML =
"Carry out operations for the Bladeburner division. " +
"Failing an operation will reduce your Bladeburner rank. It will also " +
"cause you to lose HP, which can lead to hospitalization. In general, " +
"operations are harder and more punishing than contracts, " +
"but are also more rewarding.
" +
"Operations can affect the chaos level and Synthoid population of your " +
"current city. The exact effects vary between different Operations.
" +
"For operations, you can use a team. You must first recruit team members. " +
"Having a larger team will improves your chances of success.
" +
"You can unlock higher-level operations by successfully completing them. " +
"Higher-level operations are more difficult, but grant more rank and experience.";
for (var operationName in this.operations) {
if (this.operations.hasOwnProperty(operationName)) {
DomElems.operations[operationName] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-action", name:operationName
});
DomElems.actionsAndSkillsList.appendChild(DomElems.operations[operationName]);
}
}
}
Bladeburner.prototype.createBlackOpsContent = function() {
if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) {
throw new Error("Bladeburner.createBlackOpsContent called with either " +
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
DomElems.actionsAndSkillsDesc.innerHTML =
"Black Operations (Black Ops) are special, one-time covert operations. " +
"Each Black Op must be unlocked successively by completing " +
"the one before it.
" +
"Your ultimate goal to climb through the ranks of Bladeburners is to complete " +
"all of the Black Ops.
" +
"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
var blackops = [];
for (var blackopName in BlackOperations) {
if (BlackOperations.hasOwnProperty(blackopName)) {
blackops.push(BlackOperations[blackopName]);
}
}
blackops.sort(function(a, b) {
return (a.reqdRank - b.reqdRank);
});
for (var i = blackops.length-1; i >= 0 ; --i) {
if (this.blackops[[blackops[i].name]] == null && i !== 0 && this.blackops[[blackops[i-1].name]] == null) {continue;} // If this one nor the next are completed then this isn't unlocked yet.
DomElems.blackops[blackops[i].name] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-action", name:blackops[i].name
});
DomElems.actionsAndSkillsList.appendChild(DomElems.blackops[blackops[i].name]);
}
}
Bladeburner.prototype.createSkillsContent = function() {
if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) {
throw new Error("Bladeburner.createSkillsContent called with either " +
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
// 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. " +
"However, the effects of different skills with each other is multiplicative.
"
var multKeys = Object.keys(this.skillMultipliers);
for (var i = 0; i < multKeys.length; ++i) {
var mult = this.skillMultipliers[multKeys[i]];
if (mult && mult !== 1) {
mult = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(mult, 3);
switch(multKeys[i]) {
case "successChanceAll":
DomElems.actionsAndSkillsDesc.innerHTML += "Total Success Chance: x" + mult + " ";
break;
case "successChanceStealth":
DomElems.actionsAndSkillsDesc.innerHTML += "Stealth Success Chance: x" + mult + " ";
break;
case "successChanceKill":
DomElems.actionsAndSkillsDesc.innerHTML += "Retirement Success Chance: x" + mult + " ";
break;
case "successChanceContract":
DomElems.actionsAndSkillsDesc.innerHTML += "Contract Success Chance: x" + mult + " ";
break;
case "successChanceOperation":
DomElems.actionsAndSkillsDesc.innerHTML += "Operation Success Chance: x" + mult + " ";
break;
case "successChanceEstimate":
DomElems.actionsAndSkillsDesc.innerHTML += "Synthoid Data Estimate: x" + mult + " ";
break;
case "actionTime":
DomElems.actionsAndSkillsDesc.innerHTML += "Action Time: x" + mult + " ";
break;
case "effHack":
DomElems.actionsAndSkillsDesc.innerHTML += "Hacking Skill: x" + mult + " ";
break;
case "effStr":
DomElems.actionsAndSkillsDesc.innerHTML += "Strength: x" + mult + " ";
break;
case "effDef":
DomElems.actionsAndSkillsDesc.innerHTML += "Defense: x" + mult + " ";
break;
case "effDex":
DomElems.actionsAndSkillsDesc.innerHTML += "Dexterity: x" + mult + " ";
break;
case "effAgi":
DomElems.actionsAndSkillsDesc.innerHTML += "Agility: x" + mult + " ";
break;
case "effCha":
DomElems.actionsAndSkillsDesc.innerHTML += "Charisma: x" + mult + " ";
break;
case "effInt":
DomElems.actionsAndSkillsDesc.innerHTML += "Intelligence: x" + mult + " ";
break;
case "stamina":
DomElems.actionsAndSkillsDesc.innerHTML += "Stamina: x" + mult + " ";
break;
case "money":
DomElems.actionsAndSkillsDesc.innerHTML += "Contract Money: x" + mult + " ";
break;
case "expGain":
DomElems.actionsAndSkillsDesc.innerHTML += "Exp Gain: x" + mult + " ";
break;
case "weaponAbility":
// TODO in the future if items are ever implemented
break;
case "gunAbility":
// TODO in the future if items are ever implemented
break;
default:
console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]);
break;
}
}
}
// Skill Points
DomElems.skillPointsDisplay = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", {
innerHTML:" Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.skillPoints, 0) + ""
});
DomElems.actionAndSkillsDiv.appendChild(DomElems.skillPointsDisplay);
// UI Element for each skill
for (var skillName in Skills) {
if (Skills.hasOwnProperty(skillName)) {
DomElems.skills[skillName] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", {
class:"bladeburner-action", name:skillName
});
DomElems.actionsAndSkillsList.appendChild(DomElems.skills[skillName]);
}
}
}
Bladeburner.prototype.updateContent = function() {
this.updateOverviewContent();
this.updateActionAndSkillsContent();
}
Bladeburner.prototype.updateOverviewContent = function() {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner)) {return;}
DomElems.overviewRank.childNodes[0].nodeValue = "Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.rank, 2);
DomElems.overviewStamina.innerText = "Stamina: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.stamina, 3) + " / " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.maxStamina, 3);
DomElems.overviewGen1.innerHTML =
"Stamina Penalty: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])((1-this.calculateStaminaPenalty())*100, 1) + "%
');
if (DomElems.consoleTable.childNodes.length > MaxConsoleEntries) {
DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild);
}
this.updateConsoleScroll();
}
Bladeburner.prototype.updateConsoleScroll = function() {
DomElems.consoleDiv.scrollTop = DomElems.consoleDiv.scrollHeight;
}
Bladeburner.prototype.resetConsoleInput = function() {
DomElems.consoleInput.value = "";
}
Bladeburner.prototype.clearConsole = function() {
while (DomElems.consoleTable.childNodes.length > 1) {
DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild);
}
this.consoleLogs.length = 0;
}
Bladeburner.prototype.log = function(input) {
// Adds a timestamp and then just calls postToConsole
this.postToConsole(`[${Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_21__["getTimestamp"])()}] ${input}`);
}
// Handles a potential series of commands (comm1; comm2; comm3;)
Bladeburner.prototype.executeConsoleCommands = function(commands) {
try {
// Console History
if (this.consoleHistory[this.consoleHistory.length-1] != commands) {
this.consoleHistory.push(commands);
if (this.consoleHistory.length > 50) {
this.consoleHistory.splice(0, 1);
}
}
consoleHistoryIndex = this.consoleHistory.length;
var arrayOfCommands = commands.split(";");
for (var i = 0; i < arrayOfCommands.length; ++i) {
this.executeConsoleCommand(arrayOfCommands[i]);
}
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_19__["exceptionAlert"])(e);
}
}
// 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
var args = this.parseCommandArguments(command);
if (args.length <= 0) {return;} // Log an error?
switch(args[0].toLowerCase()) {
case "automate":
this.executeAutomateConsoleCommand(args);
break;
case "clear":
case "cls":
this.clearConsole();
break;
case "help":
this.executeHelpConsoleCommand(args);
break;
case "log":
this.executeLogConsoleCommand(args);
break;
case "skill":
this.executeSkillConsoleCommand(args);
break;
case "start":
this.executeStartConsoleCommand(args);
break;
case "stop":
this.resetAction();
break;
default:
this.postToConsole("Invalid console command");
break;
}
}
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
*/
const args = [];
let start = 0, i = 0;
while (i < command.length) {
const c = command.charAt(i);
if (c === '"') { // Double quotes
const endQuote = command.indexOf('"', i+1);
if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) {
args.push(command.substr(i+1, (endQuote - i - 1)));
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
start = i = endQuote+2; // Skip the space
}
continue;
}
} else if (c === "'") { // Single quotes, same thing as above
const endQuote = command.indexOf("'", i+1);
if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) {
args.push(command.substr(i+1, (endQuote - i - 1)));
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
start = i = endQuote+2; // Skip the space
}
continue;
}
} else if (c === " ") {
args.push(command.substr(start, i-start));
start = i+1;
}
++i;
}
if (start !== i) {args.push(command.substr(start, i-start));}
console.log("Bladeburner console command parsing returned: " + args);
return args;
}
Bladeburner.prototype.executeAutomateConsoleCommand = function(args) {
if (args.length !== 2 && args.length !== 4) {
this.postToConsole("Invalid use of 'automate' command: automate [var] [val] [hi/low]. Use 'help automate' for more info");
return;
}
// Enable/Disable
if (args.length === 2) {
var flag = args[1];
if (flag.toLowerCase() === "status") {
this.postToConsole("Automation: " + (this.automateEnabled ? "enabled" : "disabled"));
if (this.automateEnabled) {
this.postToConsole("When your stamina drops to " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.automateThreshLow, 0) +
", you will automatically switch to " + this.automateActionLow.name +
". When your stamina recovers to " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.automateThreshHigh, 0) + ", you will automatically " +
"switch to " + this.automateActionHigh.name + ".");
}
} else if (flag.toLowerCase().includes("en")) {
if (!(this.automateActionLow instanceof ActionIdentifier) ||
!(this.automateActionHigh instanceof ActionIdentifier)) {
return this.log("Failed to enable automation. Actions were not set");
}
this.automateEnabled = true;
this.log("Bladeburner automation enabled");
} else if (flag.toLowerCase().includes("d")) {
this.automateEnabled = false;
this.log("Bladeburner automation disabled");
} else {
this.log("Invalid argument for 'automate' console command: " + args[1]);
}
return;
}
// Set variables
if (args.length === 4) {
var variable = args[1], val = args[2];
var highLow = false; // True for high, false for low
if (args[3].toLowerCase().includes("hi")) {highLow = true;}
switch (variable) {
case "general":
case "gen":
if (GeneralActions[val] != null) {
var action = new ActionIdentifier({
type:ActionTypes[val], name:val
});
if (highLow) {
this.automateActionHigh = action;
} else {
this.automateActionLow = action;
}
this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val);
} else {
this.postToConsole("Invalid action name specified: " + val);
}
break;
case "contract":
case "contracts":
if (this.contracts[val] != null) {
var action = new ActionIdentifier({
type:ActionTypes.Contract, name:val
});
if (highLow) {
this.automateActionHigh = action;
} else {
this.automateActionLow = action;
}
this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val);
} else {
this.postToConsole("Invalid contract name specified: " + val);
}
break;
case "ops":
case "op":
case "operations":
case "operation":
if (this.operations[val] != null) {
var action = new ActionIdentifier({
type:ActionTypes.Operation, name:val
});
if (highLow) {
this.automateActionHigh = action;
} else {
this.automateActionLow = action;
}
this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val);
} else {
this.postToConsole("Invalid Operation name specified: " + val);
}
break;
case "stamina":
if (isNaN(val)) {
this.postToConsole("Invalid value specified for stamina threshold (must be numeric): " + val);
} else {
if (highLow) {
this.automateThreshHigh = Number(val);
} else {
this.automateThreshLow = Number(val);
}
this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") stamina threshold set to " + val);
}
break;
default:
break;
}
return;
}
}
Bladeburner.prototype.executeHelpConsoleCommand = function(args) {
if (args.length === 1) {
this.postToConsole(consoleHelpText.helpList);
} else {
for (var i = 1; i < args.length; ++i) {
var commandText = consoleHelpText[args[i]];
if (commandText != null) {
this.postToConsole(commandText);
this.postToConsole(" ");
}
}
}
}
Bladeburner.prototype.executeLogConsoleCommand = function(args) {
if (args.length < 3) {
this.postToConsole("Invalid usage of log command: log [enable/disable] [action/event]");
this.postToConsole("Use 'help log' for more details and examples");
return;
}
var flag = true;
if (args[1].toLowerCase().includes("d")) {flag = false;} // d for disable
switch (args[2].toLowerCase()) {
case "general":
case "gen":
this.logging.general = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for general actions");
break;
case "contract":
case "contracts":
this.logging.contracts = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for Contracts");
break;
case "ops":
case "op":
case "operations":
case "operation":
this.logging.ops = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for Operations");
break;
case "blackops":
case "blackop":
case "black operations":
case "black operation":
this.logging.blackops = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for BlackOps");
break;
case "event":
case "events":
this.logging.events = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for events");
break;
case "all":
this.logging.general = flag;
this.logging.contracts = flag;
this.logging.ops = flag;
this.logging.blackops = flag;
this.logging.events = flag;
this.log("Logging " + (flag ? "enabled" : "disabled") + " for everything");
break;
default:
this.postToConsole("Invalid action/event type specified: " + args[2]);
this.postToConsole("Examples of valid action/event identifiers are: [general, contracts, ops, blackops, events]");
break;
}
}
Bladeburner.prototype.executeSkillConsoleCommand = function(args) {
switch (args.length) {
case 1:
// 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
this.postToConsole("Skills: ");
var skillNames = Object.keys(Skills);
for(var i = 0; i < skillNames.length; ++i) {
var skill = Skills[skillNames[i]];
var level = 0;
if (this.skills[skill.name] != null) {level = this.skills[skill.name];}
this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(level, 0));
}
this.postToConsole(" ");
this.postToConsole("Effects: ");
var multKeys = Object.keys(this.skillMultipliers);
for (var i = 0; i < multKeys.length; ++i) {
var mult = this.skillMultipliers[multKeys[i]];
if (mult && mult !== 1) {
mult = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(mult, 3);
switch(multKeys[i]) {
case "successChanceAll":
this.postToConsole("Total Success Chance: x" + mult);
break;
case "successChanceStealth":
this.postToConsole("Stealth Success Chance: x" + mult);
break;
case "successChanceKill":
this.postToConsole("Retirement Success Chance: x" + mult);
break;
case "successChanceContract":
this.postToConsole("Contract Success Chance: x" + mult);
break;
case "successChanceOperation":
this.postToConsole("Operation Success Chance: x" + mult);
break;
case "successChanceEstimate":
this.postToConsole("Synthoid Data Estimate: x" + mult);
break;
case "actionTime":
this.postToConsole("Action Time: x" + mult);
break;
case "effHack":
this.postToConsole("Hacking Skill: x" + mult);
break;
case "effStr":
this.postToConsole("Strength: x" + mult);
break;
case "effDef":
this.postToConsole("Defense: x" + mult);
break;
case "effDex":
this.postToConsole("Dexterity: x" + mult);
break;
case "effAgi":
this.postToConsole("Agility: x" + mult);
break;
case "effCha":
this.postToConsole("Charisma: x" + mult);
break;
case "effInt":
this.postToConsole("Intelligence: x" + mult);
break;
case "stamina":
this.postToConsole("Stamina: x" + mult);
break;
case "weaponAbility":
// TODO if items are ever implemented
break;
case "gunAbility":
// TODO if items are ever implemented
break;
default:
console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]);
break;
}
}
}
} else {
this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]");
this.postToConsole("Use 'help skill' for more info");
}
break;
case 3:
var skillName = args[2];
var skill = Skills[skillName];
if (skill == null || !(skill instanceof Skill)) {
return this.postToConsole("Invalid skill name (Note that this is case-sensitive): " + skillName);
}
if (args[1].toLowerCase() === "list") {
this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.skills[skill.name]), 0);
} else if (args[1].toLowerCase() === "level") {
var currentLevel = 0;
if (this.skills[skillName] && !isNaN(this.skills[skillName])) {
currentLevel = this.skills[skillName];
}
var pointCost = skill.calculateCost(currentLevel);
if (this.skillPoints >= pointCost) {
this.skillPoints -= pointCost;
this.upgradeSkill(skill);
this.log(skill.name + " upgraded to Level " + this.skills[skillName]);
this.createActionAndSkillsContent();
} else {
this.postToConsole("You do not have enough Skill Points to upgrade this. You need " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(pointCost, 0));
}
} else {
this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]");
this.postToConsole("Use 'help skill' for more info");
}
break;
default:
this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]");
this.postToConsole("Use 'help skill' for more info");
break;
}
}
Bladeburner.prototype.executeStartConsoleCommand = function(args) {
if (args.length !== 3) {
this.postToConsole("Invalid usage of 'start' console command: start [type] [name]");
this.postToConsole("Use 'help start' for more info");
return;
}
var name = args[2];
switch (args[1].toLowerCase()) {
case "general":
case "gen":
if (GeneralActions[name] != null) {
this.action.type = ActionTypes[name];
this.action.name = name;
this.startAction(this.action);
this.updateActionAndSkillsContent();
} else {
this.postToConsole("Invalid action name specified: " + args[2]);
}
break;
case "contract":
case "contracts":
if (this.contracts[name] != null) {
this.action.type = ActionTypes.Contract;
this.action.name = name;
this.startAction(this.action);
this.updateActionAndSkillsContent();
} else {
this.postToConsole("Invalid contract name specified: " + args[2]);
}
break;
case "ops":
case "op":
case "operations":
case "operation":
if (this.operations[name] != null) {
this.action.type = ActionTypes.Operation;
this.action.name = name;
this.startAction(this.action);
this.updateActionAndSkillsContent();
} else {
this.postToConsole("Invalid Operation name specified: " + args[2]);
}
break;
case "blackops":
case "blackop":
case "black operations":
case "black operation":
if (BlackOperations[name] != null) {
this.action.type = ActionTypes.BlackOperation;
this.action.name = name;
this.startAction(this.action);
this.updateActionAndSkillsContent();
} else {
this.postToConsole("Invalid BlackOp name specified: " + args[2]);
}
break;
default:
this.postToConsole("Invalid action/event type specified: " + args[1]);
this.postToConsole("Examples of valid action/event identifiers are: [general, contract, op, blackop]");
break;
}
}
Bladeburner.prototype.getActionIdFromTypeAndName = function(type="", name="") {
if (type === "" || name === "") {return null;}
var action = new ActionIdentifier();
var convertedType = type.toLowerCase().trim();
var convertedName = name.toLowerCase().trim();
switch (convertedType) {
case "contract":
case "contracts":
case "contr":
action.type = ActionTypes["Contract"];
if (this.contracts.hasOwnProperty(name)) {
action.name = name;
return action;
} else {
return null;
}
break;
case "operation":
case "operations":
case "op":
case "ops":
action.type = ActionTypes["Operation"];
if (this.operations.hasOwnProperty(name)) {
action.name = name;
return action;
} else {
return null;
}
break;
case "blackoperation":
case "black operation":
case "black operations":
case "black op":
case "black ops":
case "blackop":
case "blackops":
action.type = ActionTypes["BlackOp"];
if (BlackOperations.hasOwnProperty(name)) {
action.name = name;
return action;
} else {
return null;
}
break;
case "general":
case "general action":
case "gen":
break;
default:
return null;
}
if (convertedType.startsWith("gen")) {
switch (convertedName) {
case "training":
action.type = ActionTypes["Training"];
action.name = "Training";
break;
case "recruitment":
case "recruit":
action.type = ActionTypes["Recruitment"];
action.name = "Recruitment";
break;
case "field analysis":
case "fieldanalysis":
action.type = ActionTypes["Field Analysis"];
action.name = "Field Analysis";
break;
case "diplomacy":
action.type = ActionTypes["Diplomacy"];
action.name = "Diplomacy";
break;
case "hyperbolic regeneration chamber":
action.type = ActionTypes["Hyperbolic Regeneration Chamber"];
action.name = "Hyperbolic Regeneration Chamber";
break;
default:
return null;
}
return action;
}
}
Bladeburner.prototype.getTypeAndNameFromActionId = function(actionId) {
var res = {};
let types = Object.keys(ActionTypes);
for (let i = 0; i < types.length; ++i) {
if (actionId.type === ActionTypes[types[i]]) {
res.type = types[i];
break;
}
}
if (res.type == null) {res.type = "Idle";}
res.name = actionId.name != null ? actionId.name : "Idle";
return res;
}
Bladeburner.prototype.getContractNamesNetscriptFn = function() {
return Object.keys(this.contracts);
}
Bladeburner.prototype.getOperationNamesNetscriptFn = function() {
return Object.keys(this.operations);
}
Bladeburner.prototype.getBlackOpNamesNetscriptFn = function() {
return Object.keys(BlackOperations);
}
Bladeburner.prototype.getGeneralActionNamesNetscriptFn = function() {
return Object.keys(GeneralActions);
}
Bladeburner.prototype.getSkillNamesNetscriptFn = function() {
return Object.keys(Skills);
}
Bladeburner.prototype.startActionNetscriptFn = function(type, name, workerScript) {
var errorLogText = "ERROR: bladeburner.startAction() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return false;
}
// Special logic for Black Ops
if (actionId.type === ActionTypes["BlackOp"]) {
// Can't start a BlackOp if you don't have the required rank
let action = this.getActionObject(actionId);
if (action.reqdRank > this.rank) {
workerScript.log(`Failed to start Black Op ${actionId.name} due to insufficient rank`);
return false;
}
// Can't start a BlackOp if its already been done
if (this.blackops[actionId.name] != null) {
workerScript.log(`Failed to start Black Op ${actionId.name} because its already been completed`);
return false;
}
// Can't start a BlackOp if you haven't done the one before it
var blackops = [];
for (const nm in BlackOperations) {
if (BlackOperations.hasOwnProperty(nm)) {
blackops.push(nm);
}
}
blackops.sort(function(a, b) {
return (BlackOperations[a].reqdRank - BlackOperations[b].reqdRank); // Sort black ops in intended order
});
let i = blackops.indexOf(actionId.name);
if (i === -1) {
workerScript.log("ERROR: Invalid Black Operation name passed into bladeburner.startAction(). Note that this name is case-sensitive & whitespace-sensitive");
return false;
}
if (i > 0 && this.blackops[blackops[i-1]] == null) {
workerScript.log(`ERROR: Cannot attempt Black Operation ${actionId.name} because you have not done the preceding one`);
return false;
}
}
try {
this.startAction(actionId);
if (workerScript.shouldLog("startAction")) {
workerScript.log("Starting bladeburner action with type " + type + " and name " + name);
}
return true;
} catch(e) {
this.resetAction();
workerScript.log("ERROR: bladeburner.startAction() failed to start action of type " + type + " due to invalid name: " + name +
"Note that this name is case-sensitive and whitespace-sensitive");
return false;
}
}
Bladeburner.prototype.getActionTimeNetscriptFn = function(type, name, workerScript) {
var errorLogText = "ERROR: bladeburner.getActionTime() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
var actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
switch (actionId.type) {
case ActionTypes["Contract"]:
case ActionTypes["Operation"]:
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
return actionObj.getActionTime(this);
case ActionTypes["Training"]:
case ActionTypes["Field Analysis"]:
case ActionTypes["FieldAnalysis"]:
return 30;
case ActionTypes["Recruitment"]:
return this.getRecruitmentTime();
default:
workerScript.log(errorLogText);
return -1;
}
}
Bladeburner.prototype.getActionEstimatedSuccessChanceNetscriptFn = function(type, name, workerScript) {
var errorLogText = "ERROR: bladeburner.getActionEstimatedSuccessChance() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
var actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
switch (actionId.type) {
case ActionTypes["Contract"]:
case ActionTypes["Operation"]:
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
return actionObj.getSuccessChance(this, {est:true});
case ActionTypes["Training"]:
case ActionTypes["Field Analysis"]:
case ActionTypes["FieldAnalysis"]:
return 1;
case ActionTypes["Recruitment"]:
return this.getRecruitmentSuccessChance();
default:
workerScript.log(errorLogText);
return -1;
}
}
Bladeburner.prototype.getActionCountRemainingNetscriptFn = function(type, name, workerScript) {
var errorLogText = "ERROR: bladeburner.getActionCountRemaining() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
var actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
switch (actionId.type) {
case ActionTypes["Contract"]:
case ActionTypes["Operation"]:
return Math.floor( actionObj.count );
case ActionTypes["BlackOp"]:
case ActionTypes["BlackOperation"]:
if (this.blackops[name] != null) {
return 0;
} else {
return 1;
}
case ActionTypes["Training"]:
case ActionTypes["Field Analysis"]:
case ActionTypes["FieldAnalysis"]:
return Infinity;
default:
workerScript.log(errorLogText);
return -1;
}
}
Bladeburner.prototype.getSkillLevelNetscriptFn = function(skillName, workerScript) {
var errorLogText = "ERROR: bladeburner.getSkillLevel() failed due to an invalid skill specified: " +
skillName + ". Note that the name of the skill is case-sensitive";
if (skillName === "") {
return -1;
}
if (!Skills.hasOwnProperty(skillName)) {
workerScript.log(errorLogText);
return -1;
}
if (this.skills[skillName] == null) {
return 0;
} else {
return this.skills[skillName];
}
}
Bladeburner.prototype.getSkillUpgradeCostNetscriptFn = function(skillName, workerScript) {
var errorLogText = "ERROR: bladeburner.getSkillUpgradeCostNetscriptFn() failed due to an invalid skill specified: " +
skillName + ". Note that the name of the skill is case-sensitive";
if (skillName === "") {
return -1;
}
if (!Skills.hasOwnProperty(skillName)) {
workerScript.log(errorLogText);
return -1;
}
var skill = Skills[skillName];
if (this.skills[skillName] == null) {
return skill.calculateCost(0);
} else {
return skill.calculateCost(this.skills[skillName]);
}
}
Bladeburner.prototype.upgradeSkillNetscriptFn = function(skillName, workerScript) {
var errorLogText = "ERROR: bladeburner.upgradeSkill() failed due to an invalid skill specified: " +
skillName + ". Note that the name of the skill is case-sensitive";
if (!Skills.hasOwnProperty(skillName)) {
workerScript.log(errorLogText);
return false;
}
var skill = Skills[skillName];
var currentLevel = 0;
if (this.skills[skillName] && !isNaN(this.skills[skillName])) {
currentLevel = this.skills[skillName];
}
var cost = skill.calculateCost(currentLevel);
if(skill.maxLvl && currentLevel >= skill.maxLvl) {
if (workerScript.shouldLog("upgradeSkill")) {
workerScript.log(`bladeburner.upgradeSkill() failed because ${skillName} is already maxed`);
}
return false;
}
if (this.skillPoints < cost) {
if (workerScript.shouldLog("upgradeSkill")) {
workerScript.log("bladeburner.upgradeSkill() failed because you do not have enough " +
"skill points to upgrade " + skillName + " (You have " +
this.skillPoints + ", you need " + cost + ")");
}
return false;
}
this.skillPoints -= cost;
this.upgradeSkill(skill);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner) && DomElems.currentTab.toLowerCase() === "skills") {
this.createActionAndSkillsContent();
}
if (workerScript.shouldLog("upgradeSkill")) {
workerScript.log(skillName + " successfully upgraded to level " + this.skills[skillName]);
}
return true;
}
Bladeburner.prototype.getTeamSizeNetscriptFn = function(type, name, workerScript) {
if (type === "" && name === "") {
return this.teamSize;
}
var errorLogText = "ERROR: bladeburner.getTeamSize() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
var actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
if (actionId.type === ActionTypes["Operation"] ||
actionId.type === ActionTypes["BlackOp"] ||
actionId.type === ActionTypes["BlackOperation"]) {
return actionObj.teamCount;
} else {
return 0;
}
}
Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, workerScript) {
var errorLogText = "ERROR: bladeburner.setTeamSize() failed due to an invalid action specified. " +
"Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " +
"name of the operation is case-sensitive.";
var actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
if (actionId.type !== ActionTypes["Operation"] &&
actionId.type !== ActionTypes["BlackOp"] &&
actionId.type !== ActionTypes["BlackOperation"]) {
workerScript.log("ERROR: bladeburner.setTeamSize() failed. This function " +
"only works for Operations and BlackOps");
return -1;
}
var actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
var sanitizedSize = Math.round(size);
if (isNaN(sanitizedSize)) {
workerScript.log("ERROR: bladeburner.setTeamSize() failed due to an invalid 'size' argument: " + size);
return -1;
}
if (this.teamSize < sanitizedSize) {sanitizedSize = this.teamSize;}
actionObj.teamCount = sanitizedSize;
if (workerScript.shouldLog("setTeamSize")) {
workerScript.log("Team size for " + name + " set to " + sanitizedSize);
}
return sanitizedSize;
}
Bladeburner.prototype.getCityEstimatedPopulationNetscriptFn = function(cityName, workerScript) {
if (!this.cities.hasOwnProperty(cityName)) {
workerScript.log("ERROR: bladeburner.getCityEstimatedPopulation() failed because the specified " +
"city was invalid: " + cityName + ". Note that this city argument is case-sensitive");
return -1;
}
return this.cities[cityName].popEst;
}
Bladeburner.prototype.getCityEstimatedCommunitiesNetscriptFn = function(cityName, workerScript) {
if (!this.cities.hasOwnProperty(cityName)) {
workerScript.log("ERROR: bladeburner.getCityEstimatedCommunities() failed because the specified " +
"city was invalid: " + cityName + ". Note that this city argument is case-sensitive");
return -1;
}
return this.cities[cityName].commsEst;
}
Bladeburner.prototype.getCityChaosNetscriptFn = function(cityName, workerScript) {
if (!this.cities.hasOwnProperty(cityName)) {
workerScript.log("ERROR: bladeburner.getCityChaos() failed because the specified " +
"city was invalid: " + cityName + ". Note that this city argument is case-sensitive");
return -1;
}
return this.cities[cityName].chaos;
}
Bladeburner.prototype.switchCityNetscriptFn = function(cityName, workerScript) {
if (!this.cities.hasOwnProperty(cityName)) {
workerScript.log("ERROR: bladeburner.switchCity() failed because the specified " +
"city was invalid: " + cityName + ". Note that this city argument is case-sensitive");
return false;
}
this.city = cityName;
return true;
}
Bladeburner.prototype.joinBladeburnerFactionNetscriptFn = function(workerScript) {
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"]["Bladeburners"];
if (bladeburnerFac.isMember) {
return true;
} else if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_7__["joinFaction"])(bladeburnerFac);
if (workerScript.shouldLog("joinBladeburnerFaction")) {
workerScript.log("Joined Bladeburners Faction");
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Bladeburner)) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(DomElems.overviewDiv);
this.createOverviewContent();
}
return true;
} else {
if (workerScript.shouldLog("joinBladeburnerFaction")) {
workerScript.log("Failed to join Bladeburners Faction because " +
"you do not have the required " + RankNeededForFaction + " rank");
}
return false;
}
}
Bladeburner.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("Bladeburner", this);
}
Bladeburner.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(Bladeburner, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["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
*/
function initBladeburner() {
// Skills
Skills[SkillNames.BladesIntuition] = new Skill({
name:SkillNames.BladesIntuition,
desc:"Each level of this skill increases your success chance " +
"for all Contracts, Operations, and BlackOps by 3%",
baseCost: 3, costInc: 2.1,
successChanceAll:3
});
Skills[SkillNames.Cloak] = new Skill({
name:SkillNames.Cloak,
desc:"Each level of this skill increases your " +
"success chance in stealth-related Contracts, Operations, and BlackOps by 5.5%",
baseCost: 2, costInc: 1.1,
successChanceStealth:5.5
});
// TODO Marksman - If items are ever implemented
// TODO Weapon Proficiency - If items are ever implemented
Skills[SkillNames.ShortCircuit] = new Skill({
name:SkillNames.ShortCircuit,
desc:"Each level of this skill increases your success chance " +
"in Contracts, Operations, and BlackOps that involve retirement by 5.5%",
baseCost: 2, costInc: 2.1,
successChanceKill:5.5
});
Skills[SkillNames.DigitalObserver] = new Skill({
name:SkillNames.DigitalObserver,
desc:"Each level of this skill increases your success chance in " +
"all Operations and BlackOps by 4%",
baseCost: 2, costInc: 2.1,
successChanceOperation:4
});
Skills[SkillNames.Tracer] = new Skill({
name:SkillNames.Tracer,
desc:"Each level of this skill increases your success chance in " +
"all Contracts by 4%",
baseCost: 2, costInc: 2.1,
successChanceContract:4
});
Skills[SkillNames.Overclock] = new Skill({
name:SkillNames.Overclock,
desc:"Each level of this skill decreases the time it takes " +
"to attempt a Contract, Operation, and BlackOp by 1% (Max Level: 90)",
baseCost: 3, costInc: 1.4, maxLvl: 90,
actionTime:1
});
Skills[SkillNames.Reaper] = new Skill({
name: SkillNames.Reaper,
desc: "Each level of this skill increases your effective combat stats for Bladeburner actions by 2%",
baseCost: 2, costInc: 2.1,
effStr: 2, effDef: 2, effDex: 2, effAgi: 2
});
Skills[SkillNames.EvasiveSystem] = new Skill({
name:SkillNames.EvasiveSystem,
desc:"Each level of this skill increases your effective " +
"dexterity and agility for Bladeburner actions by 4%",
baseCost: 2, costInc: 2.1,
effDex: 4, effAgi: 4
});
Skills[SkillNames.Datamancer] = new Skill({
name:SkillNames.Datamancer,
desc:"Each level of this skill increases your effectiveness in " +
"synthoid population analysis and investigation by 5%. " +
"This affects all actions that can potentially increase " +
"the accuracy of your synthoid population/community estimates.",
baseCost:3, costInc:1,
successChanceEstimate:5
});
Skills[SkillNames.CybersEdge] = new Skill({
name:SkillNames.CybersEdge,
desc:"Each level of this skill increases your max stamina by 2%",
baseCost:1, costInc:3,
stamina:2
});
Skills[SkillNames.HandsOfMidas] = new Skill({
name: SkillNames.HandsOfMidas,
desc: "Each level of this skill increases the amount of money you receive from Contracts by 10%",
baseCost: 2, costInc: 2.5,
money: 10,
});
Skills[SkillNames.Hyperdrive] = new Skill({
name: SkillNames.Hyperdrive,
desc: "Each level of this skill increases the experience earned from Contracts, Operations, and BlackOps by 10%",
baseCost: 1, costInc: 2.5,
expGain: 10,
});
// General Actions
let actionName;
actionName = "Training";
GeneralActions[actionName] = new Action({
name:actionName,
desc:"Improve your abilities at the Bladeburner unit's specialized training " +
"center. Doing this gives experience for all combat stats and also " +
"increases your max stamina."
});
actionName = "Field Analysis";
GeneralActions[actionName] = new Action({
name:actionName,
desc:"Mine and analyze Synthoid-related data. This improve the " +
"Bladeburner's unit intelligence on Synthoid locations and " +
"activities. Completing this action will improve the accuracy " +
"of your Synthoid population estimated in the current city.
" +
"Does NOT require stamina."
});
actionName = "Recruitment";
GeneralActions[actionName] = new Action({
name:actionName,
desc:"Attempt to recruit members for your Bladeburner team. These members " +
"can help you conduct operations.
" +
"Does NOT require stamina."
});
actionName = "Diplomacy";
GeneralActions[actionName] = new Action({
name: actionName,
desc: "Improve diplomatic relations with the Synthoid population. " +
"Completing this action will reduce the Chaos level in your current city.
" +
"Does NOT require stamina."
});
actionName = "Hyperbolic Regeneration Chamber";
GeneralActions[actionName] = new Action({
name: actionName,
desc: "Enter cryogenic stasis using the Bladeburner division's hi-tech Regeneration Chamber. " +
"This will slowly heal your wounds and slightly increase your stamina.
",
});
// Black Operations
BlackOperations["Operation Typhoon"] = new BlackOperation({
name:"Operation Typhoon",
desc:"Obadiah Zenyatta is the leader of a RedWater PMC. It has long " +
"been known among the intelligence community that Zenyatta, along " +
"with the rest of the PMC, is a Synthoid.
" +
"The goal of Operation Typhoon is to find and eliminate " +
"Zenyatta and RedWater by any means necessary. After the task " +
"is completed, the actions must be covered up from the general public.",
baseDifficulty:2000, reqdRank:2.5e3,
rankGain:50, rankLoss:10, hpLoss:100,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Zero"] = new BlackOperation({
name:"Operation Zero",
desc:"AeroCorp is one of the world's largest defense contractors. " +
"It's leader, Steve Watataki, is thought to be a supporter of " +
"Synthoid rights. He must be removed.
" +
"The goal of Operation Zero is to covertly infiltrate AeroCorp and " +
"uncover any incriminating evidence or " +
"information against Watataki that will cause him to be removed " +
"from his position at AeroCorp. Incriminating evidence can be " +
"fabricated as a last resort. Be warned that AeroCorp has some of " +
"the most advanced security measures in the world.",
baseDifficulty:2500, reqdRank:5e3,
rankGain:60, rankLoss:15, hpLoss:50,
weights:{hack:0.2,str:0.15,def:0.15,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isStealth:true
});
BlackOperations["Operation X"] = new BlackOperation({
name:"Operation X",
desc:"We have recently discovered an underground publication " +
"group called Samizdat. Even though most of their publications " +
"are nonsensical conspiracy theories, the average human is " +
"gullible enough to believe them. Many of their works discuss " +
"Synthoids and pose a threat to society. The publications are spreading " +
"rapidly in China and other Eastern countries.
" +
"Samizdat has done a good job of keeping hidden and anonymous. " +
"However, we've just received intelligence that their base of " +
"operations is in Ishima's underground sewer systems. Your task is to " +
"investigate the sewer systems, and eliminate Samizdat. They must " +
"never publish anything again.",
baseDifficulty:3000, reqdRank:7.5e3,
rankGain:75, rankLoss:15, hpLoss:100,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Titan"] = new BlackOperation({
name:"Operation Titan",
desc:"Several months ago Titan Laboratories' Bioengineering department " +
"was infiltrated by Synthoids. As far as we know, Titan Laboratories' " +
"management has no knowledge about this. We don't know what the " +
"Synthoids are up to, but the research that they could " +
"be conducting using Titan Laboraties' vast resources is potentially " +
"very dangerous.
" +
"Your goal is to enter and destroy the Bioengineering department's " +
"facility in Aevum. The task is not just to retire the Synthoids there, but " +
"also to destroy any information or research at the facility that " +
"is relevant to the Synthoids and their goals.",
baseDifficulty:4000, reqdRank:10e3,
rankGain:100, rankLoss:20, hpLoss:100,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Ares"] = new BlackOperation({
name:"Operation Ares",
desc:"One of our undercover agents, Agent Carter, has informed us of a " +
"massive weapons deal going down in Dubai between rogue Russian " +
"militants and a radical Synthoid community. These weapons are next-gen " +
"plasma and energy weapons. It is critical for the safety of humanity " +
"that this deal does not happen.
" +
"Your task is to intercept the deal. Leave no survivors.",
baseDifficulty:5000, reqdRank:12.5e3,
rankGain:125, rankLoss:20, hpLoss:200,
weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0},
decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Archangel"] = new BlackOperation({
name:"Operation Archangel",
desc:"Our analysts have discovered that the popular Red Rabbit brothel in " +
"Amsterdam is run and 'staffed' by MK-VI Synthoids. Intelligence " +
"suggests that the profit from this brothel is used to fund a large " +
"black market arms trafficking operation.
" +
"The goal of this operation is to take out the leaders that are running " +
"the Red Rabbit brothel. Try to limit the number of other casualties, " +
"but do what you must to complete the mission.",
baseDifficulty:7500, reqdRank:15e3,
rankGain:200, rankLoss:20, hpLoss:25,
weights:{hack:0,str:0.2,def:0.2,dex:0.3,agi:0.3,cha:0, int:0},
decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true,
});
BlackOperations["Operation Juggernaut"] = new BlackOperation({
name:"Operation Juggernaut",
desc:"The CIA has just encountered a new security threat. A new " +
"criminal group, lead by a shadowy operative who calls himself " +
"Juggernaut, has been smuggling drugs and weapons (including " +
"suspected bioweapons) into Sector-12. We also have reason " +
"to believe the tried to break into one of Universal Energy's " +
"facilities in order to cause a city-wide blackout. The CIA " +
"suspects that Juggernaut is a heavily-augmented Synthoid, and " +
"have thus enlisted our help.
" +
"Your mission is to eradicate Juggernaut and his followers.",
baseDifficulty:10e3, reqdRank:20e3,
rankGain:300, rankLoss:40, hpLoss:300,
weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0},
decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true,
});
BlackOperations["Operation Red Dragon"] = new BlackOperation({
name:"Operation Red Dragon",
desc:"The Tetrads criminal organization is suspected of " +
"reverse-engineering the MK-VI Synthoid design. We believe " +
"they altered and possibly improved the design and began " +
"manufacturing their own Synthoid models in order to bolster " +
"their criminal activities.
" +
"Your task is to infiltrate and destroy the Tetrads' base of operations " +
"in Los Angeles. Intelligence tells us that their base houses " +
"one of their Synthoid manufacturing units.",
baseDifficulty:12.5e3, reqdRank:25e3,
rankGain:500, rankLoss:50, hpLoss:500,
weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true,
});
BlackOperations["Operation K"] = new BlackOperation({
name:"Operation K",
desc:"CODE RED SITUATION. Our intelligence tells us that VitaLife " +
"has discovered a new android cloning technology. This technology " +
"is supposedly capable of cloning Synthoid, not only physically " +
"but also their advanced AI modules. We do not believe that " +
"VitaLife is trying to use this technology illegally or " +
"maliciously, but if any Synthoids were able to infiltrate the " +
"corporation and take advantage of this technology then the " +
"results would be catastrophic.
" +
"We do not have the power or jurisdiction to shutdown this down " +
"through legal or political means, so we must resort to a covert " +
"operation. Your goal is to destroy this technology and eliminate" +
"anyone who was involved in its creation.",
baseDifficulty:15e3, reqdRank:30e3,
rankGain:750, rankLoss:60, hpLoss:1000,
weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Deckard"] = new BlackOperation({
name:"Operation Deckard",
desc:"Despite your success in eliminating VitaLife's new android-replicating " +
"technology in Operation K, we've discovered that a small group of " +
"MK-VI Synthoids were able to make off with the schematics and design " +
"of the technology before the Operation. It is almost a certainty that " +
"these Synthoids are some of the rogue MK-VI ones from the Synthoid Uprising." +
"The goal of Operation Deckard is to hunt down these Synthoids and retire " +
"them. I don't need to tell you how critical this mission is.",
baseDifficulty:20e3, reqdRank:40e3,
rankGain:1e3, rankLoss:75, hpLoss:200,
weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04},
decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true,
});
BlackOperations["Operation Tyrell"] = new BlackOperation({
name:"Operation Tyrell",
desc:"A week ago Blade Industries reported a small break-in at one " +
"of their Aevum Augmentation storage facitilities. We figured out " +
"that The Dark Army was behind the heist, and didn't think any more " +
"of it. However, we've just discovered that several known MK-VI Synthoids " +
"were part of that break-in group.
" +
"We cannot have Synthoids upgrading their already-enhanced abilities " +
"with Augmentations. Your task is to hunt down the associated Dark Army " +
"members and eliminate them.",
baseDifficulty:25e3, reqdRank:50e3,
rankGain:1.5e3, rankLoss:100, hpLoss:500,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true,
});
BlackOperations["Operation Wallace"] = new BlackOperation({
name:"Operation Wallace",
desc:"Based on information gathered from Operation Tyrell, we've discovered " +
"that The Dark Army was well aware that there were Synthoids amongst " +
"their ranks. Even worse, we believe that The Dark Army is working " +
"together with other criminal organizations such as The Syndicate and " +
"that they are planning some sort of large-scale takeover of multiple major " +
"cities, most notably Aevum. We suspect that Synthoids have infiltrated " +
"the ranks of these criminal factions and are trying to stage another " +
"Synthoid uprising.
" +
"The best way to deal with this is to prevent it before it even happens. " +
"The goal of Operation Wallace is to destroy the Dark Army and " +
"Syndicate factions in Aevum immediately. Leave no survivors.",
baseDifficulty:30e3, reqdRank:75e3,
rankGain:2e3, rankLoss:150, hpLoss:1500,
weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Shoulder of Orion"] = new BlackOperation({
name:"Operation Shoulder of Orion",
desc:"China's Solaris Space Systems is secretly launching the first " +
"manned spacecraft in over a decade using Synthoids. We believe " +
"China is trying to establish the first off-world colonies.
" +
"The mission is to prevent this launch without instigating an " +
"international conflict. When you accept this mission you will be " +
"officially disavowed by the NSA and the national government until after you " +
"successfully return. In the event of failure, all of the operation's " +
"team members must not let themselves be captured alive.",
baseDifficulty:35e3, reqdRank:100e3,
rankGain:2.5e3, rankLoss:500, hpLoss:1500,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isStealth:true
});
BlackOperations["Operation Hyron"] = new BlackOperation({
name:"Operation Hyron",
desc:"Our intelligence tells us that Fulcrum Technologies is developing " +
"a quantum supercomputer using human brains as core " +
"processors. This supercomputer " +
"is rumored to be able to store vast amounts of data and " +
"perform computations unmatched by any other supercomputer on the " +
"planet. But more importantly, the use of organic human brains " +
"means that the supercomputer may be able to reason abstractly " +
"and become self-aware.
" +
"I do not need to remind you why sentient-level AIs pose a serious " +
"thread to all of mankind.
" +
"The research for this project is being conducted at one of Fulcrum " +
"Technologies secret facilities in Aevum, codenamed 'Alpha Ranch'. " +
"Infiltrate the compound, delete and destroy the work, and then find and kill the " +
"project lead.",
baseDifficulty:40e3, reqdRank:125e3,
rankGain:3e3, rankLoss:1e3, hpLoss:500,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Morpheus"] = new BlackOperation({
name:"Operation Morpheus",
desc:"DreamSense Technologies is an advertising company that uses " +
"special technology to transmit their ads into the peoples " +
"dreams and subconcious. They do this using broadcast transmitter " +
"towers. Based on information from our agents and informants in " +
"Chonqging, we have reason to believe that one of the broadcast " +
"towers there has been compromised by Synthoids and is being used " +
"to spread pro-Synthoid propaganda.
" +
"The mission is to destroy this broadcast tower. Speed and " +
"stealth are of the upmost important for this.",
baseDifficulty:45e3, reqdRank:150e3,
rankGain:4e3, rankLoss:1e3, hpLoss:100,
weights:{hack:0.05,str:0.15,def:0.15,dex:0.3,agi:0.3,cha:0, int:0.05},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isStealth:true
});
BlackOperations["Operation Ion Storm"] = new BlackOperation({
name:"Operation Ion Storm",
desc:"Our analysts have uncovered a gathering of MK-VI Synthoids " +
"that have taken up residence in the Sector-12 Slums. We " +
"don't know if they are rogue Synthoids from the Uprising, " +
"but we do know that they have been stockpiling " +
"weapons, money, and other resources. This makes them dangerous.
" +
"This is a full-scale assault operation to find and retire all of these " +
"Synthoids in the Sector-12 Slums.",
baseDifficulty:50e3, reqdRank:175e3,
rankGain:5e3, rankLoss:1e3, hpLoss:5000,
weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Annihilus"] = new BlackOperation({
name:"Operation Annihilus",
desc:"Our superiors have ordered us to eradicate everything and everyone " +
"in an underground facility located in Aevum. They tell us " +
"that the facility houses many dangerous Synthoids and " +
"belongs to a terrorist organization called " +
"'The Covenant'. We have no prior intelligence about this " +
"organization, so you are going in blind.",
baseDifficulty:55e3, reqdRank:200e3,
rankGain:7.5e3, rankLoss:1e3, hpLoss:10e3,
weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Ultron"] = new BlackOperation({
name:"Operation Ultron",
desc:"OmniTek Incorporated, the original designer and manufacturer of Synthoids, " +
"has notified us of a malfunction in their AI design. This malfunction, " +
"when triggered, causes MK-VI Synthoids to become radicalized and seek out " +
"the destruction of humanity. They say that this bug affects all MK-VI Synthoids, " +
"not just the rogue ones from the Uprising.
" +
"OmniTek has also told us they they believe someone has triggered this " +
"malfunction in a large group of MK-VI Synthoids, and that these newly-radicalized Synthoids " +
"are now amassing in Volhaven to form a terrorist group called Ultron.
" +
"Intelligence suggests Ultron is heavily armed and that their members are " +
"augmented. We believe Ultron is making moves to take control of " +
"and weaponize DeltaOne's Tactical High-Energy Satellite Laser Array (THESLA).
" +
"Your task is to find and destroy Ultron.",
baseDifficulty:60e3, reqdRank:250e3,
rankGain:10e3, rankLoss:2e3, hpLoss:10e3,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
isKill:true
});
BlackOperations["Operation Centurion"] = new BlackOperation({
name:"Operation Centurion",
desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)
" +
"Throughout all of humanity's history, we have relied on " +
"technology to survive, conquer, and progress. Its advancement became our primary goal. " +
"And at the peak of human civilization technology turned into " +
"power. Global, absolute power.
" +
"It seems that the universe is not without a sense of irony.
" +
"The bits are all around us. The daemons that hold the Node " +
"together can manifest themselves in many different ways.
" +
"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)",
baseDifficulty:75e3, reqdRank:350e3,
rankGain:20e3, rankLoss:20e3, hpLoss:20e3,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
});
BlackOperations["Operation Daedalus"] = new BlackOperation({
name:"Operation Daedalus",
desc:"Yesterday we obeyed kings and bent our neck to emperors. " +
"Today we kneel only to truth.",
baseDifficulty:80e3, reqdRank:400e3,
rankGain:40e3, rankLoss:10e3, hpLoss:100e3,
weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1},
decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75},
});
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 40 */
/*!************************************!*\
!*** ./src/InteractiveTutorial.js ***!
\************************************/
/*! exports provided: iTutorialSteps, iTutorialEnd, iTutorialStart, iTutorialNextStep, ITutorial */
/*! exports used: ITutorial, iTutorialNextStep, iTutorialStart, iTutorialSteps */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iTutorialSteps; });
/* unused harmony export iTutorialEnd */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return iTutorialStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iTutorialNextStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ITutorial; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ui/MainMenu/Links */ 33);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 49);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 27);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 29);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_8__);
// 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
"TerminalGoToActiveScriptsPage",
"ActiveScriptsPage",
"ActiveScriptsToTerminal",
"TerminalTailScript",
"GoToHacknetNodesPage",
"HacknetNodesIntroduction",
"HacknetNodesGoToWorldPage",
"WorldDescription",
"TutorialPageInfo",
"End"
]
// 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
isRunning: false,
// Keeps track of whether each step has been done
stepIsDone: {},
}
function iTutorialStart() {
// 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;
}
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
// Don't autosave during this interactive tutorial
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity;
console.log("Interactive Tutorial started");
ITutorial.currStep = 0;
ITutorial.isRunning = true;
document.getElementById("interactive-tutorial-container").style.display = "block";
// Exit tutorial button
var exitButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("interactive-tutorial-exit");
exitButton.addEventListener("click", function() {
iTutorialEnd();
return false;
});
// Back button
var backButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("interactive-tutorial-back");
backButton.addEventListener("click", function() {
iTutorialPrevStep();
return false;
});
// Next button
var nextButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("interactive-tutorial-next");
nextButton.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
iTutorialEvaluateStep();
}
function iTutorialEvaluateStep() {
if (!ITutorial.isRunning) {console.log("Interactive Tutorial not running"); return;}
// Disable and clear main menu
var terminalMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("terminal-menu-link");
var statsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("stats-menu-link");
var activeScriptsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("active-scripts-menu-link");
var hacknetMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hacknet-nodes-menu-link");
var cityMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("city-menu-link");
var tutorialMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("tutorial-menu-link");
terminalMainMenu.removeAttribute("class");
statsMainMenu.removeAttribute("class");
activeScriptsMainMenu.removeAttribute("class");
hacknetMainMenu.removeAttribute("class");
cityMainMenu.removeAttribute("class");
tutorialMainMenu.removeAttribute("class");
// Interactive Tutorial Next button
var nextBtn = document.getElementById("interactive-tutorial-next");
switch(ITutorial.currStep) {
case iTutorialSteps.Start:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " +
"The game takes place in a dark, dystopian future...The year is 2077...
" +
"This tutorial will show you the basics of the game. " +
"You may skip the tutorial at any time.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.GoToCharacterPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " +
"the main navigation menu (left-hand side of the screen)");
nextBtn.style.display = "none";
// Flash 'Stats' menu and set its tutorial click handler
statsMainMenu.setAttribute("class", "flashing-button");
statsMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialNextStep(); //Opening the character page will go to the next step
return false;
});
break;
case iTutorialSteps.CharacterPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialSetText("The Stats page shows a lot of important information about your progress, " +
"such as your skills, money, and bonuses/multipliers. ")
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.CharacterGoToTerminalPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " +
"main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Terminal' menu and set its tutorial click handler
terminalMainMenu.setAttribute("class", "flashing-button");
terminalMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TerminalIntro:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The Terminal is used to interface with your home computer as well as " +
"all of the other machines around the world.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.TerminalHelp:
_engine__WEBPACK_IMPORTED_MODULE_0__["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
break;
case iTutorialSteps.TerminalLs:
_engine__WEBPACK_IMPORTED_MODULE_0__["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
break;
case iTutorialSteps.TerminalScan:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " +
"on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " +
"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
break;
case iTutorialSteps.TerminalScanAnalyze1:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The 'scan' command shows all available network connections. In other words, " +
"it displays a list of all servers that can be connected to from your " +
"current machine. A server is identified by either its IP or its hostname.
" +
"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
break;
case iTutorialSteps.TerminalScanAnalyze2:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " +
"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
break;
case iTutorialSteps.TerminalConnect:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " +
"as figure out how to navigate to those servers through the network. You can only connect to " +
"a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " +
"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
break;
case iTutorialSteps.TerminalAnalyze:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!
In the year 2077, currency has " +
"become digital and decentralized. People and corporations store their money " +
"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
break;
case iTutorialSteps.TerminalNuke:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("When the 'analyze' command finishes running it will show useful information " +
"about hacking the server.
For this server, the required hacking skill is only 1, " +
"which means you can hack it right now. However, in order to hack a server " +
"you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " +
"home computer is a virus that will grant you root access to a machine if there are enough " +
"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
break;
case iTutorialSteps.TerminalManualHack:
_engine__WEBPACK_IMPORTED_MODULE_0__["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
break;
case iTutorialSteps.TerminalHackingMechanics:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " +
"only has a certain percentage chance " +
"of success. This time and success chance is determined by a variety of factors, including " +
"your hacking skill and the server's security level.
" +
"If your attempt to hack the server is successful, you will steal a certain percentage " +
"of the server's total money. This percentage is affected by your hacking skill and " +
"the server's security level.
The amount of money on a server is not limitless. So, if " +
"you constantly hack a server and deplete its money, then you will encounter " +
"diminishing returns in your hacking.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.TerminalCreateScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " +
"you don't want to be hacking manually the entire time. You can automate your hacking " +
"by writing scripts!
To create a new script or edit an existing one, you can use the 'nano' " +
"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
break;
case iTutorialSteps.TerminalTypeScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadScriptEditorContent("foodnstuff.script", "");
iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " +
"written in the Netscript language, a programming language created for " +
"this game. There are details about the Netscript language in the documentation, which " +
"can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " +
"it out after this tutorial. For now, just copy " +
"and paste the following code into the script editor:
" +
"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)
break;
case iTutorialSteps.TerminalFree:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " +
"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
break;
case iTutorialSteps.TerminalRunScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["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
break;
case iTutorialSteps.TerminalGoToActiveScriptsPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " +
"Your scripts will continuously run in the background and will automatically stop if " +
"the code ever completes (the 'foodnstuff.script' will never complete because it " +
"runs an infinite loop).
These scripts can passively earn you income and hacking experience. " +
"Your scripts will also earn money and experience while you are offline, although at a " +
"much slower rate.
" +
"Let's check out some statistics for our running scripts by clicking the " +
"'Active Scripts' link in the main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Active Scripts' menu and set its tutorial click handler
activeScriptsMainMenu.setAttribute("class", "flashing-button");
activeScriptsMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.ActiveScriptsPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
iTutorialSetText("This page displays stats/information about all of your scripts that are " +
"running across every existing server. You can use this to gauge how well " +
"your scripts are doing. Let's go back to the Terminal now using the 'Terminal' " +
"link.");
nextBtn.style.display = "none";
// Flash 'Terminal' button and set its tutorial click handler
terminalMainMenu.setAttribute("class", "flashing-button");
terminalMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.ActiveScriptsToTerminal:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
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
break;
case iTutorialSteps.TerminalTailScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " +
"just started running...but check back again in a few minutes!
" +
"This pretty much covers the basics of hacking. To learn more about writing " +
"scripts using the Netscript language, select the 'Tutorial' link in the " +
"main navigation menu to look at the documentation. " +
"If you are an experienced JavaScript " +
"developer, I would highly suggest you check out the section on " +
"NetscriptJS/Netscript 2.0.
For now, let's move on to something else!");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.GoToHacknetNodesPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " +
"earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " +
"the 'Hacknet Nodes' page through the main navigation menu now.");
nextBtn.style.display = "none";
// Flash 'Hacknet' menu and set its tutorial click handler
hacknetMainMenu.setAttribute("class", "flashing-button");
hacknetMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.HacknetNodesIntroduction:
_engine__WEBPACK_IMPORTED_MODULE_0__["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)
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent();
iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " +
"earn you money over time, both online and offline. When you get enough " +
" money, you can upgrade " +
"your newly-purchased Hacknet Node below.
" +
"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
cityMainMenu.setAttribute("class", "flashing-button");
cityMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadLocationContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.WorldDescription:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadLocationContent();
iTutorialSetText("This page lists all of the different locations you can currently " +
"travel to. Each location has something that you can do. " +
"There's a lot of content out in the world, make sure " +
"you explore and discover!
" +
"Lastly, click on the 'Tutorial' link in the main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Tutorial' menu and set its tutorial click handler
tutorialMainMenu.setAttribute("class", "flashing-button");
tutorialMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TutorialPageInfo:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
iTutorialSetText("This page contains a lot of different documentation about the game's " +
"content and mechanics. I know it's a lot, but I highly suggest you read " +
"(or at least skim) through this before you start playing. That's the end of the tutorial. " +
"Hope you enjoy the game!");
nextBtn.style.display = "inline-block";
nextBtn.innerHTML = "Finish Tutorial";
break;
case iTutorialSteps.End:
iTutorialEnd();
break;
default:
throw new Error("Invalid tutorial step");
}
if (ITutorial.stepIsDone[ITutorial.currStep] === true) {
nextBtn.style.display = "inline-block";
}
}
// Go to the next step and evaluate it
function iTutorialNextStep() {
// Special behavior for certain steps
if (ITutorial.currStep === iTutorialSteps.GoToCharacterPage) {
document.getElementById("stats-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.CharacterGoToTerminalPage) {
document.getElementById("terminal-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.TerminalGoToActiveScriptsPage) {
document.getElementById("active-scripts-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.ActiveScriptsPage) {
document.getElementById("terminal-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.GoToHacknetNodesPage) {
document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.HacknetNodesGoToWorldPage) {
document.getElementById("city-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.WorldDescription) {
document.getElementById("tutorial-menu-link").removeAttribute("class");
}
ITutorial.stepIsDone[ITutorial.currStep] = true;
if (ITutorial.currStep < iTutorialSteps.End) {
ITutorial.currStep += 1;
}
iTutorialEvaluateStep();
}
// Go to previous step and evaluate
function iTutorialPrevStep() {
if (ITutorial.currStep > iTutorialSteps.Start) {
ITutorial.currStep -= 1;
}
iTutorialEvaluateStep();
}
function iTutorialEnd() {
// Re-enable auto save
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval === 0) {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity;
} else {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = _Settings_Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval * 5;
}
console.log("Ending interactive tutorial");
// Initialize references to main menu links
// We have to call initializeMainMenuLinks() again because the Interactive Tutorial
// re-creates Main menu links with clearEventListeners()
if (!Object(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__["initializeMainMenuLinks"])()) {
const errorMsg = "Failed to initialize Main Menu Links. Please try refreshing the page. " +
"If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].init();
ITutorial.currStep = iTutorialSteps.End;
ITutorial.isRunning = false;
document.getElementById("interactive-tutorial-container").style.display = "none";
// Create a popup with final introductory stuff
var popupId = "interactive-tutorial-ending-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {
innerHTML:
"If you are new to the game, the following links may be useful for you!
" +
"The Beginner's Guide to Hacking was added to your home computer! It contains some tips/pointers for starting out with the game. " +
"To read it, go to Terminal and enter
cat hackers-starting-handbook.lit"
});
var gotitBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", {
class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId);
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_7__["createPopup"])(popupId, [txt, gotitBtn]);
_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().messages.push("hackers-starting-handbook.lit");
}
function iTutorialSetText(txt) {
var textBox = document.getElementById("interactive-tutorial-text");
if (textBox == null) {throw new Error("Could not find text box"); return;}
textBox.innerHTML = txt;
textBox.parentElement.scrollTop = 0; // this resets scroll position
}
/***/ }),
/* 41 */
/*!******************************************************!*\
!*** ./utils/uiHelpers/removeChildrenFromElement.ts ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __webpack_require__(/*! ../helpers/isString */ 51);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 91);
/**
* Clears out all children from the provided element.
* If a string is passed in, it will treat it as an ID and search for the element to delete all children from.
* @param el The element or ID of an element to remove all children from.
*/
function removeChildrenFromElement(el) {
if (el === null) {
return;
}
try {
const elem = (isString_1.isString(el) ? getElementById_1.getElementById(el) : el);
if (elem instanceof Element) {
while (elem.firstChild !== null) {
elem.removeChild(elem.firstChild);
}
}
}
catch (e) {
// tslint:disable-next-line:no-console
console.debug(e);
return;
}
}
exports.removeChildrenFromElement = removeChildrenFromElement;
/***/ }),
/* 42 */
/*!********************************!*\
!*** ./src/NetscriptWorker.js ***!
\********************************/
/*! exports provided: workerScripts, NetscriptPorts, prestigeWorkerScripts, runScriptsLoop, killWorkerScript, addWorkerScript, updateOnlineScriptTimes, loadAllRunningScripts, runScriptFromScript */
/*! exports used: NetscriptPorts, addWorkerScript, killWorkerScript, loadAllRunningScripts, prestigeWorkerScripts, runScriptFromScript, runScriptsLoop, updateOnlineScriptTimes, workerScripts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return workerScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeWorkerScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return runScriptsLoop; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return killWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return addWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return updateOnlineScriptTimes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadAllRunningScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptFromScript; });
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Netscript/WorkerScript */ 102);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ActiveScriptsUI */ 92);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _JSInterpreter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./JSInterpreter */ 259);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptFunctions */ 126);
/* harmony import */ var _NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./NetscriptJSEvaluator */ 258);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./NetscriptPort */ 110);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Script/RunningScript */ 137);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Script/RunningScriptHelpers */ 168);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 67);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Server/AllServers */ 21);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 68);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! escodegen */ 175);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(escodegen__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/acorn */ 79);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 150);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 77);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 141);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_22__);
/**
* Functions for handling WorkerScripts, which are the underlying mechanism
* that allows for scripts to run
*/
const walk = __webpack_require__(/*! acorn/dist/walk */ 369);
//Array containing all scripts that are running across all servers, to easily run them all
const workerScripts = [];
const NetscriptPorts = [];
for (var i = 0; i < _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].NumNetscriptPorts; ++i) {
NetscriptPorts.push(new _NetscriptPort__WEBPACK_IMPORTED_MODULE_8__[/* NetscriptPort */ "a"]());
}
function prestigeWorkerScripts() {
for (var i = 0; i < workerScripts.length; ++i) {
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]);
workerScripts[i].env.stopFlag = true;
}
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__[/* updateActiveScriptsItems */ "c"])(5000); //Force UI to update
workerScripts.length = 0;
}
// JS script promises need a little massaging to have the same guarantees as netscript
// promises. This does said massaging and kicks the script off. It returns a promise
// that resolves or rejects when the corresponding worker script is done.
function startNetscript2Script(workerScript) {
workerScript.running = true;
// The name of the currently running netscript function, to prevent concurrent
// calls to hack, grow, etc.
let runningFn = null;
// We need to go through the environment and wrap each function in such a way that it
// can be called at most once at a time. This will prevent situations where multiple
// hack promises are outstanding, for example.
function wrap(propName, f) {
// This function unfortunately cannot be an async function, because we don't
// know if the original one was, and there's no way to tell.
return function (...args) {
// Wrap every netscript function with a check for the stop flag.
// This prevents cases where we never stop because we are only calling
// netscript functions that don't check this.
// This is not a problem for legacy Netscript because it also checks the
// stop flag in the evaluator.
if (workerScript.env.stopFlag) {throw workerScript;}
if (propName === "sleep") return f(...args); // OK for multiple simultaneous calls to sleep.
const msg = "Concurrent calls to Netscript functions not allowed! " +
"Did you forget to await hack(), grow(), or some other " +
"promise-returning function? (Currently running: %s tried to run: %s)"
if (runningFn) {
workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "c"])(workerScript, sprintf(msg, runningFn, propName), null)
throw workerScript;
}
runningFn = propName;
// If the function throws an error, clear the runningFn flag first, and then re-throw it
// This allows people to properly catch errors thrown by NS functions without getting
// the concurrent call error above
let result;
try {
result = f(...args);
} catch(e) {
runningFn = null;
throw(e);
}
if (result && result.finally !== undefined) {
return result.finally(function () {
runningFn = null;
});
} else {
runningFn = null;
return result;
}
}
};
for (let prop in workerScript.env.vars) {
if (typeof workerScript.env.vars[prop] !== "function") continue;
workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]);
}
// Note: the environment that we pass to the JS script only needs to contain the functions visible
// to that script, which env.vars does at this point.
return Object(_NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_7__[/* executeJSScript */ "a"])(workerScript.getServer().scripts,
workerScript).then(function (mainReturnValue) {
if (mainReturnValue === undefined) return workerScript;
return [mainReturnValue, workerScript];
}).catch(e => {
if (e instanceof Error) {
workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "c"])(
workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || ""));
throw workerScript;
} else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "a"])(e)) {
workerScript.errorMessage = e;
throw workerScript;
}
throw e; // Don't know what to do with it, let's rethrow.
});
}
function startNetscript1Script(workerScript) {
var code = workerScript.code;
workerScript.running = true;
//Process imports
var codeWithImports, codeLineOffset;
try {
let importProcessingRes = processNetscript1Imports(code, workerScript);
codeWithImports = importProcessingRes.code;
codeLineOffset = importProcessingRes.lineOffset;
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Error processing Imports in " + workerScript.name + ": " + e);
workerScript.env.stopFlag = true;
workerScript.running = false;
return;
}
var interpreterInitialization = function(int, scope) {
//Add the Netscript environment
var ns = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__[/* NetscriptFunctions */ "a"])(workerScript);
for (let name in ns) {
let entry = ns[name];
if (typeof entry === "function") {
//Async functions need to be wrapped. See JS-Interpreter documentation
if (name === "hack" || name === "grow" || name === "weaken" || name === "sleep" ||
name === "prompt" || name === "run" || name === "exec") {
let tempWrapper = function() {
let fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns
for (let i = 0; i < arguments.length-1; ++i) {
if (typeof arguments[i] === 'object' || arguments[i].constructor === Array) {
fnArgs.push(int.pseudoToNative(arguments[i]));
} else {
fnArgs.push(arguments[i]);
}
}
console.log(fnArgs);
let cb = arguments[arguments.length-1];
let fnPromise = entry.apply(null, fnArgs);
fnPromise.then(function(res) {
cb(res);
}).catch(function(e) {
// Do nothing?
});
}
int.setProperty(scope, name, int.createAsyncFunction(tempWrapper));
} else if (name === "sprintf" || name === "vsprintf" || name === "scp" ||
name == "write" || name === "read" || name === "tryWrite") {
let tempWrapper = function() {
let fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns
for (let i = 0; i < arguments.length; ++i) {
if (typeof arguments[i] === 'object' || arguments[i].constructor === Array) {
fnArgs.push(int.pseudoToNative(arguments[i]));
} else {
fnArgs.push(arguments[i]);
}
}
return entry.apply(null, fnArgs);
}
int.setProperty(scope, name, int.createNativeFunction(tempWrapper));
} else {
let tempWrapper = function() {
let res = entry.apply(null, arguments);
if (res == null) {
return res;
} else if (res.constructor === Array || (res === Object(res))) {
//Objects and Arrays must be converted to the interpreter's format
return int.nativeToPseudo(res);
} else {
return res;
}
}
int.setProperty(scope, name, int.createNativeFunction(tempWrapper));
}
} else {
//bladeburner, or anything else
int.setProperty(scope, name, int.nativeToPseudo(entry));
}
}
//Add the arguments
int.setProperty(scope, "args", int.nativeToPseudo(workerScript.args));
}
var interpreter;
try {
interpreter = new _JSInterpreter__WEBPACK_IMPORTED_MODULE_4__[/* Interpreter */ "a"](codeWithImports, interpreterInitialization, codeLineOffset);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Syntax ERROR in " + workerScript.name + ": " + e);
workerScript.env.stopFlag = true;
workerScript.running = false;
return;
}
return new Promise(function(resolve, reject) {
function runInterpreter() {
try {
if (workerScript.env.stopFlag) { return reject(workerScript); }
if (interpreter.step()) {
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_15__["setTimeoutRef"])(runInterpreter, _Settings_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].CodeInstructionRunTime);
} else {
resolve(workerScript);
}
} catch(e) {
e = e.toString();
if (!Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "a"])(e)) {
e = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "c"])(workerScript, e);
}
workerScript.errorMessage = e;
return reject(workerScript);
}
}
try {
runInterpreter();
} catch(e) {
if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_22__["isString"])(e)) {
workerScript.errorMessage = e;
return reject(workerScript);
} else if (e instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__["WorkerScript"]) {
return reject(e);
} else {
return reject(workerScript);
}
}
});
}
/* Since the JS Interpreter used for Netscript 1.0 only supports ES5, the keyword
'import' throws an error. However, since we want to support import funtionality
we'll implement it ourselves by parsing the Nodes in the AST out.
@param code - The script's code
@returns {Object} {
code: Newly-generated code with imported functions
lineOffset: Net number of lines of code added/removed due to imported functions
Should typically be positive
}
*/
function processNetscript1Imports(code, workerScript) {
//allowReserved prevents 'import' from throwing error in ES5
var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_17__["parse"])(code, {ecmaVersion:6, allowReserved:true, sourceType:"module"});
var server = workerScript.getServer();
if (server == null) {
throw new Error("Failed to find underlying Server object for script");
}
function getScript(scriptName) {
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === scriptName) {
return server.scripts[i];
}
}
return null;
}
var generatedCode = ""; //Generated Javascript Code
var hasImports = false;
//Walk over the tree and process ImportDeclaration nodes
walk.simple(ast, {
ImportDeclaration: (node) => {
hasImports = true;
let scriptName = node.source.value;
if (scriptName.startsWith("./")) {
scriptName = scriptName.slice(2);
}
let script = getScript(scriptName);
if (script == null) {
throw new Error("'Import' failed due to invalid script: " + scriptName);
}
let scriptAst = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_17__["parse"])(script.code, {ecmaVersion:5, allowReserved:true, sourceType:"module"});
if (node.specifiers.length === 1 && node.specifiers[0].type === "ImportNamespaceSpecifier") {
//import * as namespace from script
let namespace = node.specifiers[0].local.name;
let fnNames = []; //Names only
let fnDeclarations = []; //FunctionDeclaration Node objects
walk.simple(scriptAst, {
FunctionDeclaration: (node) => {
fnNames.push(node.id.name);
fnDeclarations.push(node);
}
});
//Now we have to generate the code that would create the namespace
generatedCode =
"var " + namespace + ";\n" +
"(function (namespace) {\n";
//Add the function declarations
fnDeclarations.forEach((fn) => {
generatedCode += Object(escodegen__WEBPACK_IMPORTED_MODULE_16__["generate"])(fn);
generatedCode += "\n";
});
//Add functions to namespace
fnNames.forEach((fnName) => {
generatedCode += ("namespace." + fnName + " = " + fnName);
generatedCode += "\n";
});
//Finish
generatedCode += (
"})(" + namespace + " || " + "(" + namespace + " = {}));\n"
)
} else {
//import {...} from script
//Get array of all fns to import
let fnsToImport = [];
node.specifiers.forEach((e) => {
fnsToImport.push(e.local.name);
});
//Walk through script and get FunctionDeclaration code for all specified fns
let fnDeclarations = [];
walk.simple(scriptAst, {
FunctionDeclaration: (node) => {
if (fnsToImport.includes(node.id.name)) {
fnDeclarations.push(node);
}
}
});
//Convert FunctionDeclarations into code
fnDeclarations.forEach((fn) => {
generatedCode += Object(escodegen__WEBPACK_IMPORTED_MODULE_16__["generate"])(fn);
generatedCode += "\n";
});
}
}
});
//If there are no imports, just return the original code
if (!hasImports) {return {code:code, lineOffset:0};}
//Remove ImportDeclarations from AST. These ImportDeclarations must be in top-level
var linesRemoved = 0;
if (ast.type !== "Program" || ast.body == null) {
throw new Error("Code could not be properly parsed");
}
for (let i = ast.body.length-1; i >= 0; --i) {
if (ast.body[i].type === "ImportDeclaration") {
ast.body.splice(i, 1);
++linesRemoved;
}
}
//Calculated line offset
var lineOffset = (generatedCode.match(/\n/g) || []).length - linesRemoved;
//Convert the AST back into code
code = Object(escodegen__WEBPACK_IMPORTED_MODULE_16__["generate"])(ast);
//Add the imported code and re-generate in ES5 (JS Interpreter for NS1 only supports ES5);
code = generatedCode + code;
var res = {
code: code,
lineOffset: lineOffset
}
return res;
}
//Loop through workerScripts and run every script that is not currently running
function runScriptsLoop() {
var scriptDeleted = false;
//Delete any scripts that finished or have been killed. Loop backwards bc removing items screws up indexing
for (var i = workerScripts.length - 1; i >= 0; i--) {
if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) {
scriptDeleted = true;
//Delete script from the runningScripts array on its host serverIp
var ip = workerScripts[i].serverIp;
var name = workerScripts[i].name;
//recalculate ram used
_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].ramUsed = 0;
for(let j = 0; j < workerScripts.length; j++) {
if(workerScripts[j].serverIp !== ip) {
continue
}
if(j === i) { // not this one
continue
}
_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].ramUsed += workerScripts[j].ramUsage;
}
//Delete script from Active Scripts
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]);
for (var j = 0; j < _Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].runningScripts.length; j++) {
if (_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].runningScripts[j].filename == name &&
Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__["compareArrays"])(_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].runningScripts[j].args, workerScripts[i].args)) {
_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][ip].runningScripts.splice(j, 1);
break;
}
}
//Delete script from workerScripts
workerScripts.splice(i, 1);
}
}
if (scriptDeleted) {Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__[/* updateActiveScriptsItems */ "c"])();} //Force Update
//Run any scripts that haven't been started
for (var i = 0; i < workerScripts.length; i++) {
//If it isn't running, start the script
if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) {
let p = null; // p is the script's result promise.
if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) {
p = startNetscript2Script(workerScripts[i]);
} else {
p = startNetscript1Script(workerScripts[i]);
if (!(p instanceof Promise)) { continue; }
}
//Once the code finishes (either resolved or rejected, doesnt matter), set its
//running status to false
p.then(function(w) {
console.log("Stopping script " + w.name + " because it finished running naturally");
w.running = false;
w.env.stopFlag = true;
w.scriptRef.log("Script finished running");
}).catch(function(w) {
if (w instanceof Error) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
console.error("Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString());
return;
} else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") {
//Script ends with a return statement
console.log("Script returning with value: " + w[1]);
//TODO maybe do something with this in the future
return;
} else if (w instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__["WorkerScript"]) {
if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "a"])(w.errorMessage)) {
var errorTextArray = w.errorMessage.split("|");
if (errorTextArray.length != 4) {
console.log("ERROR: Something wrong with Error text in evaluator...");
console.log("Error text: " + errorText);
return;
}
var serverIp = errorTextArray[1];
var scriptName = errorTextArray[2];
var errorMsg = errorTextArray[3];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Script runtime error: Server Ip: " + serverIp +
" Script name: " + scriptName +
" Args:" + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20__["arrayToString"])(w.args) + " " + errorMsg);
w.scriptRef.log("Script crashed with runtime error");
} else {
w.scriptRef.log("Script killed");
}
w.running = false;
w.env.stopFlag = true;
} else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "a"])(w)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString());
return;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev");
console.log(w);
}
});
}
}
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_15__["setTimeoutRef"])(runScriptsLoop, 6000);
}
/**
* Queues a script to be killed by setting its stop flag to true. This
* kills and timed/blocking Netscript functions (like hack(), sleep(), etc.) and
* prevents any further execution of Netscript functions.
* The runScriptsLoop() handles the actual deletion of the WorkerScript
*/
function killWorkerScript(runningScriptObj, serverIp) {
for (var i = 0; i < workerScripts.length; i++) {
if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp &&
Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) {
workerScripts[i].env.stopFlag = true;
Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* killNetscriptDelay */ "b"])(workerScripts[i]);
return true;
}
}
return false;
}
/**
* Given a RunningScript object, queues that script to be run
*/
function addWorkerScript(runningScriptObj, server) {
var filename = runningScriptObj.filename;
//Update server's ram usage
var threads = 1;
if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) {
threads = runningScriptObj.threads;
} else {
runningScriptObj.threads = 1;
}
var ramUsage = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_21__["roundToTwo"])(Object(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_11__["getRamUsageFromRunningScript"])(runningScriptObj) * threads);
var ramAvailable = server.maxRam - server.ramUsed;
if (ramUsage > ramAvailable) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " +
Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20__["arrayToString"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " +
"the game and the script's RAM usage increased (either because of an update to the game or " +
"your changes to the script.)");
return;
}
server.ramUsed = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_21__["roundToTwo"])(server.ramUsed + ramUsage);
//Create the WorkerScript
var s = new _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_0__["WorkerScript"](runningScriptObj, _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__[/* NetscriptFunctions */ "a"]);
s.ramUsage = ramUsage;
//Add the WorkerScript to the Active Scripts list
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_1__[/* addActiveScriptsItem */ "a"])(s);
//Add the WorkerScript
workerScripts.push(s);
return;
}
/**
* Updates the online running time stat of all running scripts
*/
function updateOnlineScriptTimes(numCycles = 1) {
var time = (numCycles * _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"]._idleSpeed) / 1000; //seconds
for (var i = 0; i < workerScripts.length; ++i) {
workerScripts[i].scriptRef.onlineRunningTime += time;
}
}
/**
* Called when the game is loaded. Loads all running scripts (from all servers)
* into worker scripts so that they will start running
*/
function loadAllRunningScripts() {
var total = 0;
let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1);
if (skipScriptLoad) { console.info("Skipping the load of any scripts during startup"); }
for (const property in _Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"]) {
if (_Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"].hasOwnProperty(property)) {
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_13__["AllServers"][property];
// Reset each server's RAM usage to 0
server.ramUsed = 0;
// Reset modules on all scripts
for (let i = 0; i < server.scripts.length; ++i) {
server.scripts[i].module = "";
}
if (skipScriptLoad) {
// Start game with no scripts
server.runningScripts.length = 0;
} else {
for (let j = 0; j < server.runningScripts.length; ++j) {
addWorkerScript(server.runningScripts[j], server);
// Offline production
total += Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_12__[/* scriptCalculateOfflineProduction */ "c"])(server.runningScripts[j]);
}
}
}
}
return total;
}
/**
* Run a script from inside another script (run(), exec(), spawn(), etc.)
*/
function runScriptFromScript(server, scriptname, args, workerScript, threads=1) {
//Check if the script is already running
let runningScriptObj = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_12__[/* findRunningScript */ "a"])(scriptname, args, server);
if (runningScriptObj != null) {
workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname);
return Promise.resolve(false);
}
//'null/undefined' arguments are not allowed
for (let i = 0; i < args.length; ++i) {
if (args[i] == null) {
workerScript.scriptRef.log("ERROR: Cannot execute a script with null/undefined as an argument");
return Promise.resolve(false);
}
}
//Check if the script exists and if it does run it
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) {
//Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage;
threads = Math.round(Number(threads)); //Convert to number and round
if (threads === 0) { return Promise.resolve(false); }
ramUsage = ramUsage * threads;
var ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!");
return Promise.resolve(false);
} else if (ramUsage > ramAvailable){
workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!");
return Promise.resolve(false);
} else {
//Able to run script
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.exec == null && workerScript.disableLogs.run == null && workerScript.disableLogs.spawn == null) {
workerScript.scriptRef.log(`Running script: ${scriptname} on ${server.hostname} with ${threads} threads and args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_20__["arrayToString"])(args)}. May take a few seconds to start up...`);
}
let runningScriptObj = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_10__["RunningScript"](script, args);
runningScriptObj.threads = threads;
addWorkerScript(runningScriptObj, server);
// Push onto runningScripts.
// This has to come after addWorkerScript() because that fn updates RAM usage
server.runScript(runningScriptObj, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
return Promise.resolve(true);
}
}
}
workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname);
return Promise.resolve(false);
}
/***/ }),
/* 43 */,
/* 44 */,
/* 45 */
/*!*****************************************!*\
!*** ./src/StockMarket/StockMarket.jsx ***!
\*****************************************/
/*! exports provided: StockMarket, SymbolToStockMap, placeOrder, cancelOrder, loadStockMarket, deleteStockMarket, initStockMarket, initSymbolToStockMap, stockMarketCycle, processStockPrices, displayStockMarketContent */
/*! exports used: StockMarket, SymbolToStockMap, cancelOrder, deleteStockMarket, displayStockMarketContent, initStockMarket, initSymbolToStockMap, loadStockMarket, placeOrder, processStockPrices, stockMarketCycle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return placeOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return cancelOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return loadStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return deleteStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return initStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initSymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return stockMarketCycle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return processStockPrices; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return displayStockMarketContent; });
/* harmony import */ var _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BuyingAndSelling */ 97);
/* harmony import */ var _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Order__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Order */ 179);
/* harmony import */ var _Order__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Order__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _OrderProcessing__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OrderProcessing */ 104);
/* harmony import */ var _OrderProcessing__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Stock */ 82);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _StockMarketHelpers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./StockMarketHelpers */ 135);
/* harmony import */ var _StockMarketHelpers__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _StockMarketCosts__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./StockMarketCosts */ 127);
/* harmony import */ var _StockMarketCosts__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_StockMarketCosts__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _data_InitStockMetadata__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./data/InitStockMetadata */ 271);
/* harmony import */ var _data_InitStockMetadata__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_data_InitStockMetadata__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./data/OrderTypes */ 66);
/* harmony import */ var _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./data/PositionTypes */ 57);
/* harmony import */ var _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _data_StockSymbols__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./data/StockSymbols */ 115);
/* harmony import */ var _data_StockSymbols__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_data_StockSymbols__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/Root */ 270);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_ui_Root__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Netscript/WorkerScript */ 102);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! .././ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! .././ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! react-dom */ 64);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_19__);
let StockMarket = {}; // Maps full stock name -> Stock object
let SymbolToStockMap = {}; // Maps symbol -> Stock object
function placeOrder(stock, shares, price, type, position, workerScript = null) {
const tixApi = workerScript instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_12__["WorkerScript"];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"])) {
if (tixApi) {
workerScript.log(`ERROR: Invalid stock passed to placeOrder() function`);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(`ERROR: Invalid stock passed to placeOrder() function`);
}
return false;
}
if (typeof shares !== "number" || typeof price !== "number") {
if (tixApi) {
workerScript.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
}
return false;
}
const order = new _Order__WEBPACK_IMPORTED_MODULE_1__["Order"](stock.symbol, shares, price, type, position);
if (StockMarket["Orders"] == null) {
const orders = {};
for (const name in StockMarket) {
const stk = StockMarket[name];
if (!(stk instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"])) {
continue;
}
orders[stk.symbol] = [];
}
StockMarket["Orders"] = orders;
}
StockMarket["Orders"][stock.symbol].push(order); // Process to see if it should be executed immediately
const processOrderRefs = {
rerenderFn: displayStockMarketContent,
stockMarket: StockMarket,
symbolToStockMap: SymbolToStockMap
};
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, order.type, order.pos, processOrderRefs);
displayStockMarketContent();
return true;
} // Returns true if successfully cancels an order, false otherwise
function cancelOrder(params, workerScript = null) {
var tixApi = workerScript instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_12__["WorkerScript"];
if (StockMarket["Orders"] == null) {
return false;
}
if (params.order && params.order instanceof _Order__WEBPACK_IMPORTED_MODULE_1__["Order"]) {
const order = params.order; // An 'Order' object is passed in
var stockOrders = StockMarket["Orders"][order.stockSymbol];
for (var i = 0; i < stockOrders.length; ++i) {
if (order == stockOrders[i]) {
stockOrders.splice(i, 1);
displayStockMarketContent();
return true;
}
}
return false;
} else if (params.stock && params.shares && params.price && params.type && params.pos && params.stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"]) {
// Order properties are passed in. Need to look for the order
var stockOrders = StockMarket["Orders"][params.stock.symbol];
var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_15__["numeralWrapper"].formatMoney(params.price);
for (var i = 0; i < stockOrders.length; ++i) {
var order = stockOrders[i];
if (params.shares === order.shares && params.price === order.price && params.type === order.type && params.pos === order.pos) {
stockOrders.splice(i, 1);
displayStockMarketContent();
if (tixApi) {
workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt);
}
return true;
}
}
if (tixApi) {
workerScript.scriptRef.log("Failed to cancel order: " + orderTxt);
}
return false;
}
return false;
}
function loadStockMarket(saveString) {
if (saveString === "") {
StockMarket = {};
} else {
StockMarket = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_17__["Reviver"]); // Backwards compatibility for v0.47.0
const orderBook = StockMarket["Orders"];
if (orderBook != null) {
// For each order, set its 'stockSymbol' property equal to the
// symbol of its 'stock' property
for (const stockSymbol in orderBook) {
const ordersForStock = orderBook[stockSymbol];
if (Array.isArray(ordersForStock)) {
for (const order of ordersForStock) {
if (order instanceof _Order__WEBPACK_IMPORTED_MODULE_1__["Order"] && order.stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"]) {
order.stockSymbol = order.stock.symbol;
}
}
}
}
console.log(`Converted Stock Market order book to v0.47.0 format`);
}
}
}
function deleteStockMarket() {
StockMarket = {};
}
function initStockMarket() {
for (const stk in StockMarket) {
if (StockMarket.hasOwnProperty(stk)) {
delete StockMarket[stk];
}
}
for (const metadata of _data_InitStockMetadata__WEBPACK_IMPORTED_MODULE_6__["InitStockMetadata"]) {
const name = metadata.name;
StockMarket[name] = new _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"](metadata);
}
const orders = {};
for (const name in StockMarket) {
const stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"])) {
continue;
}
orders[stock.symbol] = [];
}
StockMarket["Orders"] = orders;
StockMarket.storedCycles = 0;
StockMarket.lastUpdate = 0;
}
function initSymbolToStockMap() {
for (const name in _data_StockSymbols__WEBPACK_IMPORTED_MODULE_9__["StockSymbols"]) {
if (_data_StockSymbols__WEBPACK_IMPORTED_MODULE_9__["StockSymbols"].hasOwnProperty(name)) {
const stock = StockMarket[name];
if (stock == null) {
console.error(`Could not find Stock for ${name}`);
continue;
}
const symbol = _data_StockSymbols__WEBPACK_IMPORTED_MODULE_9__["StockSymbols"][name];
SymbolToStockMap[symbol] = stock;
}
}
}
function stockMarketCycle() {
for (const name in StockMarket) {
const stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"])) {
continue;
}
let thresh = 0.6;
if (stock.b) {
thresh = 0.4;
}
if (Math.random() < thresh) {
stock.b = !stock.b;
if (stock.otlkMag < 10) {
stock.otlkMag += 0.2;
}
}
}
} // Stock prices updated every 6 seconds
const msPerStockUpdate = 6e3;
const cyclesPerStockUpdate = msPerStockUpdate / _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].MilliPerCycle;
function processStockPrices(numCycles = 1) {
if (StockMarket.storedCycles == null || isNaN(StockMarket.storedCycles)) {
StockMarket.storedCycles = 0;
}
StockMarket.storedCycles += numCycles;
if (StockMarket.storedCycles < cyclesPerStockUpdate) {
return;
} // We can process the update every 4 seconds as long as there are enough
// stored cycles. This lets us account for offline time
const timeNow = new Date().getTime();
if (timeNow - StockMarket.lastUpdate < 4e3) {
return;
}
StockMarket.lastUpdate = timeNow;
StockMarket.storedCycles -= cyclesPerStockUpdate;
var v = Math.random();
for (const name in StockMarket) {
const stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_3__["Stock"])) {
continue;
}
let av = v * stock.mv / 100;
if (isNaN(av)) {
av = .02;
}
let chc = 50;
if (stock.b) {
chc = (chc + stock.otlkMag) / 100;
} else {
chc = (chc - stock.otlkMag) / 100;
}
if (stock.price >= stock.cap) {
chc = 0.1; // "Soft Limit" on stock price. It could still go up but its unlikely
stock.b = false;
}
if (isNaN(chc)) {
chc = 0.5;
}
const c = Math.random();
const processOrderRefs = {
rerenderFn: displayStockMarketContent,
stockMarket: StockMarket,
symbolToStockMap: SymbolToStockMap
};
if (c < chc) {
stock.changePrice(stock.price * (1 + av));
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].LimitBuy, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Short, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].LimitSell, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Long, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].StopBuy, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Long, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].StopSell, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Short, processOrderRefs);
} else {
stock.changePrice(stock.price / (1 + av));
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].LimitBuy, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Long, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].LimitSell, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Short, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].StopBuy, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Short, processOrderRefs);
Object(_OrderProcessing__WEBPACK_IMPORTED_MODULE_2__["processOrders"])(stock, _data_OrderTypes__WEBPACK_IMPORTED_MODULE_7__["OrderTypes"].StopSell, _data_PositionTypes__WEBPACK_IMPORTED_MODULE_8__["PositionTypes"].Long, processOrderRefs);
}
let otlkMagChange = stock.otlkMag * av;
if (stock.otlkMag <= 0.1) {
otlkMagChange = 1;
}
if (c < 0.5) {
stock.otlkMag += otlkMagChange;
} else {
stock.otlkMag -= otlkMagChange;
}
if (stock.otlkMag > 50) {
stock.otlkMag = 50;
} // Cap so the "forecast" is between 0 and 100
if (stock.otlkMag < 0) {
stock.otlkMag *= -1;
stock.b = !stock.b;
} // Shares required for price movement gradually approaches max over time
stock.shareTxUntilMovement = Math.min(stock.shareTxUntilMovement + 5, stock.shareTxForMovement);
}
displayStockMarketContent();
}
let stockMarketContainer = null;
function setStockMarketContainer() {
stockMarketContainer = document.getElementById("stock-market-container");
document.removeEventListener("DOMContentLoaded", setStockMarketContainer);
}
document.addEventListener("DOMContentLoaded", setStockMarketContainer);
function initStockMarketFnForReact() {
initStockMarket();
initSymbolToStockMap();
}
function displayStockMarketContent() {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__["Page"].StockMarket)) {
return;
}
if (stockMarketContainer instanceof HTMLElement) {
react_dom__WEBPACK_IMPORTED_MODULE_19___default.a.render(react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_10__["StockMarketRoot"], {
buyStockLong: _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__["buyStock"],
buyStockShort: _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__["shortStock"],
cancelOrder: cancelOrder,
initStockMarket: initStockMarketFnForReact,
p: _Player__WEBPACK_IMPORTED_MODULE_13__["Player"],
placeOrder: placeOrder,
sellStockLong: _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__["sellStock"],
sellStockShort: _BuyingAndSelling__WEBPACK_IMPORTED_MODULE_0__["sellShort"],
stockMarket: StockMarket
}), stockMarketContainer);
}
}
/***/ }),
/* 46 */
/*!***************************!*\
!*** ./utils/YesNoBox.ts ***!
\***************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Generic Yes-No Pop-up box
* Used to create pop-up boxes that require a yes/no response from player
*
* There are two types of pop ups:
* 1. Just a Yes/No response from player
* 2. Popup also includes a text input field in addition to the Yes/No response
*/
const clearEventListeners_1 = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 27);
const keyCodes_1 = __webpack_require__(/*! ./helpers/keyCodes */ 32);
exports.yesNoBoxOpen = false;
const yesNoBoxContainer = document.getElementById("yes-no-box-container");
const yesNoBoxTextElement = document.getElementById("yes-no-box-text");
function yesNoBoxHotkeyHandler(e) {
if (e.keyCode === keyCodes_1.KEY.ESC) {
yesNoBoxClose();
}
else if (e.keyCode === keyCodes_1.KEY.ENTER) {
const yesBtn = document.getElementById("yes-no-box-yes");
if (yesBtn) {
yesBtn.click();
}
else {
console.error(`Could not find YesNoBox Yes button DOM element`);
}
}
}
exports.yesNoBoxHotkeyHandler = yesNoBoxHotkeyHandler;
function yesNoBoxClose() {
if (yesNoBoxContainer) {
yesNoBoxContainer.style.display = "none";
}
else {
console.error("Container not found for YesNoBox");
}
exports.yesNoBoxOpen = false;
// Remove hotkey handler
document.removeEventListener("keydown", yesNoBoxHotkeyHandler);
return false; //So that 'return yesNoBoxClose()' is return false in event listeners
}
exports.yesNoBoxClose = yesNoBoxClose;
function yesNoBoxGetYesButton() {
return clearEventListeners_1.clearEventListeners("yes-no-box-yes");
}
exports.yesNoBoxGetYesButton = yesNoBoxGetYesButton;
function yesNoBoxGetNoButton() {
return clearEventListeners_1.clearEventListeners("yes-no-box-no");
}
exports.yesNoBoxGetNoButton = yesNoBoxGetNoButton;
function yesNoBoxCreate(txt) {
if (exports.yesNoBoxOpen) {
return false;
} //Already open
exports.yesNoBoxOpen = true;
if (yesNoBoxTextElement) {
yesNoBoxTextElement.innerHTML = txt;
}
else {
console.error(`Text element not found for YesNoBox`);
}
if (yesNoBoxContainer) {
yesNoBoxContainer.style.display = "flex";
}
else {
console.error("Container not found for YesNoBox");
}
// Add event listener for Esc and Enter hotkeys
document.addEventListener("keydown", yesNoBoxHotkeyHandler);
return true;
}
exports.yesNoBoxCreate = yesNoBoxCreate;
/**
* Yes-No pop up box with text input field
*/
const yesNoTextInputBoxContainer = document.getElementById("yes-no-text-input-box-container");
const yesNoTextInputBoxInput = document.getElementById("yes-no-text-input-box-input");
const yesNoTextInputBoxTextElement = document.getElementById("yes-no-text-input-box-text");
function yesNoTxtInpBoxHotkeyHandler(e) {
if (e.keyCode === keyCodes_1.KEY.ESC) {
yesNoTxtInpBoxClose();
}
else if (e.keyCode === keyCodes_1.KEY.ENTER) {
const yesBtn = document.getElementById("yes-no-text-input-box-yes");
if (yesBtn) {
yesBtn.click();
}
else {
console.error(`Could not find YesNoTxtInputBox Yes button DOM element`);
}
}
}
exports.yesNoTxtInpBoxHotkeyHandler = yesNoTxtInpBoxHotkeyHandler;
function yesNoTxtInpBoxClose() {
if (yesNoTextInputBoxContainer != null) {
yesNoTextInputBoxContainer.style.display = "none";
}
else {
console.error("Container not found for YesNoTextInputBox");
return false;
}
exports.yesNoBoxOpen = false;
yesNoTextInputBoxInput.value = "";
// Remove hotkey handler
document.removeEventListener("keydown", yesNoTxtInpBoxHotkeyHandler);
return false;
}
exports.yesNoTxtInpBoxClose = yesNoTxtInpBoxClose;
function yesNoTxtInpBoxGetYesButton() {
return clearEventListeners_1.clearEventListeners("yes-no-text-input-box-yes");
}
exports.yesNoTxtInpBoxGetYesButton = yesNoTxtInpBoxGetYesButton;
function yesNoTxtInpBoxGetNoButton() {
return clearEventListeners_1.clearEventListeners("yes-no-text-input-box-no");
}
exports.yesNoTxtInpBoxGetNoButton = yesNoTxtInpBoxGetNoButton;
function yesNoTxtInpBoxGetInput() {
if (yesNoTextInputBoxInput == null) {
console.error("Could not find YesNoTextInputBox input element");
return "";
}
let val = yesNoTextInputBoxInput.value;
val = val.replace(/\s+/g, '');
return val;
}
exports.yesNoTxtInpBoxGetInput = yesNoTxtInpBoxGetInput;
function yesNoTxtInpBoxCreate(txt) {
exports.yesNoBoxOpen = true;
if (yesNoTextInputBoxTextElement) {
yesNoTextInputBoxTextElement.innerHTML = txt;
}
if (yesNoTextInputBoxContainer) {
yesNoTextInputBoxContainer.style.display = "flex";
}
else {
console.error("Container not found for YesNoTextInputBox");
}
// Add event listener for Esc and Enter hotkeys
document.addEventListener("keydown", yesNoTxtInpBoxHotkeyHandler);
yesNoTextInputBoxInput.focus();
}
exports.yesNoTxtInpBoxCreate = yesNoTxtInpBoxCreate;
/***/ }),
/* 47 */
/*!******************************!*\
!*** ./src/NetscriptGang.js ***!
\******************************/
/*! exports provided: unknownGangApiExceptionMessage, checkGangApiAccess */
/*! exports used: checkGangApiAccess, unknownGangApiExceptionMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return unknownGangApiExceptionMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkGangApiAccess; });
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Gang */ 69);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
function unknownGangApiExceptionMessage(functionName, err) {
return `gang.${functionName}() failed with exception: ` + err;
}
function checkGangApiAccess(workerScript, functionName) {
const accessDenied = `gang.${functionName}() failed because you do not currently have a Gang`;
const hasAccess = _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].gang instanceof _Gang__WEBPACK_IMPORTED_MODULE_1__[/* Gang */ "b"];
if (!hasAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__[/* makeRuntimeRejectMsg */ "c"])(workerScript, accessDenied);
}
}
/***/ }),
/* 48 */
/*!*****************************************!*\
!*** ./src/Company/CompanyPositions.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Constructs all CompanyPosition objects using the metadata in data/companypositions.ts
const CompanyPositionsMetadata_1 = __webpack_require__(/*! ./data/CompanyPositionsMetadata */ 630);
const CompanyPosition_1 = __webpack_require__(/*! ./CompanyPosition */ 134);
exports.CompanyPositions = {};
function addCompanyPosition(params) {
if (exports.CompanyPositions[params.name] != null) {
console.warn(`Duplicate Company Position being defined: ${params.name}`);
}
exports.CompanyPositions[params.name] = new CompanyPosition_1.CompanyPosition(params);
}
CompanyPositionsMetadata_1.companyPositionMetadata.forEach((e) => {
addCompanyPosition(e);
});
/***/ }),
/* 49 */
/*!*****************************************!*\
!*** ./utils/helpers/exceptionAlert.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DialogBox_1 = __webpack_require__(/*! ../DialogBox */ 9);
function exceptionAlert(e) {
console.error(e);
DialogBox_1.dialogBoxCreate("Caught an exception: " + e + "
" +
"This is a bug, please report to game developer with this " +
"message as well as details about how to reproduce the bug.
" +
"If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " +
"safe doesn't get corrupted", false);
}
exports.exceptionAlert = exceptionAlert;
/***/ }),
/* 50 */
/*!********************************!*\
!*** ./src/CodingContracts.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const codingcontracttypes_1 = __webpack_require__(/*! ./data/codingcontracttypes */ 672);
const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 17);
const keyCodes_1 = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
const createElement_1 = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3);
const createPopup_1 = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36);
const removeElementById_1 = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 29);
/* tslint:disable:no-magic-numbers completed-docs max-classes-per-file no-console */
/* Represents different types of problems that a Coding Contract can have */
class CodingContractType {
constructor(name, desc, gen, solver, diff, numTries) {
this.name = name;
this.desc = desc;
this.generate = gen;
this.solver = solver;
this.difficulty = diff;
this.numTries = numTries;
}
}
exports.CodingContractType = CodingContractType;
/* Contract Types */
// tslint:disable-next-line
exports.CodingContractTypes = {};
for (const md of codingcontracttypes_1.codingContractTypesMetadata) {
// tslint:disable-next-line
exports.CodingContractTypes[md.name] = new CodingContractType(md.name, md.desc, md.gen, md.solver, md.difficulty, md.numTries);
}
console.info(`${Object.keys(exports.CodingContractTypes).length} Coding Contract Types loaded`);
/**
* Enum representing the different types of rewards a Coding Contract can give
*/
var CodingContractRewardType;
(function (CodingContractRewardType) {
CodingContractRewardType[CodingContractRewardType["FactionReputation"] = 0] = "FactionReputation";
CodingContractRewardType[CodingContractRewardType["FactionReputationAll"] = 1] = "FactionReputationAll";
CodingContractRewardType[CodingContractRewardType["CompanyReputation"] = 2] = "CompanyReputation";
CodingContractRewardType[CodingContractRewardType["Money"] = 3] = "Money";
})(CodingContractRewardType = exports.CodingContractRewardType || (exports.CodingContractRewardType = {}));
/**
* Enum representing the result when trying to solve the Contract
*/
var CodingContractResult;
(function (CodingContractResult) {
CodingContractResult[CodingContractResult["Success"] = 0] = "Success";
CodingContractResult[CodingContractResult["Failure"] = 1] = "Failure";
CodingContractResult[CodingContractResult["Cancelled"] = 2] = "Cancelled";
})(CodingContractResult = exports.CodingContractResult || (exports.CodingContractResult = {}));
/**
* A Coding Contract is a file that poses a programming-related problem to the Player.
* The player receives a reward if the problem is solved correctly
*/
class CodingContract {
constructor(fn = "", type = "Find Largest Prime Factor", reward = null) {
/* Number of times the Contract has been attempted */
this.tries = 0;
this.fn = fn;
if (!this.fn.endsWith(".cct")) {
this.fn += ".cct";
}
// tslint:disable-next-line
if (exports.CodingContractTypes[type] == null) {
throw new Error(`Error: invalid contract type: ${type} please contact developer`);
}
this.type = type;
this.data = exports.CodingContractTypes[type].generate();
this.reward = reward;
}
/**
* Initiatizes a CodingContract from a JSON save state.
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(CodingContract, value.data);
}
getData() {
return this.data;
}
getDescription() {
return exports.CodingContractTypes[this.type].desc(this.data);
}
getDifficulty() {
return exports.CodingContractTypes[this.type].difficulty;
}
getMaxNumTries() {
return exports.CodingContractTypes[this.type].numTries;
}
getType() {
return exports.CodingContractTypes[this.type].name;
}
isSolution(solution) {
return exports.CodingContractTypes[this.type].solver(this.data, solution);
}
/**
* Creates a popup to prompt the player to solve the problem
*/
prompt() {
return __awaiter(this, void 0, void 0, function* () {
// tslint:disable-next-line
return new Promise((resolve, reject) => {
const contractType = exports.CodingContractTypes[this.type];
const popupId = `coding-contract-prompt-popup-${this.fn}`;
const txt = createElement_1.createElement("p", {
innerHTML: ["You are attempting to solve a Coding Contract. You have",
`${this.getMaxNumTries() - this.tries} tries remaining,`,
"after which the contract will self-destruct.
",
`${contractType.desc(this.data).replace(/\n/g, " ")}`].join(" "),
});
let answerInput;
let solveBtn;
let cancelBtn;
answerInput = createElement_1.createElement("input", {
onkeydown: (e) => {
if (e.keyCode === keyCodes_1.KEY.ENTER && answerInput.value !== "") {
e.preventDefault();
solveBtn.click();
}
else if (e.keyCode === keyCodes_1.KEY.ESC) {
e.preventDefault();
cancelBtn.click();
}
},
placeholder: "Enter Solution here",
width: "50%",
});
solveBtn = createElement_1.createElement("a", {
class: "a-link-button",
clickListener: () => {
const answer = answerInput.value;
if (this.isSolution(answer)) {
resolve(CodingContractResult.Success);
}
else {
resolve(CodingContractResult.Failure);
}
removeElementById_1.removeElementById(popupId);
},
innerText: "Solve",
});
cancelBtn = createElement_1.createElement("a", {
class: "a-link-button",
clickListener: () => {
resolve(CodingContractResult.Cancelled);
removeElementById_1.removeElementById(popupId);
},
innerText: "Cancel",
});
const lineBreak = createElement_1.createElement("br");
createPopup_1.createPopup(popupId, [txt, lineBreak, lineBreak, answerInput, solveBtn, cancelBtn]);
answerInput.focus();
});
});
}
/**
* Serialize the current file to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("CodingContract", this);
}
}
exports.CodingContract = CodingContract;
JSONReviver_1.Reviver.constructors.CodingContract = CodingContract;
/***/ }),
/* 51 */
/*!***********************************!*\
!*** ./utils/helpers/isString.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Checks whether the value passed in can be considered a string.
* @param value The value to check if it is a string.
*/
function isString(value) {
return (typeof value === "string" || value instanceof String);
}
exports.isString = isString;
/***/ }),
/* 52 */
/*!****************************************!*\
!*** ./src/Faction/FactionHelpers.jsx ***!
\****************************************/
/*! exports provided: inviteToFaction, joinFaction, startHackingMission, displayFactionContent, purchaseAugmentationBoxCreate, hasAugmentationPrereqs, purchaseAugmentation, getNextNeurofluxLevel, processPassiveFactionRepGain */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inviteToFaction", function() { return inviteToFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinFaction", function() { return joinFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startHackingMission", function() { return startHackingMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayFactionContent", function() { return displayFactionContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentationBoxCreate", function() { return purchaseAugmentationBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAugmentationPrereqs", function() { return hasAugmentationPrereqs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentation", function() { return purchaseAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextNeurofluxLevel", function() { return getNextNeurofluxLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processPassiveFactionRepGain", function() { return processPassiveFactionRepGain; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ 64);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ui/Root */ 282);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_ui_Root__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Augmentation/Augmentations */ 11);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Augmentation/PlayerOwnedAugmentation */ 125);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../engine */ 14);
/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Faction */ 71);
/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Faction__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Factions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Factions */ 13);
/* harmony import */ var _Factions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Factions__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Missions */ 74);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../utils/FactionInvitationBox */ 281);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../utils/YesNoBox */ 46);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__);
function inviteToFaction(faction) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].SuppressFactionInvites) {
faction.alreadyInvited = true;
_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].factionInvitations.push(faction.name);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_14__["Page"].Factions)) {
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadFactionsContent();
}
} else {
Object(_utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_16__[/* factionInvitationBoxCreate */ "a"])(faction);
}
}
function joinFaction(faction) {
faction.isMember = true;
_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].factions.push(faction.name);
const factionInfo = faction.getInfo(); //Determine what factions you are banned from now that you have joined this faction
for (const i in factionInfo.enemies) {
const enemy = factionInfo.enemies[i];
if (_Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"][enemy] instanceof _Faction__WEBPACK_IMPORTED_MODULE_9__["Faction"]) {
_Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"][enemy].isBanned = true;
}
}
}
function startHackingMission(faction) {
const mission = new _Missions__WEBPACK_IMPORTED_MODULE_11__[/* HackingMission */ "a"](faction.playerReputation, faction);
Object(_Missions__WEBPACK_IMPORTED_MODULE_11__[/* setInMission */ "d"])(true, mission); //Sets inMission flag to true
mission.init();
} //Displays the HTML content for a specific faction
function displayFactionContent(factionName, initiallyOnAugmentationsPage = false) {
const faction = _Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"][factionName];
if (faction == null) {
throw new Error(`Invalid factionName passed into displayFactionContent(): ${factionName}`);
}
if (!faction.isMember) {
throw new Error(`Not a member of this faction. Cannot display faction information`);
}
react_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_2__["FactionRoot"], {
engine: _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"],
initiallyOnAugmentationsPage: initiallyOnAugmentationsPage,
faction: faction,
p: _Player__WEBPACK_IMPORTED_MODULE_12__["Player"],
startHackingMissionFn: startHackingMission
}), _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].Display.factionContent);
}
function purchaseAugmentationBoxCreate(aug, fac) {
const factionInfo = fac.getInfo();
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__["yesNoBoxGetYesButton"])();
yesBtn.innerHTML = "Purchase";
yesBtn.addEventListener("click", function () {
purchaseAugmentation(aug, fac);
});
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__["yesNoBoxGetNoButton"])();
noBtn.innerHTML = "Cancel";
noBtn.addEventListener("click", function () {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__["yesNoBoxClose"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__["yesNoBoxCreate"])("
" + aug.name + "
" + aug.info + "
" + " Would you like to purchase the " + aug.name + " Augmentation for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_18__["formatNumber"])(aug.baseCost * factionInfo.augmentationPriceMult, 2) + "?");
} //Returns a boolean indicating whether the player has the prerequisites for the
//specified Augmentation
function hasAugmentationPrereqs(aug) {
let hasPrereqs = true;
if (aug.prereqs && aug.prereqs.length > 0) {
for (let i = 0; i < aug.prereqs.length; ++i) {
const prereqAug = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"][aug.prereqs[i]];
if (prereqAug == null) {
console.error(`Invalid prereq Augmentation ${aug.prereqs[i]}`);
continue;
}
if (prereqAug.owned === false) {
hasPrereqs = false; // Check if the aug is purchased
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations[j].name === prereqAug.name) {
hasPrereqs = true;
break;
}
}
}
}
}
return hasPrereqs;
}
function purchaseAugmentation(aug, fac, sing = false) {
const factionInfo = fac.getInfo();
var hasPrereqs = hasAugmentationPrereqs(aug);
if (!hasPrereqs) {
var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + "purchase this one.";
if (sing) {
return txt;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])(txt);
}
} else if (aug.baseCost !== 0 && _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].money.lt(aug.baseCost * factionInfo.augmentationPriceMult)) {
let txt = "You don't have enough money to purchase " + aug.name;
if (sing) {
return txt;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])(txt);
} else if (fac.playerReputation < aug.baseRepRequirement) {
let txt = "You don't have enough faction reputation to purchase " + aug.name;
if (sing) {
return txt;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])(txt);
} else if (aug.baseCost === 0 || _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].firstAugPurchased === false) {
_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].firstAugPurchased = true;
document.getElementById("augmentations-tab").style.display = "list-item";
document.getElementById("character-menu-header").click();
document.getElementById("character-menu-header").click();
}
var queuedAugmentation = new _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_4__["PlayerOwnedAugmentation"](aug.name);
if (aug.name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__["AugmentationNames"].NeuroFluxGovernor) {
queuedAugmentation.level = getNextNeurofluxLevel();
}
_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations.push(queuedAugmentation);
_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].loseMoney(aug.baseCost * factionInfo.augmentationPriceMult); // If you just purchased Neuroflux Governor, recalculate the cost
if (aug.name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__["AugmentationNames"].NeuroFluxGovernor) {
var nextLevel = getNextNeurofluxLevel();
--nextLevel;
var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
aug.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__["BitNodeMultipliers"].AugmentationRepCost;
aug.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__["BitNodeMultipliers"].AugmentationMoneyCost;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations.length - 1; ++i) {
aug.baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].MultipleAugMultiplier;
}
}
for (var name in _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"]) {
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"].hasOwnProperty(name)) {
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"][name].baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].MultipleAugMultiplier;
}
}
if (sing) {
return "You purchased " + aug.name;
} else {
if (!_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].SuppressBuyAugmentationConfirmation) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("You purchased " + aug.name + ". It's enhancements will not take " + "effect until they are installed. To install your augmentations, go to the " + "'Augmentations' tab on the left-hand navigation menu. Purchasing additional " + "augmentations will now be more expensive.");
}
} // Force a rerender of the Augmentations page
displayFactionContent(fac.name, true);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Hmm, something went wrong when trying to purchase an Augmentation. " + "Please report this to the game developer with an explanation of how to " + "reproduce this.");
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_19__["yesNoBoxClose"])();
}
function getNextNeurofluxLevel() {
// Get current Neuroflux level based on Player's augmentations
let currLevel = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].augmentations[i].name === _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__["AugmentationNames"].NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].augmentations[i].level;
}
} // Account for purchased but uninstalled Augmentations
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__["Player"].queuedAugmentations[i].name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_5__["AugmentationNames"].NeuroFluxGovernor) {
++currLevel;
}
}
return currLevel + 1;
}
function processPassiveFactionRepGain(numCycles) {
var numTimesGain = numCycles / 600 * _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].faction_rep_mult;
for (var name in _Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"]) {
if (_Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"].hasOwnProperty(name)) {
var faction = _Factions__WEBPACK_IMPORTED_MODULE_10__["Factions"][name]; //TODO Get hard value of 1 rep per "rep gain cycle"" for now..
//maybe later make this based on
//a player's 'status' like how powerful they are and how much money they have
if (faction.isMember) {
faction.playerReputation += numTimesGain * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__["BitNodeMultipliers"].FactionPassiveRepGain;
}
}
}
}
/***/ }),
/* 53 */
/*!**************************************!*\
!*** ./src/Settings/SettingEnums.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Enums that defined allowed values for setting configuration
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Allowed values for 'Keybinding/Keymap' setting in Ace editor
*/
var AceKeybindingSetting;
(function (AceKeybindingSetting) {
AceKeybindingSetting["Ace"] = "ace";
AceKeybindingSetting["Emacs"] = "emacs";
AceKeybindingSetting["Vim"] = "vim";
})(AceKeybindingSetting = exports.AceKeybindingSetting || (exports.AceKeybindingSetting = {}));
/**
* Allowed values for 'Keybinding/Keymap' setting in Code Mirror editor
*/
var CodeMirrorKeybindingSetting;
(function (CodeMirrorKeybindingSetting) {
CodeMirrorKeybindingSetting["Default"] = "default";
CodeMirrorKeybindingSetting["Emacs"] = "emacs";
CodeMirrorKeybindingSetting["Sublime"] = "sublime";
CodeMirrorKeybindingSetting["Vim"] = "vim";
})(CodeMirrorKeybindingSetting = exports.CodeMirrorKeybindingSetting || (exports.CodeMirrorKeybindingSetting = {}));
/**
* Allowed values for 'Theme' setting in Code Mirror editor
*/
var CodeMirrorThemeSetting;
(function (CodeMirrorThemeSetting) {
CodeMirrorThemeSetting["Monokai"] = "monokai";
CodeMirrorThemeSetting["Day_3024"] = "3024-day";
CodeMirrorThemeSetting["Night_3024"] = "3024-night";
CodeMirrorThemeSetting["abcdef"] = "abcdef";
CodeMirrorThemeSetting["Ambiance_mobile"] = "ambiance-mobile";
CodeMirrorThemeSetting["Ambiance"] = "ambiance";
CodeMirrorThemeSetting["Base16_dark"] = "base16-dark";
CodeMirrorThemeSetting["Base16_light"] = "base16-light";
CodeMirrorThemeSetting["Bespin"] = "bespin";
CodeMirrorThemeSetting["Blackboard"] = "blackboard";
CodeMirrorThemeSetting["Cobalt"] = "cobalt";
CodeMirrorThemeSetting["Colorforth"] = "colorforth";
CodeMirrorThemeSetting["Darcula"] = "darcula";
CodeMirrorThemeSetting["Dracula"] = "dracula";
CodeMirrorThemeSetting["Duotone_dark"] = "duotone-dark";
CodeMirrorThemeSetting["Duotone_light"] = "duotone-light";
CodeMirrorThemeSetting["Eclipse"] = "eclipse";
CodeMirrorThemeSetting["Elegant"] = "elegant";
CodeMirrorThemeSetting["Erlang_dark"] = "erlang-dark";
CodeMirrorThemeSetting["Gruvbox_dark"] = "gruvbox-dark";
CodeMirrorThemeSetting["Hopscotch"] = "hopscotch";
CodeMirrorThemeSetting["Icecoder"] = "icecoder";
CodeMirrorThemeSetting["Idea"] = "idea";
CodeMirrorThemeSetting["Isotope"] = "isotope";
CodeMirrorThemeSetting["Lesser_dark"] = "lesser-dark";
CodeMirrorThemeSetting["Liquibyte"] = "liquibyte";
CodeMirrorThemeSetting["Lucario"] = "lucario";
CodeMirrorThemeSetting["Material"] = "material";
CodeMirrorThemeSetting["Mbo"] = "mbo";
CodeMirrorThemeSetting["Mdn_like"] = "mdn-like";
CodeMirrorThemeSetting["Midnight"] = "midnight";
CodeMirrorThemeSetting["Neat"] = "neat";
CodeMirrorThemeSetting["Neo"] = "neo";
CodeMirrorThemeSetting["Night"] = "night";
CodeMirrorThemeSetting["Oceanic_next"] = "oceanic-next";
CodeMirrorThemeSetting["Panda_syntax"] = "panda-syntax";
CodeMirrorThemeSetting["Paraiso_dark"] = "paraiso-dark";
CodeMirrorThemeSetting["Paraiso_light"] = "paraiso-light";
CodeMirrorThemeSetting["Pastel_on_dark"] = "pastel-on-dark";
CodeMirrorThemeSetting["Railscasts"] = "railscasts";
CodeMirrorThemeSetting["Rubyblue"] = "rubyblue";
CodeMirrorThemeSetting["Seti"] = "seti";
CodeMirrorThemeSetting["Shadowfox"] = "shadowfox";
CodeMirrorThemeSetting["Solarized"] = "solarized";
CodeMirrorThemeSetting["ssms"] = "ssms";
CodeMirrorThemeSetting["The_matrix"] = "the-matrix";
CodeMirrorThemeSetting["Tomorrow_night_bright"] = "tomorrow-night-bright";
CodeMirrorThemeSetting["Tomorrow_night_eighties"] = "tomorrow-night-eighties";
CodeMirrorThemeSetting["Ttcn"] = "ttcn";
CodeMirrorThemeSetting["Twilight"] = "twilight";
CodeMirrorThemeSetting["Vibrant_ink"] = "vibrant-ink";
CodeMirrorThemeSetting["xq_dark"] = "xq-dark";
CodeMirrorThemeSetting["xq_light"] = "xq-light";
CodeMirrorThemeSetting["Yeti"] = "yeti";
CodeMirrorThemeSetting["Zenburn"] = "zenburn";
})(CodeMirrorThemeSetting = exports.CodeMirrorThemeSetting || (exports.CodeMirrorThemeSetting = {}));
/**
* Allowed values for the "Editor" setting
*/
var EditorSetting;
(function (EditorSetting) {
EditorSetting["Ace"] = "Ace";
EditorSetting["CodeMirror"] = "CodeMirror";
})(EditorSetting = exports.EditorSetting || (exports.EditorSetting = {}));
/**
* Allowed values for the 'OwnedAugmentationsOrder' setting
*/
var PurchaseAugmentationsOrderSetting;
(function (PurchaseAugmentationsOrderSetting) {
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Cost"] = 0] = "Cost";
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Default"] = 1] = "Default";
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Reputation"] = 2] = "Reputation";
})(PurchaseAugmentationsOrderSetting = exports.PurchaseAugmentationsOrderSetting || (exports.PurchaseAugmentationsOrderSetting = {}));
/**
* Allowed values for the 'OwnedAugmentationsOrder' setting
*/
var OwnedAugmentationsOrderSetting;
(function (OwnedAugmentationsOrderSetting) {
OwnedAugmentationsOrderSetting[OwnedAugmentationsOrderSetting["Alphabetically"] = 0] = "Alphabetically";
OwnedAugmentationsOrderSetting[OwnedAugmentationsOrderSetting["AcquirementTime"] = 1] = "AcquirementTime";
})(OwnedAugmentationsOrderSetting = exports.OwnedAugmentationsOrderSetting || (exports.OwnedAugmentationsOrderSetting = {}));
/***/ }),
/* 54 */
/*!************************************!*\
!*** ./src/Hacknet/HacknetNode.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: BaseCostForHacknetNode, HacknetNode, HacknetNodeMaxCores, HacknetNodeMaxLevel, HacknetNodeMaxRam, HacknetNodePurchaseNextMult */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 9);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
// Constants for Hacknet Node production
exports.HacknetNodeMoneyGainPerLevel = 1.6; // Base production per level
// Constants for Hacknet Node purchase/upgrade costs
exports.BaseCostForHacknetNode = 1000;
exports.BaseCostFor1GBOfRamHacknetNode = 30e3;
exports.BaseCostForHacknetNodeCore = 500e3;
exports.HacknetNodePurchaseNextMult = 1.85; // Multiplier when purchasing an additional hacknet node
exports.HacknetNodeUpgradeLevelMult = 1.04; // Multiplier for cost when upgrading level
exports.HacknetNodeUpgradeRamMult = 1.28; // Multiplier for cost when upgrading RAM
exports.HacknetNodeUpgradeCoreMult = 1.48; // Multiplier for cost when buying another core
// Constants for max upgrade levels for Hacknet Nodes
exports.HacknetNodeMaxLevel = 200;
exports.HacknetNodeMaxRam = 64;
exports.HacknetNodeMaxCores = 16;
class HacknetNode {
constructor(name = "", prodMult = 1) {
// Node's number of cores
this.cores = 1;
// Node's Level
this.level = 1;
// Node's production per second
this.moneyGainRatePerSecond = 0;
// How long this Node has existed, in seconds
this.onlineTimeSeconds = 0;
// Node's RAM (GB)
this.ram = 1;
// Total money earned by this Node
this.totalMoneyGenerated = 0;
this.name = name;
this.updateMoneyGainRate(prodMult);
}
/**
* Initiatizes a HacknetNode object from a JSON save state.
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(HacknetNode, value.data);
}
// Get the cost to upgrade this Node's number of cores
calculateCoreUpgradeCost(levels = 1, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.cores >= exports.HacknetNodeMaxCores) {
return Infinity;
}
const coreBaseCost = exports.BaseCostForHacknetNodeCore;
const mult = exports.HacknetNodeUpgradeCoreMult;
let totalCost = 0;
let currentCores = this.cores;
for (let i = 0; i < sanitizedLevels; ++i) {
totalCost += (coreBaseCost * Math.pow(mult, currentCores - 1));
++currentCores;
}
totalCost *= costMult;
return totalCost;
}
// Get the cost to upgrade this Node's level
calculateLevelUpgradeCost(levels = 1, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.level >= exports.HacknetNodeMaxLevel) {
return Infinity;
}
const mult = exports.HacknetNodeUpgradeLevelMult;
let totalMultiplier = 0;
let currLevel = this.level;
for (let i = 0; i < sanitizedLevels; ++i) {
totalMultiplier += Math.pow(mult, currLevel);
++currLevel;
}
return exports.BaseCostForHacknetNode / 2 * totalMultiplier * costMult;
}
// Get the cost to upgrade this Node's RAM
calculateRamUpgradeCost(levels = 1, costMult) {
const sanitizedLevels = Math.round(levels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (this.ram >= exports.HacknetNodeMaxRam) {
return Infinity;
}
let totalCost = 0;
let numUpgrades = Math.round(Math.log2(this.ram));
let currentRam = this.ram;
for (let i = 0; i < sanitizedLevels; ++i) {
let baseCost = currentRam * exports.BaseCostFor1GBOfRamHacknetNode;
let mult = Math.pow(exports.HacknetNodeUpgradeRamMult, numUpgrades);
totalCost += (baseCost * mult);
currentRam *= 2;
++numUpgrades;
}
totalCost *= costMult;
return totalCost;
}
// Process this Hacknet Node in the game loop.
// Returns the amount of money generated
process(numCycles = 1) {
const seconds = numCycles * Constants_1.CONSTANTS.MilliPerCycle / 1000;
let gain = this.moneyGainRatePerSecond * seconds;
if (isNaN(gain)) {
console.error(`Hacknet Node ${this.name} calculated earnings of NaN`);
gain = 0;
}
this.totalMoneyGenerated += gain;
this.onlineTimeSeconds += seconds;
return gain;
}
// Upgrade this Node's number of cores, if possible
// Returns a boolean indicating whether new cores were successfully bought
upgradeCore(levels = 1, prodMult) {
this.cores = Math.min(exports.HacknetNodeMaxCores, Math.round(this.cores + levels));
this.updateMoneyGainRate(prodMult);
}
// Upgrade this Node's level, if possible
// Returns a boolean indicating whether the level was successfully updated
upgradeLevel(levels = 1, prodMult) {
this.level = Math.min(exports.HacknetNodeMaxLevel, Math.round(this.level + levels));
this.updateMoneyGainRate(prodMult);
}
// Upgrade this Node's RAM, if possible
// Returns a boolean indicating whether the RAM was successfully upgraded
upgradeRam(levels = 1, prodMult) {
for (let i = 0; i < levels; ++i) {
this.ram *= 2; // Ram is always doubled
}
this.ram = Math.round(this.ram); // Handle any floating point precision issues
this.updateMoneyGainRate(prodMult);
}
// Re-calculate this Node's production and update the moneyGainRatePerSecond prop
updateMoneyGainRate(prodMult) {
//How much extra $/s is gained per level
var gainPerLevel = exports.HacknetNodeMoneyGainPerLevel;
this.moneyGainRatePerSecond = (this.level * gainPerLevel) *
Math.pow(1.035, this.ram - 1) *
((this.cores + 5) / 6) *
prodMult *
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney;
if (isNaN(this.moneyGainRatePerSecond)) {
this.moneyGainRatePerSecond = 0;
DialogBox_1.dialogBoxCreate("Error in calculating Hacknet Node production. Please report to game developer", false);
}
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("HacknetNode", this);
}
}
exports.HacknetNode = HacknetNode;
JSONReviver_1.Reviver.constructors.HacknetNode = HacknetNode;
/***/ }),
/* 55 */
/*!**************************************************!*\
!*** ./src/Company/data/companypositionnames.ts ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Defs for job titles, stored in arrays and categorized by job "type"
Object.defineProperty(exports, "__esModule", { value: true });
exports.SoftwareCompanyPositions = [
"Software Engineering Intern",
"Junior Software Engineer",
"Senior Software Engineer",
"Lead Software Developer",
"Head of Software",
"Head of Engineering",
"Vice President of Technology",
"Chief Technology Officer"
];
exports.ITCompanyPositions = [
"IT Intern",
"IT Analyst",
"IT Manager",
"Systems Administrator"
];
exports.SecurityEngineerCompanyPositions = [
"Security Engineer"
];
exports.NetworkEngineerCompanyPositions = [
"Network Engineer",
"Network Administrator"
];
exports.BusinessCompanyPositions = [
"Business Intern",
"Business Analyst",
"Business Manager",
"Operations Manager",
"Chief Financial Officer",
"Chief Executive Officer"
];
exports.SecurityCompanyPositions = [
"Police Officer",
"Police Chief",
"Security Guard",
"Security Officer",
"Security Supervisor",
"Head of Security"
];
exports.AgentCompanyPositions = [
"Field Agent",
"Secret Agent",
"Special Operative"
];
exports.MiscCompanyPositions = [
"Waiter",
"Employee"
];
exports.SoftwareConsultantCompanyPositions = [
"Software Consultant",
"Senior Software Consultant"
];
exports.BusinessConsultantCompanyPositions = [
"Business Consultant",
"Senior Business Consultant"
];
exports.PartTimeCompanyPositions = [
"Part-time Waiter",
"Part-time Employee"
];
/***/ }),
/* 56 */
/*!************************!*\
!*** ./src/Hacking.js ***!
\************************/
/*! exports provided: calculateHackingChance, calculateHackingExpGain, calculatePercentMoneyHacked, calculateHackingTime, calculateGrowTime, calculateWeakenTime */
/*! exports used: calculateGrowTime, calculateHackingChance, calculateHackingExpGain, calculateHackingTime, calculatePercentMoneyHacked, calculateWeakenTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return calculateHackingChance; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return calculateHackingExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return calculatePercentMoneyHacked; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return calculateHackingTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return calculateGrowTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return calculateWeakenTime; });
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server/Server */ 105);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Server_Server__WEBPACK_IMPORTED_MODULE_2__);
/**
* Returns the chance the player has to successfully hack a server
*/
function calculateHackingChance(server) {
const hackFactor = 1.75;
const intFactor = 0.2;
const difficultyMult = (100 - server.hackDifficulty) / 100;
const skillMult = (hackFactor * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill) + (intFactor * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence);
const skillChance = (skillMult - server.requiredHackingSkill) / skillMult;
const chance = skillChance * difficultyMult * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_chance_mult;
if (chance > 1) { return 1; }
if (chance < 0) { return 0; }
return chance;
}
/**
* Returns the amount of hacking experience the player will gain upon
* successfully hacking a server
*/
function calculateHackingExpGain(server) {
const baseExpGain = 3;
const diffFactor = 0.3;
if (server.baseDifficulty == null) {
server.baseDifficulty = server.hackDifficulty;
}
var expGain = baseExpGain;
expGain += (server.baseDifficulty * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_exp_mult * diffFactor);
return expGain * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain;
}
/**
* Returns the percentage of money that will be stolen from a server if
* it is successfully hacked (returns the decimal form, not the actual percent value)
*/
function calculatePercentMoneyHacked(server) {
// Adjust if needed for balancing. This is the divisor for the final calculation
const balanceFactor = 240;
const difficultyMult = (100 - server.hackDifficulty) / 100;
const skillMult = (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill - (server.requiredHackingSkill - 1)) / _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill;
const percentMoneyHacked = difficultyMult * skillMult * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_money_mult / balanceFactor;
if (percentMoneyHacked < 0) { return 0; }
if (percentMoneyHacked > 1) { return 1; }
return percentMoneyHacked * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney;
}
/**
* Returns time it takes to complete a hack on a server, in seconds
*/
function calculateHackingTime(server, hack, int) {
const difficultyMult = server.requiredHackingSkill * server.hackDifficulty;
const baseDiff = 500;
const baseSkill = 50;
const diffFactor = 2.5;
const intFactor = 0.1;
if (hack == null) {hack = _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill;}
if (int == null) {int = _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence;}
var skillFactor = (diffFactor * difficultyMult + baseDiff);
// tslint:disable-next-line
skillFactor /= (hack + baseSkill + (intFactor * int));
const hackTimeMultiplier = 5;
const hackingTime = hackTimeMultiplier * skillFactor / _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_speed_mult;
return hackingTime;
}
/**
* Returns time it takes to complete a grow operation on a server, in seconds
*/
function calculateGrowTime(server, hack, int) {
const growTimeMultiplier = 3.2; // Relative to hacking time. 16/5 = 3.2
return growTimeMultiplier * calculateHackingTime(server, hack, int);
}
/**
* Returns time it takes to complete a weaken operation on a server, in seconds
*/
function calculateWeakenTime(server, hack, int) {
const weakenTimeMultiplier = 4; // Relative to hacking time
return weakenTimeMultiplier * calculateHackingTime(server, hack, int);
}
/***/ }),
/* 57 */
/*!***********************************************!*\
!*** ./src/StockMarket/data/PositionTypes.ts ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PositionTypes;
(function (PositionTypes) {
PositionTypes["Long"] = "L";
PositionTypes["Short"] = "S";
})(PositionTypes = exports.PositionTypes || (exports.PositionTypes = {}));
/***/ }),
/* 58 */
/*!***************************************************!*\
!*** ./utils/uiHelpers/createPopupCloseButton.ts ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Creates a Close/Cancel button that is used for removing popups
*/
Object.defineProperty(exports, "__esModule", { value: true });
const createElement_1 = __webpack_require__(/*! ./createElement */ 3);
const removeElement_1 = __webpack_require__(/*! ./removeElement */ 76);
function createPopupCloseButton(popup, options) {
let button;
function closePopupWithEscFn(e) {
if (e.keyCode === 27) {
button.click();
}
}
button = createElement_1.createElement("button", {
class: options.class ? options.class : "popup-box-button",
display: options.display ? options.display : "inline-block",
innerText: options.innerText == null ? "Cancel" : options.innerText,
clickListener: () => {
if (popup instanceof Element) {
removeElement_1.removeElement(popup);
}
else {
try {
const popupEl = document.getElementById(popup);
if (popupEl instanceof Element) {
removeElement_1.removeElement(popupEl);
}
}
catch (e) {
console.error(`createPopupCloseButton() threw: ${e}`);
}
}
document.removeEventListener("keydown", closePopupWithEscFn);
return false;
},
});
document.addEventListener("keydown", closePopupWithEscFn);
return button;
}
exports.createPopupCloseButton = createPopupCloseButton;
/***/ }),
/* 59 */
/*!**********************!*\
!*** ./src/Alias.ts ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const postToTerminal_1 = __webpack_require__(/*! ./ui/postToTerminal */ 7);
exports.Aliases = {};
exports.GlobalAliases = {};
function loadAliases(saveString) {
if (saveString === "") {
exports.Aliases = {};
}
else {
exports.Aliases = JSON.parse(saveString);
}
}
exports.loadAliases = loadAliases;
function loadGlobalAliases(saveString) {
if (saveString === "") {
exports.GlobalAliases = {};
}
else {
exports.GlobalAliases = JSON.parse(saveString);
}
}
exports.loadGlobalAliases = loadGlobalAliases;
// Prints all aliases to terminal
function printAliases() {
for (var name in exports.Aliases) {
if (exports.Aliases.hasOwnProperty(name)) {
postToTerminal_1.post("alias " + name + "=" + exports.Aliases[name]);
}
}
for (var name in exports.GlobalAliases) {
if (exports.GlobalAliases.hasOwnProperty(name)) {
postToTerminal_1.post("global alias " + name + "=" + exports.GlobalAliases[name]);
}
}
}
exports.printAliases = printAliases;
// Returns true if successful, false otherwise
function parseAliasDeclaration(dec, global = false) {
var re = /^([_|\w|!|%|,|@]+)="(.+)"$/;
var matches = dec.match(re);
if (matches == null || matches.length != 3) {
return false;
}
if (global) {
addGlobalAlias(matches[1], matches[2]);
}
else {
addAlias(matches[1], matches[2]);
}
return true;
}
exports.parseAliasDeclaration = parseAliasDeclaration;
function addAlias(name, value) {
if (name in exports.GlobalAliases) {
delete exports.GlobalAliases[name];
}
exports.Aliases[name] = value;
}
function addGlobalAlias(name, value) {
if (name in exports.Aliases) {
delete exports.Aliases[name];
}
exports.GlobalAliases[name] = value;
}
function getAlias(name) {
if (exports.Aliases.hasOwnProperty(name)) {
return exports.Aliases[name];
}
return null;
}
function getGlobalAlias(name) {
if (exports.GlobalAliases.hasOwnProperty(name)) {
return exports.GlobalAliases[name];
}
return null;
}
function removeAlias(name) {
if (exports.Aliases.hasOwnProperty(name)) {
delete exports.Aliases[name];
return true;
}
if (exports.GlobalAliases.hasOwnProperty(name)) {
delete exports.GlobalAliases[name];
return true;
}
return false;
}
exports.removeAlias = removeAlias;
/**
* Returns the original string with any aliases substituted in.
* Aliases are only applied to "whole words", one level deep
*/
function substituteAliases(origCommand) {
const commandArray = origCommand.split(" ");
if (commandArray.length > 0) {
// For the unalias command, dont substite
if (commandArray[0] === "unalias") {
return commandArray.join(" ");
}
var alias = getAlias(commandArray[0]);
if (alias != null) {
commandArray[0] = alias;
}
else {
var alias = getGlobalAlias(commandArray[0]);
if (alias != null) {
commandArray[0] = alias;
}
}
for (var i = 0; i < commandArray.length; ++i) {
var alias = getGlobalAlias(commandArray[i]);
if (alias != null) {
commandArray[i] = alias;
}
}
}
return commandArray.join(" ");
}
exports.substituteAliases = substituteAliases;
/***/ }),
/* 60 */,
/* 61 */
/*!************************************************!*\
!*** ./utils/uiHelpers/createOptionElement.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const createElement_1 = __webpack_require__(/*! ./createElement */ 3);
function createOptionElement(text, value = "") {
let sanitizedValue = value;
if (sanitizedValue === "") {
sanitizedValue = text;
}
return createElement_1.createElement("option", {
text: text,
value: sanitizedValue,
});
}
exports.createOptionElement = createOptionElement;
/***/ }),
/* 62 */
/*!***************************************!*\
!*** ./src/Script/ScriptHelpersTS.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Script helper functions
function isScriptFilename(f) {
return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns");
}
exports.isScriptFilename = isScriptFilename;
/***/ }),
/* 63 */
/*!**************************************************!*\
!*** ./src/Corporation/ui/BaseReactComponent.js ***!
\**************************************************/
/*! exports provided: BaseReactComponent */
/*! exports used: BaseReactComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BaseReactComponent; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 1);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
// Base class for React Components for Corporation UI
// Contains a few helper functions that let derived classes easily
// access Corporation properties
const Component = react__WEBPACK_IMPORTED_MODULE_0___default.a.Component;
class BaseReactComponent extends Component {
corp() {
return this.props.corp;
}
eventHandler() {
return this.props.eventHandler;
}
routing() {
return this.props.routing;
}
render() {}
}
/***/ }),
/* 64 */,
/* 65 */
/*!********************************!*\
!*** ./src/Message/Message.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
class Message {
constructor(filename = "", msg = "") {
// Name of Message file
this.filename = "";
// The text contains in the Message
this.msg = "";
// Flag indicating whether this Message has been received by the player
this.recvd = false;
this.filename = filename;
this.msg = msg;
this.recvd = false;
}
// Initializes a Message Object from a JSON save state
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Message, value.data);
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("Message", this);
}
}
exports.Message = Message;
JSONReviver_1.Reviver.constructors.Message = Message;
/***/ }),
/* 66 */
/*!********************************************!*\
!*** ./src/StockMarket/data/OrderTypes.ts ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OrderTypes;
(function (OrderTypes) {
OrderTypes["LimitBuy"] = "Limit Buy Order";
OrderTypes["LimitSell"] = "Limit Sell Order";
OrderTypes["StopBuy"] = "Stop Buy Order";
OrderTypes["StopSell"] = "Stop Sell Order";
})(OrderTypes = exports.OrderTypes || (exports.OrderTypes = {}));
/***/ }),
/* 67 */
/*!*************************************!*\
!*** ./src/Script/ScriptHelpers.js ***!
\*************************************/
/*! exports provided: scriptEditorInit, getCurrentEditor, updateScriptEditorContent, scriptCalculateOfflineProduction, findRunningScript */
/*! exports used: findRunningScript, getCurrentEditor, scriptCalculateOfflineProduction, scriptEditorInit, updateScriptEditorContent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return scriptEditorInit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCurrentEditor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return updateScriptEditorContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return scriptCalculateOfflineProduction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return findRunningScript; });
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Script */ 116);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Script__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _RamCalculations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./RamCalculations */ 197);
/* harmony import */ var _ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ScriptHelpersTS */ 62);
/* harmony import */ var _ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../engine */ 14);
/* harmony import */ var _Fconf_Fconf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Fconf/Fconf */ 128);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Fconf/FconfSettings */ 34);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../InteractiveTutorial */ 40);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../ScriptEditor/Ace */ 122);
/* harmony import */ var _ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../ScriptEditor/CodeMirror */ 121);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Server/AllServers */ 21);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Settings/SettingEnums */ 53);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Terminal/DirectoryHelpers */ 93);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../TextFile */ 96);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../utils/helpers/compareArrays */ 150);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__);
var scriptEditorRamCheck = null, scriptEditorRamText = null;
function scriptEditorInit() {
// Wrapper container that holds all the buttons below the script editor
const wrapper = document.getElementById("script-editor-buttons-wrapper");
if (wrapper == null) {
console.error("Could not find 'script-editor-buttons-wrapper'");
return false;
}
// Beautify button
const beautifyButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("button", {
class: "std-button",
display: "inline-block",
innerText: "Beautify",
clickListener:()=>{
let editor = getCurrentEditor();
if (editor != null) {
editor.beautifyScript();
}
return false;
}
});
// Text that displays RAM calculation
scriptEditorRamText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("p", {
display:"inline-block", margin:"10px", id:"script-editor-status-text"
});
// Label for checkbox (defined below)
const checkboxLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("label", {
for:"script-editor-ram-check", margin:"4px", marginTop: "8px",
innerText:"Dynamic RAM Usage Checker", color:"white",
tooltip:"Enable/Disable the dynamic RAM Usage display. You may " +
"want to disable it for very long scripts because there may be " +
"performance issues"
});
// Checkbox for enabling/disabling dynamic RAM calculation
scriptEditorRamCheck = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("input", {
type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check",
margin:"4px", marginTop: "8px",
});
scriptEditorRamCheck.checked = true;
// Link to Netscript documentation
const documentationButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class: "std-button",
display: "inline-block",
href:"https://bitburner.readthedocs.io/en/latest/index.html",
innerText:"Netscript Documentation",
target:"_blank",
});
// Save and Close button
const closeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("button", {
class: "std-button",
display: "inline-block",
innerText: "Save & Close (Ctrl/Cmd + b)",
clickListener:()=>{
saveAndCloseScriptEditor();
return false;
}
});
// Add all buttons to the UI
wrapper.appendChild(beautifyButton);
wrapper.appendChild(closeButton);
wrapper.appendChild(scriptEditorRamText);
wrapper.appendChild(scriptEditorRamCheck);
wrapper.appendChild(checkboxLabel);
wrapper.appendChild(documentationButton);
// Initialize editors
const initParams = {
saveAndCloseFn: saveAndCloseScriptEditor,
quitFn: _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadTerminalContent,
}
_ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].init(initParams);
_ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].init(initParams);
// Setup the selector for which Editor to use
const editorSelector = document.getElementById("script-editor-option-editor");
if (editorSelector == null) {
console.error(`Could not find DOM Element for editor selector (id=script-editor-option-editor)`);
return false;
}
for (let i = 0; i < editorSelector.options.length; ++i) {
if (editorSelector.options[i].value === _Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].Editor) {
editorSelector.selectedIndex = i;
break;
}
}
editorSelector.onchange = () => {
const opt = editorSelector.value;
switch (opt) {
case _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["EditorSetting"].Ace: {
const codeMirrorCode = _ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].getCode();
const codeMirrorFn = _ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].getFilename();
_ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].create();
_ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].setInvisible();
_ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].openScript(codeMirrorFn, codeMirrorCode);
break;
}
case _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["EditorSetting"].CodeMirror: {
const aceCode = _ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].getCode();
const aceFn = _ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].getFilename();
_ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].create();
_ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"].setInvisible();
_ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"].openScript(aceFn, aceCode);
break;
}
default:
console.error(`Unrecognized Editor Setting: ${opt}`);
return;
}
_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].Editor = opt;
}
editorSelector.onchange(); // Trigger the onchange event handler
}
function getCurrentEditor() {
switch (_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].Editor) {
case _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["EditorSetting"].Ace:
return _ScriptEditor_Ace__WEBPACK_IMPORTED_MODULE_9__[/* AceEditor */ "a"];
case _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["EditorSetting"].CodeMirror:
return _ScriptEditor_CodeMirror__WEBPACK_IMPORTED_MODULE_10__[/* CodeMirrorEditor */ "a"];
default:
console.log(`Invalid Editor Setting: ${_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].Editor}`);
throw new Error(`Invalid Editor Setting: ${_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].Editor}`);
return null;
}
}
//Updates RAM usage in script
async function updateScriptEditorContent() {
var filename = document.getElementById("script-editor-filename").value;
if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !Object(_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_2__["isScriptFilename"])(filename)) {
scriptEditorRamText.innerText = "N/A";
return;
}
let code;
try {
code = getCurrentEditor().getCode();
} catch(e) {
scriptEditorRamText.innerText = "RAM: ERROR";
return;
}
var codeCopy = code.repeat(1);
var ramUsage = await Object(_RamCalculations__WEBPACK_IMPORTED_MODULE_1__["calculateRamUsage"])(codeCopy, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer().scripts);
if (ramUsage !== -1) {
scriptEditorRamText.innerText = "RAM: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(ramUsage, '0.00') + " GB";
} else {
scriptEditorRamText.innerText = "RAM: Syntax Error";
}
}
//Define key commands in script editor (ctrl o to save + close, etc.)
$(document).keydown(function(e) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_13__["Settings"].DisableHotkeys === true) {return;}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__["Page"].ScriptEditor)) {
//Ctrl + b
if (e.keyCode == 66 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
saveAndCloseScriptEditor();
}
}
});
function saveAndCloseScriptEditor() {
var filename = document.getElementById("script-editor-filename").value;
let code;
try {
code = getCurrentEditor().getCode();
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Something went wrong when trying to save (getCurrentEditor().getCode()). Please report to game developer with details");
return;
}
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__[/* ITutorial */ "a"].isRunning && _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__[/* ITutorial */ "a"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__[/* iTutorialSteps */ "d"].TerminalTypeScript) {
//Make sure filename + code properly follow tutorial
if (filename !== "foodnstuff.script") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Leave the script name as 'foodnstuff'!");
return;
}
code = code.replace(/\s/g, "");
if (code.indexOf("while(true){hack('foodnstuff');}") == -1) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!");
return;
}
//Save the script
let s = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer();
for (var i = 0; i < s.scripts.length; i++) {
if (filename == s.scripts[i].filename) {
s.scripts[i].saveScript(getCurrentEditor().getCode(), _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].currentServer, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer().scripts);
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadTerminalContent();
return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__[/* iTutorialNextStep */ "b"])();
}
}
// If the current script does NOT exist, create a new one
let script = new _Script__WEBPACK_IMPORTED_MODULE_0__["Script"]();
script.saveScript(getCurrentEditor().getCode(), _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].currentServer, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer().scripts);
s.scripts.push(script);
return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__[/* iTutorialNextStep */ "b"])();
}
if (filename == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("You must specify a filename!");
return;
}
if (filename !== ".fconf" && !Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_15__["isValidFilePath"])(filename)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores");
return;
}
var s = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer();
if (filename === ".fconf") {
try {
Object(_Fconf_Fconf__WEBPACK_IMPORTED_MODULE_5__[/* parseFconfSettings */ "c"])(code);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])(`Invalid .fconf file: ${e}`);
return;
}
} else if (Object(_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_2__["isScriptFilename"])(filename)) {
//If the current script already exists on the server, overwrite it
for (var i = 0; i < s.scripts.length; i++) {
if (filename == s.scripts[i].filename) {
s.scripts[i].saveScript(getCurrentEditor().getCode(), _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].currentServer, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer().scripts);
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadTerminalContent();
return;
}
}
//If the current script does NOT exist, create a new one
const script = new _Script__WEBPACK_IMPORTED_MODULE_0__["Script"]();
script.saveScript(getCurrentEditor().getCode(), _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].currentServer, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getCurrentServer().scripts);
s.scripts.push(script);
} else if (filename.endsWith(".txt")) {
for (var i = 0; i < s.textFiles.length; ++i) {
if (s.textFiles[i].fn === filename) {
s.textFiles[i].write(code);
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadTerminalContent();
return;
}
}
var textFile = new _TextFile__WEBPACK_IMPORTED_MODULE_16__["TextFile"](filename, code);
s.textFiles.push(textFile);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Invalid filename. Must be either a script (.script) or " +
" or text file (.txt)")
return;
}
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadTerminalContent();
}
function scriptCalculateOfflineProduction(runningScriptObj) {
//The Player object stores the last update time from when we were online
var thisUpdate = new Date().getTime();
var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].lastUpdate;
var timePassed = (thisUpdate - lastUpdate) / 1000; //Seconds
//Calculate the "confidence" rating of the script's true production. This is based
//entirely off of time. We will arbitrarily say that if a script has been running for
//4 hours (14400 sec) then we are completely confident in its ability
var confidence = (runningScriptObj.onlineRunningTime) / 14400;
if (confidence >= 1) {confidence = 1;}
//Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
// Grow
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;}
var serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_11__["AllServers"][ip];
if (serv == null) {continue;}
var timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
runningScriptObj.log("Called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
var growth = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_12__["processSingleServerGrowth"])(serv, timesGrown * 450, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"]);
runningScriptObj.log(serv.hostname + " grown by " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__["numeralWrapper"].format(growth * 100 - 100, '0.000000%') + " from grow() calls made while offline");
}
}
// Money from hacking
var totalOfflineProduction = 0;
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][0] == 0 || runningScriptObj.dataMap[ip][0] == null) {continue;}
var serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_11__["AllServers"][ip];
if (serv == null) {continue;}
var production = 0.5 * runningScriptObj.dataMap[ip][0] / runningScriptObj.onlineRunningTime * timePassed;
production *= confidence;
if (production > serv.moneyAvailable) {
production = serv.moneyAvailable;
}
totalOfflineProduction += production;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainMoney(production);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].recordMoneySource(production, "hacking");
console.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
runningScriptObj.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
serv.moneyAvailable -= production;
if (serv.moneyAvailable < 0) {serv.moneyAvailable = 0;}
if (isNaN(serv.moneyAvailable)) {serv.moneyAvailable = 0;}
}
}
// Offline EXP gain
// A script's offline production will always be at most half of its online production.
var expGain = 0.5 * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed;
expGain *= confidence;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainHackingExp(expGain);
// Update script stats
runningScriptObj.offlineMoneyMade += totalOfflineProduction;
runningScriptObj.offlineRunningTime += timePassed;
runningScriptObj.offlineExpGained += expGain;
// Fortify a server's security based on how many times it was hacked
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][1] == 0 || runningScriptObj.dataMap[ip][1] == null) {continue;}
var serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_11__["AllServers"][ip];
if (serv == null) {continue;}
var timesHacked = Math.round(0.5 * runningScriptObj.dataMap[ip][1] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " hacked " + serv.hostname + " " + timesHacked + " times while offline");
runningScriptObj.log("Hacked " + serv.hostname + " " + timesHacked + " times while offline");
serv.fortify(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ServerFortifyAmount * timesHacked);
}
}
// Weaken
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;}
var serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_11__["AllServers"][ip];
if (serv == null) {continue;}
var timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
runningScriptObj.log("Called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
serv.weaken(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ServerWeakenAmount * timesWeakened);
}
}
return totalOfflineProduction;
}
//Returns a RunningScript object matching the filename and arguments on the
//designated server, and false otherwise
function findRunningScript(filename, args, server) {
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename === filename &&
Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_21__["compareArrays"])(server.runningScripts[i].args, args)) {
return server.runningScripts[i];
}
}
return null;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 68 */
/*!************************************!*\
!*** ./src/utils/SetTimeoutRef.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// This is a reference to the native setTimeout() function
// setTimeout() is used in various places around the game's source code.
// This reference is used to make sure that if players alter window.setTimeout()
// through NetscriptJS, then the game will still function properly
exports.setTimeoutRef = window.setTimeout.bind(window);
/***/ }),
/* 69 */
/*!*********************!*\
!*** ./src/Gang.js ***!
\*********************/
/*! exports provided: AllGangs, resetGangs, loadAllGangs, Gang */
/*! exports used: AllGangs, Gang, loadAllGangs, resetGangs */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllGangs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return resetGangs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadAllGangs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Gang; });
/* harmony import */ var _data_gangmembertasks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./data/gangmembertasks */ 280);
/* harmony import */ var _data_gangmembertasks__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_data_gangmembertasks__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _data_gangmemberupgrades__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./data/gangmemberupgrades */ 279);
/* harmony import */ var _data_gangmemberupgrades__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_data_gangmemberupgrades__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction/Faction */ 71);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction/Factions */ 13);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 52);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver */ 17);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 49);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 15);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/createAccordionElement */ 109);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 41);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/removeElement */ 76);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 29);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__);
/**
* TODO
* Add police clashes
* balance point to keep them from running out of control
*/
// Constants
const GangRespectToReputationRatio = 5; // Respect is divided by this to get rep gain
const MaximumGangMembers = 30;
const GangRecruitCostMultiplier = 2;
const CyclesPerTerritoryAndPowerUpdate = 100;
const AscensionMultiplierRatio = 15 / 100; // Portion of upgrade multiplier that is kept after ascending
// Switch between territory and management screen with 1 and 2
$(document).keydown(function(event) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["Page"].Gang) && event.altKey) {
if (UIElems.gangMemberFilter != null && UIElems.gangMemberFilter === document.activeElement) {return;}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__["KEY"]["1"]) {
if(UIElems.gangTerritorySubpage.style.display === "block") {
UIElems.managementButton.click();
}
} else if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__["KEY"]["2"]) {
if (UIElems.gangManagementSubpage.style.display === "block") {
UIElems.territoryButton.click();
}
}
}
});
// 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";
if (UIElems.gangMemberUpgradeBoxOpened) {
if ( $(event.target).closest("#" + contentId).get(0) == null ) {
//Delete the box
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18__["removeElement"])(UIElems.gangMemberUpgradeBox);
UIElems.gangMemberUpgradeBox = null;
UIElems.gangMemberUpgradeBoxContent = null;
UIElems.gangMemberUpgradeBoxOpened = false;
UIElems.gangMemberUpgradeBoxElements = null;
}
}
});
const GangNames = [
"Slum Snakes",
"Tetrads",
"The Syndicate",
"The Dark Army",
"Speakers for the Dead",
"NiteSec",
"The Black Hand"
];
let AllGangs = {
"Slum Snakes" : {
power: 1,
territory: 1/7,
},
"Tetrads" : {
power: 1,
territory: 1/7,
},
"The Syndicate" : {
power: 1,
territory: 1/7,
},
"The Dark Army" : {
power: 1,
territory: 1/7,
},
"Speakers for the Dead" : {
power: 1,
territory: 1/7,
},
"NiteSec" : {
power: 1,
territory: 1/7,
},
"The Black Hand" : {
power: 1,
territory: 1/7,
},
}
function resetGangs() {
AllGangs = {
"Slum Snakes" : {
power: 1,
territory: 1/7,
},
"Tetrads" : {
power: 1,
territory: 1/7,
},
"The Syndicate" : {
power: 1,
territory: 1/7,
},
"The Dark Army" : {
power: 1,
territory: 1/7,
},
"Speakers for the Dead" : {
power: 1,
territory: 1/7,
},
"NiteSec" : {
power: 1,
territory: 1/7,
},
"The Black Hand" : {
power: 1,
territory: 1/7,
},
}
}
function loadAllGangs(saveString) {
AllGangs = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"]);
}
/**
* @param facName {string} Name of corresponding faction
* @param hacking {bollean} Whether or not its a hacking gang
*/
function Gang(facName, hacking=false) {
this.facName = facName;
this.members = [];
this.wanted = 1;
this.respect = 1;
this.isHackingGang = hacking;
this.respectGainRate = 0;
this.wantedGainRate = 0;
this.moneyGainRate = 0;
// When processing gains, this stores the number of cycles until some
// limit is reached, and then calculates and applies the gains only at that limit
this.storedCycles = 0;
// Separate variable to keep track of cycles for Territry + Power gang, which
// happens on a slower "clock" than normal processing
this.storedTerritoryAndPowerCycles = 0;
this.territoryClashChance = 0;
this.territoryWarfareEngaged = false;
this.notifyMemberDeath = true;
}
Gang.prototype.getPower = function() {
return AllGangs[this.facName].power;
}
Gang.prototype.getTerritory = function() {
return AllGangs[this.facName].territory;
}
Gang.prototype.process = function(numCycles=1, player) {
const CyclesPerSecond = 1000 / _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed;
if (isNaN(numCycles)) {
console.error(`NaN passed into Gang.process(): ${numCycles}`);
}
this.storedCycles += numCycles;
// Only process if there are at least 2 seconds, and at most 5 seconds
if (this.storedCycles < 2 * CyclesPerSecond) { return; }
const cycles = Math.min(this.storedCycles, 5 * CyclesPerSecond);
try {
this.processGains(cycles, player);
this.processExperienceGains(cycles);
this.processTerritoryAndPowerGains(cycles);
this.storedCycles -= cycles;
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__["exceptionAlert"])(`Exception caught when processing Gang: ${e}`);
}
}
Gang.prototype.processGains = function(numCycles=1, player) {
// 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));
wantedLevelGains += (this.members[i].calculateWantedLevelGain(this));
moneyGains += (this.members[i].calculateMoneyGain(this));
}
this.respectGainRate = respectGains;
this.wantedGainRate = wantedLevelGains;
this.moneyGainRate = moneyGains;
if (typeof respectGains === "number") {
const gain = respectGains * numCycles;
this.respect += gain;
// Faction reputation gains is respect gain divided by some constant
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_4__["Factions"][this.facName];
if (!(fac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_3__["Faction"])) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("ERROR: Could not get Faction associates with your gang. This is a bug, please report to game dev");
} else {
var favorMult = 1 + (fac.favor / 100);
fac.playerReputation += ((player.faction_rep_mult * gain * favorMult) / GangRespectToReputationRatio);
}
// Keep track of respect gained per member
for (let i = 0; i < this.members.length; ++i) {
this.members[i].recordEarnedRespect(numCycles, this);
}
} else {
console.warn("respectGains calculated to be NaN");
}
if (typeof wantedLevelGains === "number") {
if (this.wanted === 1 && wantedLevelGains < 0) {
// At minimum wanted, do nothing
} else {
const oldWanted = this.wanted;
let newWanted = oldWanted + (wantedLevelGains * numCycles);
// Prevent overflow
if (wantedLevelGains <= 0 && newWanted > oldWanted) {
newWanted = 1;
}
this.wanted = newWanted;
if (this.wanted < 1) {this.wanted = 1;}
}
} else {
console.warn("ERROR: wantedLevelGains is NaN");
}
if (typeof moneyGains === "number") {
player.gainMoney(moneyGains * numCycles);
player.recordMoneySource(moneyGains * numCycles, "gang");
} else {
console.warn("ERROR: respectGains is NaN");
}
}
Gang.prototype.processTerritoryAndPowerGains = function(numCycles=1) {
this.storedTerritoryAndPowerCycles += numCycles;
if (this.storedTerritoryAndPowerCycles < CyclesPerTerritoryAndPowerUpdate) { return; }
this.storedTerritoryAndPowerCycles -= CyclesPerTerritoryAndPowerUpdate;
// Process power first
var gangName = this.facName;
for (const name in AllGangs) {
if (AllGangs.hasOwnProperty(name)) {
if (name == gangName) {
AllGangs[name].power += this.calculatePower();
} else {
// All NPC gangs get random power gains
const gainRoll = Math.random();
if (gainRoll < 0.5) {
// Multiplicative gain (50% chance)
// This is capped per cycle, to prevent it from getting out of control
const multiplicativeGain = AllGangs[name].power * 0.005;
AllGangs[name].power += Math.min(0.85, multiplicativeGain);
} else {
// Additive gain (50% chance)
const additiveGain = 0.75 * gainRoll * AllGangs[name].territory;
AllGangs[name].power += (additiveGain);
}
}
}
}
// Determine if territory should be processed
if (this.territoryWarfareEngaged) {
this.territoryClashChance = 1;
} else if (this.territoryClashChance > 0) {
// Engagement turned off, but still a positive clash chance. So there's
// still a chance of clashing but it slowly goes down over time
this.territoryClashChance = Math.max(0, this.territoryClashChance - 0.01);
}
// Then process territory
for (let i = 0; i < GangNames.length; ++i) {
const others = GangNames.filter((e) => {
return e !== GangNames[i];
});
const other = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(0, others.length - 1);
const thisGang = GangNames[i];
const otherGang = others[other];
// If either of the gangs involved in this clash is the player, determine
// whether to skip or process it using the clash chance
if (thisGang === gangName || otherGang === gangName) {
if (!(Math.random() < this.territoryClashChance)) { continue; }
}
const thisPwr = AllGangs[thisGang].power;
const otherPwr = AllGangs[otherGang].power;
const thisChance = thisPwr / (thisPwr + otherPwr);
if (Math.random() < thisChance) {
if (AllGangs[otherGang].territory <= 0) {
return;
}
AllGangs[thisGang].territory += 0.0001;
AllGangs[otherGang].territory -= 0.0001;
if (thisGang === gangName) {
this.clash(true); // Player won
AllGangs[otherGang].power *= (1 / 1.01);
} else if (otherGang === gangName) {
this.clash(false); // Player lost
} else {
AllGangs[otherGang].power *= (1 / 1.01);
}
} else {
if (AllGangs[thisGang].territory <= 0) {
return;
}
AllGangs[thisGang].territory -= 0.0001;
AllGangs[otherGang].territory += 0.0001;
if (thisGang === gangName) {
this.clash(false); // Player lost
} else if (otherGang === gangName) {
this.clash(true); // Player won
AllGangs[thisGang].power *= (1 / 1.01);
} else {
AllGangs[thisGang].power *= (1 / 1.01);
}
}
}
}
Gang.prototype.canRecruitMember = function() {
if (this.members.length >= MaximumGangMembers) { return false; }
return (this.respect >= this.getRespectNeededToRecruitMember());
}
Gang.prototype.getRespectNeededToRecruitMember = function() {
// First N gang members are free (can be recruited at 0 respect)
const numFreeMembers = 3;
if (this.members.length < numFreeMembers) { return 0; }
const i = this.members.length - (numFreeMembers - 1);
return Math.round(0.9 * Math.pow(i, 3) + Math.pow(i, 2));
}
Gang.prototype.recruitMember = function(name) {
name = String(name);
if (name === "" || !this.canRecruitMember()) { return false; }
// Check for already-existing names
let sameNames = this.members.filter((m) => {
return m.name === name;
});
if (sameNames.length >= 1) { return false; }
let member = new GangMember(name);
this.members.push(member);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["Page"].Gang)) {
this.createGangMemberDisplayElement(member);
this.updateGangContent();
}
return true;
}
// Money and Respect gains multiplied by this number (< 1)
Gang.prototype.getWantedPenalty = function() {
return (this.respect) / (this.respect + this.wanted);
}
Gang.prototype.processExperienceGains = function(numCycles=1) {
for (var i = 0; i < this.members.length; ++i) {
this.members[i].gainExperience(numCycles);
this.members[i].updateSkillLevels();
}
}
//Calculates power GAIN, which is added onto the Gang's existing power
Gang.prototype.calculatePower = function() {
var memberTotal = 0;
for (var i = 0; i < this.members.length; ++i) {
if (GangMemberTasks.hasOwnProperty(this.members[i].task) && this.members[i].task == "Territory Warfare") {
const gain = this.members[i].calculatePower();
memberTotal += gain;
}
}
return (0.015 * this.getTerritory() * memberTotal);
}
Gang.prototype.clash = function(won=false) {
// Determine if a gang member should die
let baseDeathChance = 0.01;
if (won) { baseDeathChance /= 2; }
// If the clash was lost, the player loses a small percentage of power
if (!won) {
AllGangs[this.facName].power *= (1 / 1.008);
}
// Deaths can only occur during X% of clashes
if (Math.random() < 0.65) { return; }
for (let i = this.members.length - 1; i >= 0; --i) {
const member = this.members[i];
// Only members assigned to Territory Warfare can die
if (member.task !== "Territory Warfare") { continue; }
// Chance to die is decreased based on defense
const modifiedDeathChance = baseDeathChance / Math.pow(member.def, 0.6);
if (Math.random() < modifiedDeathChance) {
this.killMember(member);
}
}
}
Gang.prototype.killMember = function(memberObj) {
const gangName = this.facName;
// Player loses a percentage of total respect, plus whatever respect that member has earned
const totalRespect = this.respect;
const lostRespect = (0.05 * totalRespect) + memberObj.earnedRespect;
this.respect = Math.max(0, totalRespect - lostRespect);
for (let i = 0; i < this.members.length; ++i) {
if (memberObj.name === this.members[i].name) {
this.members.splice(i, 1);
break;
}
}
// Notify of death
if (this.notifyMemberDeath) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])(`${memberObj.name} was killed in a gang clash! You lost ${lostRespect} respect`);
}
// Update UI
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["Page"].Gang)) {
this.displayGangMemberList();
}
}
Gang.prototype.ascendMember = function(memberObj, workerScript) {
try {
/**
* res is an object with the following format:
* {
* respect: Amount of respect to deduct
* hack/str/def/dex/agi/cha: Ascension multipliers gained for each stat
* }
*/
const res = memberObj.ascend();
this.respect = Math.max(1, this.respect - res.respect);
if (workerScript == null) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])([`You ascended ${memberObj.name}!`,
"",
`Your gang lost ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.respect, "0.000a")} respect`,
"",
`${memberObj.name} gained the following stat multipliers for ascending:`,
`Hacking: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.hack, "0.000%")}`,
`Strength: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.str, "0.000%")}`,
`Defense: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.def, "0.000%")}`,
`Dexterity: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.dex, "0.000%")}`,
`Agility: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.agi, "0.000%")}`,
`Charisma: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(res.cha, "0.000%")}`].join(" "));
} else {
workerScript.log(`Ascended Gang member ${memberObj.name}`);
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["Page"].Gang)) {
this.displayGangMemberList();
}
return res;
} catch(e) {
if (workerScript == null) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__["exceptionAlert"])(e);
} else {
throw e; // Re-throw, will be caught in the Netscript Function
}
}
}
// Cost of upgrade gets cheaper as gang increases in respect + power
Gang.prototype.getDiscount = function() {
const power = this.getPower();
const respect = this.respect;
const respectLinearFac = 5e6;
const powerLinearFac = 1e6;
const discount = Math.pow(respect, 0.01) + respect / respectLinearFac + Math.pow(power, 0.01) + power / powerLinearFac - 1;
return Math.max(1, discount);
}
// Returns only valid tasks for this gang. Excludes 'Unassigned'
Gang.prototype.getAllTaskNames = function() {
let tasks = [];
const allTasks = Object.keys(GangMemberTasks);
if (this.isHackingGang) {
tasks = allTasks.filter((e) => {
let task = GangMemberTasks[e];
if (task == null) { return false; }
if (e === "Unassigned") { return false; }
return task.isHacking;
});
} else {
tasks = allTasks.filter((e) => {
let task = GangMemberTasks[e];
if (task == null) { return false; }
if (e === "Unassigned") { return false; }
return task.isCombat;
});
}
return tasks;
}
Gang.prototype.getAllUpgradeNames = function() {
return Object.keys(GangMemberUpgrades);
}
Gang.prototype.getUpgradeCost = function(upgName) {
if (GangMemberUpgrades[upgName] == null) { return Infinity; }
return GangMemberUpgrades[upgName].getCost(this);
}
// Returns a player-friendly string stating the type of the specified upgrade
Gang.prototype.getUpgradeType = function(upgName) {
const upg = GangMemberUpgrades[upgName];
if (upg == null) { return ""; }
switch (upg.type) {
case "w":
return "Weapon";
case "a":
return "Armor";
case "v":
return "Vehicle";
case "r":
return "Rootkit";
case "g":
return "Augmentation";
default:
return "";
}
}
Gang.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Gang", this);
}
Gang.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Gang, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Gang = Gang;
function GangMember(name) {
this.name = name;
this.task = "Unassigned";
this.earnedRespect = 0;
this.hack = 1;
this.str = 1;
this.def = 1;
this.dex = 1;
this.agi = 1;
this.cha = 1;
this.hack_exp = 0;
this.str_exp = 0;
this.def_exp = 0;
this.dex_exp = 0;
this.agi_exp = 0;
this.cha_exp = 0;
this.hack_mult = 1;
this.str_mult = 1;
this.def_mult = 1;
this.dex_mult = 1;
this.agi_mult = 1;
this.cha_mult = 1;
this.hack_asc_mult = 1;
this.str_asc_mult = 1;
this.def_asc_mult = 1;
this.dex_asc_mult = 1;
this.agi_asc_mult = 1;
this.cha_asc_mult = 1;
this.upgrades = []; // Names of upgrades
this.augmentations = []; // Names of augmentations only
}
// 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);
}
GangMember.prototype.updateSkillLevels = function() {
this.hack = this.calculateSkill(this.hack_exp, this.hack_mult * this.hack_asc_mult);
this.str = this.calculateSkill(this.str_exp, this.str_mult * this.str_asc_mult);
this.def = this.calculateSkill(this.def_exp, this.def_mult * this.def_asc_mult);
this.dex = this.calculateSkill(this.dex_exp, this.dex_mult * this.dex_asc_mult);
this.agi = this.calculateSkill(this.agi_exp, this.agi_mult * this.agi_asc_mult);
this.cha = this.calculateSkill(this.cha_exp, this.cha_mult * this.cha_asc_mult);
}
GangMember.prototype.calculatePower = function() {
return (this.hack + this.str + this.def + this.dex + this.agi + this.cha) / 95;
}
GangMember.prototype.assignToTask = function(taskName) {
if (GangMemberTasks.hasOwnProperty(taskName)) {
this.task = taskName;
return true;
} else {
this.task = "Unassigned";
return false;
}
}
GangMember.prototype.unassignFromTask = function() {
this.task = "Unassigned";
}
GangMember.prototype.getTask = function() {
// Backwards compatibility
if (this.task instanceof GangMemberTask) {
this.task = this.task.name;
}
if (GangMemberTasks.hasOwnProperty(this.task)) {
return GangMemberTasks[this.task];
}
return GangMemberTasks["Unassigned"];
}
// Gains are per cycle
GangMember.prototype.calculateRespectGain = function(gang) {
const task = this.getTask();
if (task == null || !(task instanceof GangMemberTask) || task.baseRespect === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (4 * task.difficulty);
if (statWeight <= 0) { return 0; }
const territoryMult = Math.pow(AllGangs[gang.facName].territory * 100, task.territory.respect) / 100;
if (isNaN(territoryMult) || territoryMult <= 0) { return 0; }
var respectMult = gang.getWantedPenalty();
return 11 * task.baseRespect * statWeight * territoryMult * respectMult;
}
GangMember.prototype.calculateWantedLevelGain = function(gang) {
const task = this.getTask();
if (task == null || !(task instanceof GangMemberTask) || task.baseWanted === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (3.5 * task.difficulty);
if (statWeight <= 0) { return 0; }
const territoryMult = Math.pow(AllGangs[gang.facName].territory * 100, task.territory.wanted) / 100;
if (isNaN(territoryMult) || territoryMult <= 0) { return 0; }
if (task.baseWanted < 0) {
return 0.5 * task.baseWanted * statWeight * territoryMult;
} else {
return 7 * task.baseWanted / (Math.pow(3 * statWeight * territoryMult, 0.8));
}
}
GangMember.prototype.calculateMoneyGain = function(gang) {
const task = this.getTask();
if (task == null || !(task instanceof GangMemberTask) || task.baseMoney === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (3.2 * task.difficulty);
if (statWeight <= 0) { return 0; }
const territoryMult = Math.pow(AllGangs[gang.facName].territory * 100, task.territory.money) / 100;
if (isNaN(territoryMult) || territoryMult <= 0) { return 0; }
var respectMult = gang.getWantedPenalty();
return 5 * task.baseMoney * statWeight * territoryMult * respectMult;
}
GangMember.prototype.gainExperience = function(numCycles=1) {
const task = this.getTask();
if (task == null || !(task instanceof GangMemberTask) || task === GangMemberTasks["Unassigned"]) {return;}
const difficultyMult = Math.pow(task.difficulty, 0.9);
const difficultyPerCycles = difficultyMult * numCycles;
const weightDivisor = 1500;
this.hack_exp += (task.hackWeight / weightDivisor) * difficultyPerCycles;
this.str_exp += (task.strWeight / weightDivisor) * difficultyPerCycles;
this.def_exp += (task.defWeight / weightDivisor) * difficultyPerCycles;
this.dex_exp += (task.dexWeight / weightDivisor) * difficultyPerCycles;
this.agi_exp += (task.agiWeight / weightDivisor) * difficultyPerCycles;
this.cha_exp += (task.chaWeight / weightDivisor) * difficultyPerCycles;
}
GangMember.prototype.recordEarnedRespect = function(numCycles=1, gang) {
this.earnedRespect += (this.calculateRespectGain(gang) * numCycles);
}
GangMember.prototype.ascend = function() {
const res = this.getAscensionResults();
const hackAscMult = res.hack;
const strAscMult = res.str;
const defAscMult = res.def;
const dexAscMult = res.dex;
const agiAscMult = res.agi;
const chaAscMult = res.cha;
this.hack_asc_mult += hackAscMult;
this.str_asc_mult += strAscMult;
this.def_asc_mult += defAscMult;
this.dex_asc_mult += dexAscMult;
this.agi_asc_mult += agiAscMult;
this.cha_asc_mult += chaAscMult;
// Remove upgrades. Then re-calculate multipliers and stats
this.upgrades.length = 0;
this.hack_mult = 1;
this.str_mult = 1;
this.def_mult = 1;
this.dex_mult = 1;
this.agi_mult = 1;
this.cha_mult = 1;
for (let i = 0; i < this.augmentations.length; ++i) {
let aug = GangMemberUpgrades[this.augmentations[i]];
aug.apply(this);
}
// Clear exp and recalculate stats
this.hack_exp = 0;
this.str_exp = 0;
this.def_exp = 0;
this.dex_exp = 0;
this.agi_exp = 0;
this.cha_exp = 0;
this.updateSkillLevels();
const respectToDeduct = this.earnedRespect;
this.earnedRespect = 0;
return {
respect: respectToDeduct,
hack: hackAscMult,
str: strAscMult,
def: defAscMult,
dex: dexAscMult,
agi: agiAscMult,
cha: chaAscMult,
};
}
// 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
*/
let hack = 1;
let str = 1;
let def = 1;
let dex = 1;
let agi = 1;
let cha = 1;
for (let i = 0; i < this.upgrades.length; ++i) {
let upg = GangMemberUpgrades[this.upgrades[i]];
if (upg.mults.hack != null) { hack *= upg.mults.hack; }
if (upg.mults.str != null) { str *= upg.mults.str; }
if (upg.mults.def != null) { def *= upg.mults.def; }
if (upg.mults.dex != null) { dex *= upg.mults.dex; }
if (upg.mults.agi != null) { agi *= upg.mults.agi; }
if (upg.mults.cha != null) { cha *= upg.mults.cha; }
}
// Subtract 1 because we're only interested in the actual "bonus" part
return {
hack: (Math.max(0, hack - 1) * AscensionMultiplierRatio),
str: (Math.max(0, str - 1) * AscensionMultiplierRatio),
def: (Math.max(0, def - 1) * AscensionMultiplierRatio),
dex: (Math.max(0, dex - 1) * AscensionMultiplierRatio),
agi: (Math.max(0, agi - 1) * AscensionMultiplierRatio),
cha: (Math.max(0, cha - 1) * AscensionMultiplierRatio),
}
}
GangMember.prototype.buyUpgrade = function(upg, player, gang) {
if (typeof upg === 'string') {
upg = GangMemberUpgrades[upg];
}
if (!(upg instanceof GangMemberUpgrade)) {
return false;
}
// Prevent purchasing of already-owned upgrades
if (this.augmentations.includes(upg.name) || this.upgrades.includes(upg.name)) {
return false;
}
if (player.money.lt(upg.getCost(gang))) { return false; }
player.loseMoney(upg.getCost(gang));
if (upg.type === "g") {
this.augmentations.push(upg.name);
} else {
this.upgrades.push(upg.name);
}
upg.apply(this);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_6__["Page"].Gang) && UIElems.gangMemberUpgradeBoxOpened) {
var initFilterValue = UIElems.gangMemberUpgradeBoxFilter.value.toString();
gang.createGangMemberUpgradeBox(player, initFilterValue);
}
return true;
}
GangMember.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("GangMember", this);
}
GangMember.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(GangMember, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.GangMember = GangMember;
// 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,
dexWeight: 0, agiWeight: 0, chaWeight: 0,
difficulty: 0}) {
this.name = name;
this.desc = desc;
// Flags that describe whether this Task is applicable for Hacking/Combat gangs
this.isHacking = isHacking;
this.isCombat = isCombat;
// Base gain rates for respect/wanted/money
this.baseRespect = params.baseRespect ? params.baseRespect : 0;
this.baseWanted = params.baseWanted ? params.baseWanted : 0;
this.baseMoney = params.baseMoney ? params.baseMoney : 0;
// Weighting for the effect that each stat has on the tasks effectiveness.
// Weights must add up to 100
this.hackWeight = params.hackWeight ? params.hackWeight : 0;
this.strWeight = params.strWeight ? params.strWeight : 0;
this.defWeight = params.defWeight ? params.defWeight : 0;
this.dexWeight = params.dexWeight ? params.dexWeight : 0;
this.agiWeight = params.agiWeight ? params.agiWeight : 0;
this.chaWeight = params.chaWeight ? params.chaWeight : 0;
if (Math.round(this.hackWeight + this.strWeight + this.defWeight + this.dexWeight + this.agiWeight + this.chaWeight) != 100) {
console.error(`GangMemberTask ${this.name} weights do not add up to 100`);
}
// 1 - 100
this.difficulty = params.difficulty ? params.difficulty : 1;
// Territory Factors. Exponential factors that dictate how territory affects gains
// Formula: Territory Mutiplier = (Territory * 100) ^ factor / 100
// So factor should be > 1 if something should scale exponentially with territory
// and should be < 1 if it should have diminshing returns
this.territory = params.territory ? params.territory : {money: 1, respect: 1, wanted: 1};
}
GangMemberTask.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("GangMemberTask", this);
}
GangMemberTask.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(GangMemberTask, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.GangMemberTask = GangMemberTask;
const GangMemberTasks = {};
function addGangMemberTask(name, desc, isHacking, isCombat, params) {
GangMemberTasks[name] = new GangMemberTask(name, desc, isHacking, isCombat, params);
}
_data_gangmembertasks__WEBPACK_IMPORTED_MODULE_0__["gangMemberTasksMetadata"].forEach((e) => {
addGangMemberTask(e.name, e.desc, e.isHacking, e.isCombat, e.params);
});
function GangMemberUpgrade(name="", cost=0, type="w", mults={}) {
this.name = name;
this.cost = cost;
this.type = type; //w = weapon, a = armor, v = vehicle, r = rootkit, g = Aug
this.mults = mults;
this.createDescription();
}
GangMemberUpgrade.prototype.getCost = function(gang) {
const discount = gang.getDiscount();
return this.cost / discount;
}
GangMemberUpgrade.prototype.createDescription = function() {
const lines = ["Increases:"];
if (this.mults.str != null) {
lines.push(`* Strength by ${Math.round((this.mults.str - 1) * 100)}%`);
}
if (this.mults.def != null) {
lines.push(`* Defense by ${Math.round((this.mults.def - 1) * 100)}%`);
}
if (this.mults.dex != null) {
lines.push(`* Dexterity by ${Math.round((this.mults.dex - 1) * 100)}%`);
}
if (this.mults.agi != null) {
lines.push(`* Agility by ${Math.round((this.mults.agi - 1) * 100)}%`);
}
if (this.mults.cha != null) {
lines.push(`* Charisma by ${Math.round((this.mults.cha - 1) * 100)}%`);
}
if (this.mults.hack != null) {
lines.push(`* Hacking by ${Math.round((this.mults.hack - 1) * 100)}%`);
}
this.desc = lines.join(" ");
}
// 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; }
if (this.mults.dex != null) { member.dex_mult *= this.mults.dex; }
if (this.mults.agi != null) { member.agi_mult *= this.mults.agi; }
if (this.mults.cha != null) { member.cha_mult *= this.mults.cha; }
if (this.mults.hack != null) { member.hack_mult *= this.mults.hack; }
return;
}
GangMemberUpgrade.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("GangMemberUpgrade", this);
}
GangMemberUpgrade.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(GangMemberUpgrade, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.GangMemberUpgrade = GangMemberUpgrade;
// Initialize Gang Member Upgrades
const GangMemberUpgrades = {}
function addGangMemberUpgrade(name, cost, type, mults) {
GangMemberUpgrades[name] = new GangMemberUpgrade(name, cost, type, mults);
}
_data_gangmemberupgrades__WEBPACK_IMPORTED_MODULE_1__["gangMemberUpgradesMetadata"].forEach((e) => {
addGangMemberUpgrade(e.name, e.cost, e.upgType, e.mults);
});
// Create a pop-up box that lets player purchase upgrades
Gang.prototype.createGangMemberUpgradeBox = function(player, initialFilter="") {
const boxId = "gang-member-upgrade-popup-box";
if (UIElems.gangMemberUpgradeBoxOpened) {
// 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;
}
for (var i = 2; i < UIElems.gangMemberUpgradeBoxElements.length; ++i) {
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18__["removeElement"])(UIElems.gangMemberUpgradeBoxElements[i]);
}
UIElems.gangMemberUpgradeBoxElements = [UIElems.gangMemberUpgradeBoxFilter, UIElems.gangMemberUpgradeBoxDiscount];
var filter = UIElems.gangMemberUpgradeBoxFilter.value.toString();
for (var i = 0; i < this.members.length; ++i) {
if (this.members[i].name.indexOf(filter) > -1 || this.members[i].task.indexOf(filter) > -1) {
var newPanel = this.members[i].createGangMemberUpgradePanel(this, player);
UIElems.gangMemberUpgradeBoxContent.appendChild(newPanel);
UIElems.gangMemberUpgradeBoxElements.push(newPanel);
}
}
} else {
// New popup
UIElems.gangMemberUpgradeBoxFilter = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
type:"text", placeholder:"Filter gang members",
value:initialFilter,
onkeyup:()=>{
var filterValue = UIElems.gangMemberUpgradeBoxFilter.value.toString();
this.createGangMemberUpgradeBox(player, filterValue);
}
});
UIElems.gangMemberUpgradeBoxDiscount = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText: "Discount: -" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(1 - 1 / this.getDiscount(), "0.00%"),
marginLeft: "6px",
tooltip: "You get a discount on equipment and upgrades based on your gang's " +
"respect and power. More respect and power leads to more discounts."
});
UIElems.gangMemberUpgradeBoxElements = [UIElems.gangMemberUpgradeBoxFilter, UIElems.gangMemberUpgradeBoxDiscount];
var filter = UIElems.gangMemberUpgradeBoxFilter.value.toString();
for (var i = 0; i < this.members.length; ++i) {
if (this.members[i].name.indexOf(filter) > -1 || this.members[i].task.indexOf(filter) > -1) {
UIElems.gangMemberUpgradeBoxElements.push(this.members[i].createGangMemberUpgradePanel(this, player));
}
}
UIElems.gangMemberUpgradeBox = Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16__["createPopup"])(boxId, UIElems.gangMemberUpgradeBoxElements);
UIElems.gangMemberUpgradeBoxContent = document.getElementById(boxId + "-content");
UIElems.gangMemberUpgradeBoxOpened = true;
}
}
// Create upgrade panels for each individual Gang Member
GangMember.prototype.createGangMemberUpgradePanel = function(gangObj, player) {
var container = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
border:"1px solid white",
});
var header = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h1", {
innerText: this.name + " (" + this.task + ")"
});
container.appendChild(header);
var text = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
fontSize:"14px", display: "inline-block", width:"20%",
innerText:
"Hack: " + this.hack + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.hack_mult * this.hack_asc_mult, 2) + ")\n" +
"Str: " + this.str + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.str_mult * this.str_asc_mult, 2) + ")\n" +
"Def: " + this.def + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.def_mult * this.def_asc_mult, 2) + ")\n" +
"Dex: " + this.dex + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.dex_mult * this.dex_asc_mult, 2) + ")\n" +
"Agi: " + this.agi + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.agi_mult * this.agi_asc_mult, 2) + ")\n" +
"Cha: " + this.cha + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.cha_mult * this.cha_asc_mult, 2) + ")\n",
});
// Already purchased upgrades
const ownedUpgradesElements = [];
function pushOwnedUpgrade(upgName) {
const upg = GangMemberUpgrades[upgName];
if (upg == null) {
console.error(`Could not find GangMemberUpgrade object for name ${upgName}`);
return;
}
ownedUpgradesElements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class: "gang-owned-upgrade",
innerText: upgName,
tooltip: upg.desc,
}));
}
for (const upgName of this.upgrades) { pushOwnedUpgrade(upgName); }
for (const upgName of this.augmentations) { pushOwnedUpgrade(upgName); }
var ownedUpgrades = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class: "gang-owned-upgrades-div",
innerText: "Purchased Upgrades:",
});
for (const elem of ownedUpgradesElements) { ownedUpgrades.appendChild(elem); }
container.appendChild(text);
container.appendChild(ownedUpgrades);
container.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br", {}));
// Upgrade buttons. Only show upgrades that can be afforded
const weaponUpgrades = [];
const armorUpgrades = [];
const vehicleUpgrades = [];
const rootkitUpgrades = [];
const augUpgrades = [];
for (let upgName in GangMemberUpgrades) {
if (GangMemberUpgrades.hasOwnProperty(upgName)) {
let upg = GangMemberUpgrades[upgName];
if (player.money.lt(upg.getCost(gangObj))) { continue; }
if (this.upgrades.includes(upgName) || this.augmentations.includes(upgName)) { continue; }
switch (upg.type) {
case "w":
weaponUpgrades.push(upg);
break;
case "a":
armorUpgrades.push(upg);
break;
case "v":
vehicleUpgrades.push(upg);
break;
case "r":
rootkitUpgrades.push(upg);
break;
case "g":
augUpgrades.push(upg);
break;
default:
console.error(`ERROR: Invalid Gang Member Upgrade Type: ${upg.type}`);
}
}
}
// Create separate columns for each upgrade type
const weaponDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {width: "20%", display: "inline-block"});
const armorDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {width: "20%", display: "inline-block"});
const vehicleDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {width: "20%", display: "inline-block"});
const rootkitDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {width: "20%", display: "inline-block"});
const augDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {width: "20%", display: "inline-block"});
// Add a title/labe for each column
weaponDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h2", {innerText: "Weapons"}));
armorDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h2", {innerText: "Armor"}));
vehicleDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h2", {innerText: "Vehicles"}));
rootkitDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h2", {innerText: "Rootkits"}));
augDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h2", {innerText: "Augmentations"}));
// Add buttons to purchase each upgrade
const upgrades = [weaponUpgrades, armorUpgrades, vehicleUpgrades, rootkitUpgrades, augUpgrades];
const divs = [weaponDiv, armorDiv, vehicleDiv, rootkitDiv, augDiv];
for (let i = 0; i < upgrades.length; ++i) {
let upgradeArray = upgrades[i];
let div = divs[i];
for (let j = 0; j < upgradeArray.length; ++j) {
let upg = upgradeArray[j];
(function (upg, div, memberObj, i, gang) {
let createElementParams = {
innerText: upg.name + " - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(upg.getCost(gang), "$0.000a"),
class: "a-link-button", margin:"2px", padding:"2px", display:"block",
fontSize:"11px",
clickListener:()=>{
memberObj.buyUpgrade(upg, player, gangObj);
return false;
}
}
// For the last two divs, tooltip should be on the left
if (i >= 3) {
createElementParams.tooltipleft = upg.desc;
} else {
createElementParams.tooltip = upg.desc;
}
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", createElementParams));
})(upg, div, this, i, gangObj);
}
}
container.appendChild(weaponDiv);
container.appendChild(armorDiv);
container.appendChild(vehicleDiv);
container.appendChild(rootkitDiv);
container.appendChild(augDiv);
return container;
}
// Gang UI Dom Elements
const UIElems = {
// Main elems
gangContentCreated: false,
gangContainer: null,
managementButton: null,
territoryButton: null,
// Subpages
gangManagementSubpage: null,
gangTerritorySubpage: null,
// Gang Management Subpage Elements
gangDesc: null,
gangInfo: null,
gangRecruitMemberButton: null,
gangRecruitRequirementText: null,
gangExpandAllButton: null,
gangCollapseAllButton: null,
gangMemberFilter: null,
gangManageEquipmentButton: null,
gangMemberList: null,
gangMemberPanels: {},
// Gang Equipment Upgrade Elements
gangMemberUpgradeBoxOpened: false,
gangMemberUpgradeBox: null,
gangMemberUpgradeBoxContent: null,
gangMemberUpgradeBoxFilter: null,
gangMemberUpgradeBoxDiscount: null,
gangMemberUpgradeBoxElements: null,
// Gang Territory Elements
gangTerritoryDescText: null,
gangTerritoryWarfareCheckbox: null,
gangTerritoryWarfareCheckboxLabel: null,
gangTerritoryWarfareClashChance: null,
gangTerritoryDeathNotifyCheckbox: null,
gangTerritoryDeathNotifyCheckboxLabel: null,
gangTerritoryInfoText: null,
}
Gang.prototype.displayGangContent = function(player) {
if (!UIElems.gangContentCreated || UIElems.gangContainer == null) {
UIElems.gangContentCreated = true;
// Create gang container
UIElems.gangContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"gang-container", class:"generic-menupage-container",
});
// Get variables
var facName = this.facName,
members = this.members,
wanted = this.wanted,
respect = this.respect;
// Back button
UIElems.gangContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Back",
clickListener:()=>{
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_5__["displayFactionContent"])(facName);
return false;
}
}));
// Buttons to switch between panels
UIElems.managementButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
id:"gang-management-subpage-button", class:"a-link-button-inactive",
display:"inline-block", innerHTML: "Gang Management (Alt+1)",
clickListener:()=>{
UIElems.gangManagementSubpage.style.display = "block";
UIElems.gangTerritorySubpage.style.display = "none";
UIElems.managementButton.classList.toggle("a-link-button-inactive");
UIElems.managementButton.classList.toggle("a-link-button");
UIElems.territoryButton.classList.toggle("a-link-button-inactive");
UIElems.territoryButton.classList.toggle("a-link-button");
this.updateGangContent();
return false;
}
})
UIElems.territoryButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
id:"gang-territory-subpage-button", class:"a-link-button",
display:"inline-block", innerHTML:"Gang Territory (Alt+2)",
clickListener:() => {
UIElems.gangManagementSubpage.style.display = "none";
UIElems.gangTerritorySubpage.style.display = "block";
UIElems.managementButton.classList.toggle("a-link-button-inactive");
UIElems.managementButton.classList.toggle("a-link-button");
UIElems.territoryButton.classList.toggle("a-link-button-inactive");
UIElems.territoryButton.classList.toggle("a-link-button");
this.updateGangContent();
return false;
}
});
UIElems.gangContainer.appendChild(UIElems.managementButton);
UIElems.gangContainer.appendChild(UIElems.territoryButton);
// Subpage for managing gang members
UIElems.gangManagementSubpage = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
display:"block", id:"gang-management-subpage",
});
var lowerWantedTask = "";
if (this.isHackingGang) {
lowerWantedTask = "Ethical Hacking";
} else {
lowerWantedTask = "Vigilante Justice";
}
UIElems.gangDesc = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {width:"70%",
innerHTML:
"This page is used to manage your gang members and get an overview of your " +
"gang's stats.
" +
"If a gang member is not earning much money or respect, the task that you " +
"have assigned to that member might be too difficult. Consider training that " +
"member's stats or choosing an easier task. The tasks closer to the " +
"top of the dropdown list are generally easier. Alternatively, the gang member's " +
"low production might be due to the fact that your wanted level is too high. " +
"Consider assigning a few members to the '" + lowerWantedTask + "' " +
"task to lower your wanted level.
" +
"Installing Augmentations does NOT reset your progress with your Gang. " +
"Furthermore, after installing Augmentations, you will " +
"automatically be a member of whatever Faction you created your gang with.
" +
"You can also manage your gang programmatically through Netscript using the Gang API"
});
UIElems.gangManagementSubpage.appendChild(UIElems.gangDesc);
UIElems.gangInfo = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {id:"gang-info", width:"70%"});
UIElems.gangManagementSubpage.appendChild(UIElems.gangInfo);
UIElems.gangRecruitMemberButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
id: "gang-management-recruit-member-btn", class:"a-link-button-inactive",
innerHTML:"Recruit Gang Member", display:"inline-block", margin:"10px",
clickListener:()=>{
const popupId = "recruit-gang-member-popup";
let yesBtn;
const txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Please enter a name for your new Gang member:",
});
const br = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br");
const nameInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
onkeyup: (e) => {
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__["KEY"].ENTER) { yesBtn.click(); }
},
placeholder: "Name must be unique",
type: "text",
});
yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class: "std-button",
clickListener: () => {
let name = nameInput.value;
if (name === "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You must enter a name for your Gang member!");
return false;
}
if (!this.canRecruitMember()) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You cannot recruit another Gang member!");
return false;
}
// At this point, the only way this can fail is if you already
// have a gang member with the same name
if (!this.recruitMember(name)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You already have a gang member with this name!");
return false;
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__["removeElementById"])(popupId);
return false;
},
innerText: "Recruit Gang Member",
});
const noBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class: "std-button",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__["removeElementById"])(popupId);
return false;
},
innerText: "Cancel",
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16__["createPopup"])(popupId, [txt, br, nameInput, yesBtn, noBtn]);
nameInput.focus();
}
});
UIElems.gangManagementSubpage.appendChild(UIElems.gangRecruitMemberButton);
// Text for how much reputation is required for recruiting next memberList
UIElems.gangRecruitRequirementText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
color:"red",
id: "gang-recruit-requirement-text",
margin: "10px",
});
UIElems.gangManagementSubpage.appendChild(UIElems.gangRecruitRequirementText);
// Gang Member List management buttons (Expand/Collapse All, select a single member)
UIElems.gangManagementSubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br", {}));
UIElems.gangExpandAllButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerHTML:"Expand All",
clickListener:()=>{
var allHeaders = UIElems.gangManagementSubpage.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
var hdr = allHeaders[i];
if (!hdr.classList.contains("active")) {
hdr.click();
}
}
return false;
}
});
UIElems.gangCollapseAllButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerHTML:"Collapse All",
clickListener:()=>{
var allHeaders = UIElems.gangManagementSubpage.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
var hdr = allHeaders[i];
if (hdr.classList.contains("active")) {
hdr.click();
}
}
return false;
}
});
UIElems.gangMemberFilter = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
type:"text", placeholder:"Filter gang members", margin:"5px", padding:"5px",
onkeyup:()=>{
this.displayGangMemberList();
}
});
UIElems.gangManageEquipmentButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerHTML:"Manage Equipment",
clickListener: () => {
this.createGangMemberUpgradeBox(player);
}
});
UIElems.gangManagementSubpage.appendChild(UIElems.gangExpandAllButton);
UIElems.gangManagementSubpage.appendChild(UIElems.gangCollapseAllButton);
UIElems.gangManagementSubpage.appendChild(UIElems.gangMemberFilter);
UIElems.gangManagementSubpage.appendChild(UIElems.gangManageEquipmentButton);
// Gang Member list
UIElems.gangMemberList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("ul", {id:"gang-member-list"});
this.displayGangMemberList();
UIElems.gangManagementSubpage.appendChild(UIElems.gangMemberList);
// Subpage for seeing gang territory information
UIElems.gangTerritorySubpage = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"gang-territory-subpage", display:"none"
});
// Info text for territory page
UIElems.gangTerritoryDescText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
width:"70%",
innerHTML:
"This page shows how much territory your Gang controls. This statistic is listed as a percentage, " +
"which represents how much of the total territory you control.
" +
"Every ~20 seconds, your gang has a chance to 'clash' with other gangs. Your chance " +
"to win a clash depends on your gang's power, which is listed in the display below. " +
"Your gang's power slowly accumulates over time. The accumulation rate is determined by the stats " +
"of all Gang members you have assigned to the 'Territory Warfare' task. Gang members that are not " +
"assigned to this task do not contribute to your gang's power. Your gang also loses a small amount " +
"of power whenever you lose a clash
" +
"NOTE: Gang members assigned to 'Territory Warfare' can be killed during clashes. This can happen regardless of whether you win " +
"or lose the clash. A gang member being killed results in both respect and power loss for your gang.
" +
"The amount of territory you have affects all aspects of your Gang members' production, including " +
"money, respect, and wanted level. It is very beneficial to have high territory control.
"
});
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryDescText);
// Checkbox for Engaging in Territory Warfare
UIElems.gangTerritoryWarfareCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
display: "inline-block",
id: "gang-management-territory-warfare-checkbox",
changeListener: () => {
this.territoryWarfareEngaged = UIElems.gangTerritoryWarfareCheckbox.checked;
},
margin: "2px",
type: "checkbox",
});
UIElems.gangTerritoryWarfareCheckbox.checked = this.territoryWarfareEngaged;
UIElems.gangTerritoryWarfareCheckboxLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("label", {
color: "white",
display: "inline-block",
for: "gang-management-territory-warfare-checkbox",
innerText: "Engage in Territory Warfare",
tooltip: "Engaging in Territory Warfare sets your clash chance to 100%. " +
"Disengaging will cause your clash chance to gradually decrease until " +
"it reaches 0%",
});
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryWarfareCheckbox);
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryWarfareCheckboxLabel);
// Territory Clash chance
UIElems.gangTerritorySubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
UIElems.gangTerritoryWarfareClashChance = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {display: "inline-block"});
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryWarfareClashChance);
UIElems.gangTerritorySubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class: "help-tip",
display: "inline-block",
innerText: "?",
clickListener: () => {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("This percentage represents the chance you have of 'clashing' with " +
"with another gang. If you do not wish to gain/lose territory, " +
"then keep this percentage at 0% by not engaging in territory " +
"warfare.")
},
}));
// Checkbox for whether player wants to be notified of gang member death
UIElems.gangTerritoryDeathNotifyCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
display: "inline-block",
id: "gang-management-notify-member-death-checkbox",
changeListener: () => {
this.notifyMemberDeath = UIElems.gangTerritoryDeathNotifyCheckbox.checked;
},
margin: "2px",
type: "checkbox",
});
UIElems.gangTerritoryDeathNotifyCheckbox.checked = this.notifyMemberDeath;
UIElems.gangTerritoryDeathNotifyCheckboxLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("label", {
color: "white",
display: "inline-block",
for: "gang-management-notify-member-death-checkbox",
innerText: "Notify about Gang Member Deaths",
tooltip: "If this is enabled, then you will receive a pop-up notifying you " +
"whenever one of your Gang Members dies in a territory clash.",
});
UIElems.gangTerritorySubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryDeathNotifyCheckbox);
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryDeathNotifyCheckboxLabel);
// Territory info (percentages of territory owned for each gang)
UIElems.gangTerritorySubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
var territoryBorder = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("fieldset", {
display:"block",
margin: "6px",
width:"50%",
});
UIElems.gangTerritoryInfoText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p");
territoryBorder.appendChild(UIElems.gangTerritoryInfoText);
UIElems.gangTerritorySubpage.appendChild(territoryBorder);
UIElems.gangContainer.appendChild(UIElems.gangTerritorySubpage);
UIElems.gangContainer.appendChild(UIElems.gangManagementSubpage);
document.getElementById("entire-game-container").appendChild(UIElems.gangContainer);
}
UIElems.gangContainer.style.display = "block";
this.updateGangContent();
}
Gang.prototype.displayGangMemberList = function() {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17__["removeChildrenFromElement"])(UIElems.gangMemberList);
UIElems.gangMemberPanels = {};
const members = this.members;
const filter = UIElems.gangMemberFilter.value.toString();
for (var i = 0; i < members.length; ++i) {
if (members[i].name.indexOf(filter) > -1 || members[i].task.indexOf(filter) > -1) {
this.createGangMemberDisplayElement(members[i]);
}
}
}
Gang.prototype.updateGangContent = function() {
if (!UIElems.gangContentCreated) { return; }
if (UIElems.gangMemberUpgradeBoxOpened) {
UIElems.gangMemberUpgradeBoxDiscount.childNodes[0].nodeValue =
"Discount: -" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(1 - 1 / this.getDiscount(), "0.00%");
}
if (UIElems.gangTerritorySubpage.style.display === "block") {
// Territory Warfare Clash Chance
UIElems.gangTerritoryWarfareClashChance.innerText =
`Territory Clash Chance: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(this.territoryClashChance, '0.000%')}`;
// Engaged in Territory Warfare checkbox
UIElems.gangTerritoryWarfareCheckbox.checked = this.territoryWarfareEngaged;
// Update territory information
UIElems.gangTerritoryInfoText.innerHTML = "";
const playerPower = AllGangs[this.facName].power;
for (const gangname in AllGangs) {
if (AllGangs.hasOwnProperty(gangname)) {
const gangTerritoryInfo = AllGangs[gangname];
let territory = gangTerritoryInfo.territory * 100;
//Fix some rounding issues graphically
let displayNumber;
if (territory <= 0) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(0, 2);
} else if (territory >= 100) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(100, 2);
} else {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(territory, 2);
}
if (gangname === this.facName) {
let newHTML = `${gangname} Power: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gangTerritoryInfo.power, 6)} `;
newHTML += `Territory: ${displayNumber}%
`;
UIElems.gangTerritoryInfoText.innerHTML += newHTML;
} else {
const clashVictoryChance = playerPower / (gangTerritoryInfo.power + playerPower);
let newHTML = `${gangname} Power: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gangTerritoryInfo.power, 6)} `;
newHTML += `Territory: ${displayNumber}% `;
newHTML += `Chance to win clash with this gang: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(clashVictoryChance, "0.000%")}
`;
UIElems.gangTerritoryInfoText.innerHTML += newHTML;
}
}
}
} else {
// Update information for overall gang
if (UIElems.gangInfo instanceof Element) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_4__["Factions"][this.facName];
var rep;
if (!(faction instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_3__["Faction"])) {
rep = "ERROR";
} else {
rep = faction.playerReputation;
}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17__["removeChildrenFromElement"])(UIElems.gangInfo);
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Respect
display: "inline-block",
innerText: "Respect: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.respect, 6) +
" (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(5*this.respectGainRate, 6) + " / sec)",
tooltip: "Represents the amount of respect your gang has from other gangs and criminal " +
"organizations. Your respect affects the amount of money " +
"your gang members will earn, and also determines how much " +
"reputation you are earning with your gang's corresponding Faction."
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Wanted level
display: "inline-block",
innerText: "Wanted Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(this.wanted, 6) +
" (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(5*this.wantedGainRate, 6) + " / sec)",
tooltip: "Represents how much the gang is wanted by law enforcement. The higher " +
"your gang's wanted level, the harder it will be for your gang members " +
"to make money and earn respect. Note that the minimum wanted level is 1."
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
var wantedPenalty = this.getWantedPenalty();
wantedPenalty = (1 - wantedPenalty) * 100;
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Wanted Level multiplier
display: "inline-block",
innerText: `Wanted Level Penalty: -${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(wantedPenalty, 2)}%`,
tooltip: "Penalty for respect and money gain rates due to Wanted Level"
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Money gain rate
display: "inline-block",
innerText: `Money gain rate: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(5 * this.moneyGainRate, "$0.000a")} / sec`,
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
// Fix some rounding issues graphically
var territoryMult = AllGangs[this.facName].territory * 100;
let displayNumber;
if (territoryMult <= 0) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(0, 2);
} else if (territoryMult >= 100) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(100, 2);
} else {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(territoryMult, 2);
}
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Territory multiplier
display: "inline-block",
innerText: `Territory: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(displayNumber, 3)}%`,
tooltip: "The percentage of total territory your Gang controls"
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Faction reputation
display:"inline-block",
innerText:"Faction reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(rep, 3)
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
const CyclesPerSecond = 1000 / _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed;
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { // Stored Cycles
innerText: `Bonus time(s): ${this.storedCycles / CyclesPerSecond}`,
display: "inline-block",
tooltip: "You gain bonus time while offline or when the game is inactive (e.g. when the tab is throttled by the browser). " +
"Bonus time makes the Gang mechanic progress faster, up to 5x the normal speed",
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
} else {
console.error("gang-info DOM element DNE");
}
// Toggle the 'Recruit member button' if valid
const numMembers = this.members.length;
const respectCost = this.getRespectNeededToRecruitMember();
const btn = UIElems.gangRecruitMemberButton;
if (numMembers >= MaximumGangMembers) {
btn.className = "a-link-button-inactive";
UIElems.gangRecruitRequirementText.style.display = "inline-block";
UIElems.gangRecruitRequirementText.innerHTML = "You have reached the maximum amount of gang members";
} else if (this.canRecruitMember()) {
btn.className = "a-link-button";
UIElems.gangRecruitRequirementText.style.display = "none";
} else {
btn.className = "a-link-button-inactive";
UIElems.gangRecruitRequirementText.style.display = "inline-block";
UIElems.gangRecruitRequirementText.innerHTML = `${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(respectCost, 2)} respect needed to recruit next 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
Gang.prototype.createGangMemberDisplayElement = function(memberObj) {
if (!UIElems.gangContentCreated) { return; }
const name = memberObj.name;
// Clear/Update the UIElems map to keep track of this gang member's panel
UIElems.gangMemberPanels[name] = {};
// Create the accordion
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_14__["createAccordionElement"])({
id: name + "gang-member",
hdrText: name,
});
const li = accordion[0];
const hdr = accordion[1];
const gangMemberDiv = accordion[2];
UIElems.gangMemberPanels[name]["panel"] = gangMemberDiv;
// Gang member content divided into 3 panels:
// Panel 1 - Shows member's stats & Ascension stuff
const statsDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class: "gang-member-info-div",
id: name + "gang-member-stats",
tooltipsmall: [`Hk: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_mult * memberObj.hack_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_asc_mult, "0,0.00")} Asc)`,
`St: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_mult * memberObj.str_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_asc_mult, "0,0.00")} Asc)`,
`Df: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_mult * memberObj.def_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_asc_mult, "0,0.00")} Asc)`,
`Dx: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_mult * memberObj.dex_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_asc_mult, "0,0.00")} Asc)`,
`Ag: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_mult * memberObj.agi_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_asc_mult, "0,0.00")} Asc)`,
`Ch: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_mult * memberObj.cha_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_asc_mult, "0,0.00")} Asc)`].join(" "),
});
UIElems.gangMemberPanels[name]["statsDiv"] = statsDiv;
const statsP = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
display: "inline",
id: name + "gang-member-stats-text",
});
const brElement = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br");
const ascendButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("button", {
class: "accordion-button",
innerText: "Ascend",
clickListener: () => {
const popupId = `gang-management-ascend-member ${memberObj.name}`;
const ascendBenefits = memberObj.getAscensionResults();
const txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
innerText: ["Are you sure you want to ascend this member? (S)he will lose all of",
"his non-Augmentation upgrades and his/her stats will reset back to 1.",
"",
`Furthermore, your gang will lose ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.earnedRespect, "0.000000")} respect`,
"",
"In return, (s)he will gain the following permanent boost to stat multipliers:\n",
`Hacking: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.hack, "0.00%")}`,
`Strength: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.str, "0.00%")}`,
`Defense: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.def, "0.00%")}`,
`Dexterity: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.dex, "0.00%")}`,
`Agility: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.agi, "0.00%")}`,
`Charisma: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(ascendBenefits.cha, "0.00%")}`].join("\n"),
});
const confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("button", {
class: "std-button",
clickListener: () => {
this.ascendMember(memberObj);
this.updateGangMemberDisplayElement(memberObj);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__["removeElementById"])(popupId);
return false;
},
innerText: "Ascend",
});
const cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("button", {
class: "std-button",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__["removeElementById"])(popupId);
return false;
},
innerText: "Cancel",
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_16__["createPopup"])(popupId, [txt, confirmBtn, cancelBtn]);
}
});
const ascendHelpTip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class: "help-tip",
clickListener: () => {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])(["Ascending a Gang Member resets the member's progress and stats in exchange",
"for a permanent boost to their stat multipliers.",
"
The additional stat multiplier that the Gang Member gains upon ascension",
"is based on the amount of multipliers the member has from non-Augmentation Equipment.",
"
Upon ascension, the member will lose all of its non-Augmentation Equipment and your",
"gang will lose respect equal to the total respect earned by the member."].join(" "));
},
innerText: "?",
marginTop: "5px",
});
statsDiv.appendChild(statsP);
statsDiv.appendChild(brElement);
statsDiv.appendChild(ascendButton);
statsDiv.appendChild(ascendHelpTip);
// Panel 2 - Task Selection & Info
const taskDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class:"gang-member-info-div",
id: name + "gang-member-task",
});
const taskSelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("select", {
class: "dropdown",
id: name + "gang-member-task-selector",
});
// Get an array of the name of all tasks that are applicable for this Gang
let tasks = this.getAllTaskNames();
tasks.unshift("---");
// Create selector for Gang member task
for (var i = 0; i < tasks.length; ++i) {
var option = document.createElement("option");
option.text = tasks[i];
taskSelector.add(option);
}
taskSelector.addEventListener("change", () => {
var task = taskSelector.options[taskSelector.selectedIndex].text;
memberObj.assignToTask(task);
this.setGangMemberTaskDescription(memberObj, task);
this.updateGangContent();
});
// Set initial task in selector
if (GangMemberTasks.hasOwnProperty(memberObj.task)) {
var taskName = memberObj.task;
var taskIndex = 0;
for (let i = 0; i < tasks.length; ++i) {
if (taskName === tasks[i]) {
taskIndex = i;
break;
}
}
taskSelector.selectedIndex = taskIndex;
}
var gainInfo = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {id:name + "gang-member-gain-info"});
taskDiv.appendChild(taskSelector);
taskDiv.appendChild(gainInfo);
// Panel for Description of task
var taskDescDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
class:"gang-member-info-div",
id: name + "gang-member-task-desc",
});
var taskDescP = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
display:"inline",
id: name + "gang-member-task-description",
});
taskDescDiv.appendChild(taskDescP);
gangMemberDiv.appendChild(statsDiv);
gangMemberDiv.appendChild(taskDiv);
gangMemberDiv.appendChild(taskDescDiv);
UIElems.gangMemberList.appendChild(li);
this.setGangMemberTaskDescription(memberObj, taskName); //Initialize description, TODO doesnt work rn
this.updateGangMemberDisplayElement(memberObj);
}
Gang.prototype.updateGangMemberDisplayElement = function(memberObj) {
if (!UIElems.gangContentCreated) { return; }
var name = memberObj.name;
// Update stats + exp
var stats = document.getElementById(name + "gang-member-stats-text");
if (stats) {
stats.innerText =
[`Hacking: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.hack, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_exp, '(0.00a)')} exp)`,
`Strength: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.str, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_exp, '(0.00a)')} exp)`,
`Defense: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.def, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_exp, '(0.00a)')} exp)`,
`Dexterity: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.dex, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_exp, '(0.00a)')} exp)`,
`Agility: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.agi, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_exp, '(0.00a)')} exp)`,
`Charisma: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.cha, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_exp, '(0.00a)')} exp)`].join("\n");
}
// Update tooltip for stat multipliers
const panel = UIElems.gangMemberPanels[name];
if (panel) {
const statsDiv = panel["statsDiv"];
if (statsDiv) {
statsDiv.firstChild.innerHTML =
[`Hk: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_mult * memberObj.hack_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.hack_asc_mult, "0,0.00")} Asc)`,
`St: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_mult * memberObj.str_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.str_asc_mult, "0,0.00")} Asc)`,
`Df: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_mult * memberObj.def_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.def_asc_mult, "0,0.00")} Asc)`,
`Dx: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_mult * memberObj.dex_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.dex_asc_mult, "0,0.00")} Asc)`,
`Ag: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_mult * memberObj.agi_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.agi_asc_mult, "0,0.00")} Asc)`,
`Ch: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_mult * memberObj.cha_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_7__["numeralWrapper"].format(memberObj.cha_asc_mult, "0,0.00")} Asc)`].join(" ");
}
}
// Update info about gang member's earnings/gains
var gainInfo = document.getElementById(name + "gang-member-gain-info");
if (gainInfo) {
gainInfo.innerHTML =
[`Money: $ ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(5*memberObj.calculateMoneyGain(this), 2)} / sec`,
`Respect: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(5*memberObj.calculateRespectGain(this), 6)} / sec`,
`Wanted Level: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(5*memberObj.calculateWantedLevelGain(this), 6)} / sec`,
`Total Respect Earned: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(memberObj.earnedRespect, 6)}`].join(" ");
}
// Update selector to have the correct task
const taskSelector = document.getElementById(name + "gang-member-task-selector");
if (taskSelector) {
let tasks = this.getAllTaskNames();
tasks.unshift("---");
if (GangMemberTasks.hasOwnProperty(memberObj.task)) {
const taskName = memberObj.task;
let taskIndex = 0;
for (let i = 0; i < tasks.length; ++i) {
if (taskName === tasks[i]) {
taskIndex = i;
break;
}
}
taskSelector.selectedIndex = taskIndex;
}
}
}
Gang.prototype.setGangMemberTaskDescription = function(memberObj, taskName) {
const name = memberObj.name;
const taskDesc = document.getElementById(name + "gang-member-task-description");
if (taskDesc) {
var task = GangMemberTasks[taskName];
if (task == null) { task = GangMemberTasks["Unassigned"]; }
var desc = task.desc;
taskDesc.innerHTML = desc;
}
}
Gang.prototype.clearUI = function() {
if (UIElems.gangContainer instanceof Element) { Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_18__["removeElement"])(UIElems.gangContainer); }
for (const prop in UIElems) {
UIElems[prop] = null;
}
UIElems.gangContentCreated = false;
UIElems.gangMemberUpgradeBoxOpened = false;
UIElems.gangMemberPanels = {};
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 70 */
/*!***************************************!*\
!*** ./src/Message/MessageHelpers.js ***!
\***************************************/
/*! exports provided: Messages, checkForMessagesToSend, sendMessage, showMessage, loadMessages, initMessages, Message */
/*! exports used: Messages, checkForMessagesToSend, initMessages, loadMessages, showMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Messages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkForMessagesToSend; });
/* unused harmony export sendMessage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return showMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initMessages; });
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Message */ 65);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Message__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_Augmentation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Augmentation/Augmentation */ 16);
/* harmony import */ var _Augmentation_Augmentation__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentation__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Augmentation/Augmentations */ 11);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Missions */ 74);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../RedPill */ 83);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
//Sends message to player, including a pop up
function sendMessage(msg, forced=false) {
msg.recvd = true;
if (forced || !_Settings_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].SuppressMessages) {
showMessage(msg);
}
addMessageToServer(msg, "home");
}
function showMessage(msg) {
var txt = "Message received from unknown sender:
" +
"" + msg.msg + "
" +
"This message was saved as " + msg.filename + " onto your home computer.";
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])(txt);
}
//Adds a message to a server
function addMessageToServer(msg, serverHostname) {
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_8__["GetServerByHostname"])(serverHostname);
if (server == null) {
console.warn(`Could not find server ${serverHostname}`);
return;
}
for (var i = 0; i < server.messages.length; ++i) {
if (server.messages[i].filename === msg.filename) {
return; //Already exists
}
}
server.messages.push(msg);
}
//Checks if any of the 'timed' messages should be sent
function checkForMessagesToSend() {
var jumper0 = Messages[MessageFilenames.Jumper0];
var jumper1 = Messages[MessageFilenames.Jumper1];
var jumper2 = Messages[MessageFilenames.Jumper2];
var jumper3 = Messages[MessageFilenames.Jumper3];
var jumper4 = Messages[MessageFilenames.Jumper4];
var cybersecTest = Messages[MessageFilenames.CyberSecTest];
var nitesecTest = Messages[MessageFilenames.NiteSecTest];
var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest];
var redpill = Messages[MessageFilenames.RedPill];
var redpillOwned = false;
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_2__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill].owned) {
redpillOwned = true;
}
if (redpill && redpillOwned && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.length === 0 && !_RedPill__WEBPACK_IMPORTED_MODULE_7__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_5__[/* inMission */ "c"]) {
if (!_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxOpened"]) {
sendMessage(redpill, true);
}
} else if (redpill && redpillOwned) {
//If player has already destroyed a BitNode, message is not forced
if (!_RedPill__WEBPACK_IMPORTED_MODULE_7__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_5__[/* inMission */ "c"] && !_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxOpened"]) {
sendMessage(redpill);
}
} else if (jumper0 && !jumper0.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 25) {
sendMessage(jumper0);
const flightName = _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"].Flight.name;
const homeComp = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer();
if (!homeComp.programs.includes(flightName)) {
homeComp.programs.push(flightName);
}
} else if (jumper1 && !jumper1.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 40) {
sendMessage(jumper1);
} else if (cybersecTest && !cybersecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 50) {
sendMessage(cybersecTest);
} else if (jumper2 && !jumper2.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 175) {
sendMessage(jumper2);
} else if (nitesecTest && !nitesecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 200) {
sendMessage(nitesecTest);
} else if (jumper3 && !jumper3.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 350) {
sendMessage(jumper3);
} else if (jumper4 && !jumper4.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 490) {
sendMessage(jumper4);
} else if (bitrunnersTest && !bitrunnersTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_skill >= 500) {
sendMessage(bitrunnersTest);
}
}
function AddToAllMessages(msg) {
Messages[msg.filename] = msg;
}
let Messages = {}
function loadMessages(saveString) {
Messages = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"]);
}
let MessageFilenames = {
Jumper0: "j0.msg",
Jumper1: "j1.msg",
Jumper2: "j2.msg",
Jumper3: "j3.msg",
Jumper4: "j4.msg",
CyberSecTest: "csec-test.msg",
NiteSecTest: "nitesec-test.msg",
BitRunnersTest: "19dfj3l1nd.msg",
RedPill: "icarus.msg",
}
function initMessages() {
//Reset
Messages = {};
//jump3R Messages
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper0,
"I know you can sense it. I know you're searching for it. " +
"It's why you spend night after " +
"night at your computer.
It's real, I've seen it. And I can " +
"help you find it. But not right now. You're not ready yet.
" +
"Use this program to track your progress
" +
"The fl1ght.exe program was added to your home computer
" +
"-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper1,
"Soon you will be contacted by a hacking group known as CyberSec. " +
"They can help you with your search.
" +
"You should join them, garner their favor, and " +
"exploit them for their Augmentations. But do not trust them. " +
"They are not what they seem. No one is.
" +
"-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper2,
"Do not try to save the world. There is no world to save. If " +
"you want to find the truth, worry only about yourself. Ethics and " +
"morals will get you killed.
Watch out for a hacking group known as NiteSec." +
"
-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper3,
"You must learn to walk before you can run. And you must " +
"run before you can fly. Look for the black hand.
" +
"I.I.I.I
-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper4,
"To find what you are searching for, you must understand the bits. " +
"The bits are all around us. The runners will help you.
" +
"-jump3R"));
//Messages from hacking factions
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.CyberSecTest,
"We've been watching you. Your skills are very impressive. But you're wasting " +
"your talents. If you join us, you can put your skills to good use and change " +
"the world for the better. If you join us, we can unlock your full potential.
" +
"But first, you must pass our test. Find and hack our server using the Terminal.
" +
"-CyberSec"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.NiteSecTest,
"People say that the corrupted governments and corporations rule the world. " +
"Yes, maybe they do. But do you know who everyone really fears? People " +
"like us. Because they can't hide from us. Because they can't fight shadows " +
"and ideas with bullets.
" +
"Join us, and people will fear you, too.
" +
"Find and hack our hidden server using the Terminal. Then, we will contact you again." +
"
-NiteSec"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.BitRunnersTest,
"We know what you are doing. We know what drives you. We know " +
"what you are looking for.
" +
"We can help you find the answers.
" +
"run4theh111z"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.RedPill,
"@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*% " +
")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B) " +
"@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB " +
"DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
}
/***/ }),
/* 71 */
/*!********************************!*\
!*** ./src/Faction/Faction.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Constants_1 = __webpack_require__(/*! ../Constants */ 8);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 251);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
class Faction {
constructor(name = "") {
/**
* Flag signalling whether the player has already received an invitation
* to this faction
*/
this.alreadyInvited = false;
/**
* Holds names of all augmentations that this Faction offers
*/
this.augmentations = [];
/**
* Amount of favor the player has with this faction.
*/
this.favor = 0;
/**
* Flag signalling whether player has been banned from this faction
*/
this.isBanned = false;
/**
* Flag signalling whether player is a member of this faction
*/
this.isMember = false;
/**
* Name of faction
*/
this.name = "";
/**
* Amount of reputation player has with this faction
*/
this.playerReputation = 0;
/**
* Reputation from the last "prestige" that was not converted to favor.
* This reputation rolls over and is used for the next favor calculation
*/
this.rolloverRep = 0;
this.name = name;
}
/**
* Initiatizes a Faction object from a JSON save state.
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Faction, value.data);
}
getInfo() {
const info = FactionInfo_1.FactionInfos[this.name];
if (info == null) {
throw new Error(`Missing faction from FactionInfos: ${this.name} this probably means the faction got corrupted somehow`);
}
return info;
}
gainFavor() {
if (this.favor == null) {
this.favor = 0;
}
if (this.rolloverRep == null) {
this.rolloverRep = 0;
}
const res = this.getFavorGain();
if (res.length !== 2) {
console.error("Invalid result from getFavorGain() function");
return;
}
this.favor += res[0];
this.rolloverRep = res[1];
}
//Returns an array with [How much favor would be gained, how much rep would be left over]
getFavorGain() {
if (this.favor == null) {
this.favor = 0;
}
if (this.rolloverRep == null) {
this.rolloverRep = 0;
}
var favorGain = 0, rep = this.playerReputation + this.rolloverRep;
let reqdRep = Constants_1.CONSTANTS.FactionReputationToFavorBase *
Math.pow(Constants_1.CONSTANTS.FactionReputationToFavorMult, this.favor);
while (rep > 0) {
if (rep >= reqdRep) {
++favorGain;
rep -= reqdRep;
}
else {
break;
}
reqdRep *= Constants_1.CONSTANTS.FactionReputationToFavorMult;
}
return [favorGain, rep];
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Faction", this);
}
}
exports.Faction = Faction;
JSONReviver_1.Reviver.constructors.Faction = Faction;
/***/ }),
/* 72 */
/*!*************************************!*\
!*** ./src/NetscriptBladeburner.js ***!
\*************************************/
/*! exports provided: unknownBladeburnerActionErrorMessage, unknownBladeburnerExceptionMessage, checkBladeburnerAccess */
/*! exports used: checkBladeburnerAccess, unknownBladeburnerActionErrorMessage, unknownBladeburnerExceptionMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return unknownBladeburnerActionErrorMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return unknownBladeburnerExceptionMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkBladeburnerAccess; });
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Bladeburner */ 39);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
function unknownBladeburnerActionErrorMessage(functionName, actionType, actionName) {
return `ERROR: bladeburner.${functionName}() failed due to an invalid action specified. ` +
`Type: ${actionType}, Name: ${actionName}. Note that for contracts and operations, the ` +
`name of the operation is case-sensitive.`;
}
function unknownBladeburnerExceptionMessage(functionName, err) {
return `bladeburner.${functionName}() failed with exception: ` + err;
}
function checkBladeburnerAccess(workerScript, functionName) {
const accessDenied = `${functionName}() failed because you do not ` +
"currently have access to the Bladeburner API. To access the Bladeburner API" +
"you must be employed at the Bladeburner division, AND you must either be in " +
"BitNode-7 or have Source-File 7.";
const hasAccess = _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_1__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN === 7 || _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles.some(a=>{return a.n === 7}));
if(!hasAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__[/* makeRuntimeRejectMsg */ "c"])(workerScript, accessDenied);
}
}
/***/ }),
/* 73 */
/*!*************************!*\
!*** ./src/Terminal.js ***!
\*************************/
/*! exports provided: postNetburnerText, Terminal */
/*! exports used: Terminal, postNetburnerText */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return postNetburnerText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Terminal; });
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Terminal/DirectoryHelpers */ 93);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Terminal/determineAllPossibilitiesForTabCompletion */ 269);
/* harmony import */ var _Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Terminal/HelpText */ 178);
/* harmony import */ var _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Terminal/tabCompletion */ 268);
/* harmony import */ var _Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Alias */ 59);
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Alias__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CodingContracts */ 50);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./DarkWeb/DarkWeb */ 201);
/* harmony import */ var _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./DarkWeb/DarkWebItems */ 99);
/* harmony import */ var _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _Fconf_Fconf__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Fconf/Fconf */ 128);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Fconf/FconfSettings */ 34);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Hacking */ 56);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Hacknet/HacknetServer */ 35);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./InteractiveTutorial */ 40);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Literature */ 129);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Message/Message */ 65);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Message_Message__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Message/MessageHelpers */ 70);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./NetscriptWorker */ 42);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./RedPill */ 83);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Script/RunningScript */ 137);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Script/RunningScriptHelpers */ 168);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 67);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Script/ScriptHelpersTS */ 62);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Server/AllServers */ 21);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Server/Server */ 105);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_Server_Server__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./TextFile */ 96);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 68);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./ui/numeralFormat */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 88);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ../utils/helpers/isString */ 51);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 77);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 147);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ../utils/LogBox */ 119);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../utils/YesNoBox */ 46);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! autosize */ 266);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(autosize__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! jszip */ 265);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! file-saver */ 264);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_46__);
function postNetburnerText() {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bitburner v" + _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].Version);
}
// Helper function that checks if an argument (which is a string) is a valid number
function isNumber(str) {
if (typeof str != "string") { return false; } // Only process strings
return !isNaN(str) && !isNaN(parseFloat(str));
}
// Defines key commands in terminal
$(document).keydown(function(event) {
// Terminal
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["Page"].Terminal)) {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput != null && !event.ctrlKey && !event.shiftKey && !Terminal.contractOpen) {terminalInput.focus();}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].ENTER) {
event.preventDefault(); // Prevent newline from being entered in Script Editor
const command = terminalInput.value;
const dir = Terminal.currDir;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(
"[" +
(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_TIMESTAMPS ? Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_40__["getTimestamp"])() + " " : "") +
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().hostname +
` ~${dir}]> ${command}`
);
if (command.length > 0) {
Terminal.resetTerminalInput(); // Clear input first
Terminal.executeCommands(command);
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].C && event.ctrlKey) {
if (_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"]._actionInProgress) {
// Cancel action
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Cancelling...");
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"]._actionInProgress = false;
Terminal.finishAction(true);
} else if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
// Dont prevent default so it still copies
Terminal.resetTerminalInput(); // Clear Terminal
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].L && event.ctrlKey) {
event.preventDefault();
Terminal.executeCommand("clear"); // Clear screen
}
// Ctrl p same as up arrow
// Ctrl n same as down arrow
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].UPARROW ||
(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].P && event.ctrlKey)) {
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
// Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {return;}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
}
if (i != 0) {
--Terminal.commandHistoryIndex;
}
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_33__["setTimeoutRef"])(function(){terminalInput.selectionStart = terminalInput.selectionEnd = 10000; }, 0);
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].DOWNARROW ||
(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].M && event.ctrlKey)) {
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
// Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {return;}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
}
// Latest command, put nothing
if (i == len || i == len-1) {
Terminal.commandHistoryIndex = len;
terminalInput.value = "";
} else {
++Terminal.commandHistoryIndex;
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].TAB) {
event.preventDefault();
// Autocomplete
if (terminalInput == null) {return;}
let input = terminalInput.value;
if (input == "") { return; }
const semiColonIndex = input.lastIndexOf(";");
if(semiColonIndex !== -1) {
input = input.slice(semiColonIndex + 1);
}
input = input.trim();
input = input.replace(/\s\s+/g, ' ');
const commandArray = input.split(" ");
let index = commandArray.length - 2;
if (index < -1) { index = 0; }
const allPos = Object(_Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__["determineAllPossibilitiesForTabCompletion"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"], input, index, Terminal.currDir);
if (allPos.length == 0) {return;}
let arg = "";
let command = "";
if (commandArray.length == 0) {return;}
if (commandArray.length == 1) {command = commandArray[0];}
else if (commandArray.length == 2) {
command = commandArray[0];
arg = commandArray[1];
} else if (commandArray.length == 3) {
command = commandArray[0] + " " + commandArray[1];
arg = commandArray[2];
} else {
arg = commandArray.pop();
command = commandArray.join(" ");
}
Object(_Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__["tabCompletion"])(command, arg, allPos);
terminalInput.focus();
}
// Extra Bash Emulation Hotkeys, must be enabled through .fconf
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].A && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("home");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].E && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("end");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].B && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("prevchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].B && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("prevword");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].F && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("nextchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].F && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("nextword");
}
if ((event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].H || event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].D) && event.ctrlKey) {
Terminal.modifyInput("backspace");
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
}
}
});
// Keep terminal in focus
let terminalCtrlPressed = false, shiftKeyPressed = false;
$(document).ready(function() {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["Page"].Terminal)) {
$('.terminal-input').focus();
}
});
$(document).keydown(function(e) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].CTRL) {
terminalCtrlPressed = true;
} else if (e.shiftKey) {
shiftKeyPressed = true;
} else if (terminalCtrlPressed || shiftKeyPressed || Terminal.contractOpen) {
// Don't focus
} else {
var inputTextBox = document.getElementById("terminal-input-text-box");
if (inputTextBox != null) {inputTextBox.focus();}
terminalCtrlPressed = false;
shiftKeyPressed = false;
}
}
});
$(document).keyup(function(e) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_34__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_36__["KEY"].CTRL) {
terminalCtrlPressed = false;
}
if (e.shiftKey) {
shiftKeyPressed = false;
}
}
});
let Terminal = {
// Flags to determine whether the player is currently running a hack or an analyze
hackFlag: false,
analyzeFlag: false,
actionStarted: false,
actionTime: 0,
commandHistory: [],
commandHistoryIndex: 0,
// True if a Coding Contract prompt is opened
contractOpen: false,
// Full Path of current directory
// Excludes the trailing forward slash
currDir: "/",
resetTerminalInput: function() {
const dir = Terminal.currDir;
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].WRAP_INPUT) {
document.getElementById("terminal-input-td").innerHTML =
`
` +
'';
// Auto re-size the line element as it wraps
autosize__WEBPACK_IMPORTED_MODULE_44___default()(document.getElementById("terminal-input-text-box"));
} else {
document.getElementById("terminal-input-td").innerHTML =
`
` +
``;
}
var hdr = document.getElementById("terminal-input-header");
hdr.style.display = "inline";
},
modifyInput: function(mod) {
try {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput == null) {return;}
terminalInput.focus();
var inputLength = terminalInput.value.length;
var start = terminalInput.selectionStart;
var end = terminalInput.selectionEnd;
var inputText = terminalInput.value;
switch(mod.toLowerCase()) {
case "backspace":
if (start > 0 && start <= inputLength+1) {
terminalInput.value = inputText.substr(0, start-1) + inputText.substr(start);
}
break;
case "deletewordbefore": // Delete rest of word before the cursor
for (var delStart = start-1; delStart > 0; --delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, delStart) + inputText.substr(start);
return;
}
}
break;
case "deletewordafter": // Delete rest of word after the cursor
for (var delStart = start+1; delStart <= text.length+1; ++delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, start) + inputText.substr(delStart);
return;
}
}
break;
case "clearafter": // Deletes everything after cursor
break;
case "clearbefore:": // Deleetes everything before cursor
break;
}
} catch(e) {
console.error("Exception in Terminal.modifyInput: " + e);
}
},
moveTextCursor: function(loc) {
try {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput == null) {return;}
terminalInput.focus();
var inputLength = terminalInput.value.length;
var start = terminalInput.selectionStart;
var end = terminalInput.selectionEnd;
switch(loc.toLowerCase()) {
case "home":
terminalInput.setSelectionRange(0,0);
break;
case "end":
terminalInput.setSelectionRange(inputLength, inputLength);
break;
case "prevchar":
if (start > 0) {terminalInput.setSelectionRange(start-1, start-1);}
break;
case "prevword":
for (var i = start-2; i >= 0; --i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i+1, i+1);
return;
}
}
terminalInput.setSelectionRange(0, 0);
break;
case "nextchar":
terminalInput.setSelectionRange(start+1, start+1);
break;
case "nextword":
for (var i = start+1; i <= inputLength; ++i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i, i);
return;
}
}
terminalInput.setSelectionRange(inputLength, inputLength);
break;
default:
console.warn("Invalid loc argument in Terminal.moveTextCursor()");
break;
}
} catch(e) {
console.error("Exception in Terminal.moveTextCursor: " + e);
}
},
startHack: function() {
Terminal.hackFlag = true;
// Hacking through Terminal should be faster than hacking through a script
Terminal.actionTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingTime */ "d"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer()) / 4;
Terminal.startAction();
},
startAnalyze: function() {
Terminal.analyzeFlag = true;
Terminal.actionTime = 1;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Analyzing system...");
Terminal.startAction();
},
startAction: function() {
Terminal.actionStarted = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["hackProgressPost"])("Time left:");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["hackProgressBarPost"])("[");
// Disable terminal
document.getElementById("terminal-input-td").innerHTML = '';
$('input[class=terminal-input]').prop('disabled', true);
},
finishAction: function(cancelled = false) {
if (Terminal.hackFlag) {
Terminal.finishHack(cancelled);
} else if (Terminal.analyzeFlag) {
Terminal.finishAnalyze(cancelled);
}
},
// Complete the hack/analyze command
finishHack: function(cancelled = false) {
if (cancelled == false) {
var server = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
// Calculate whether hack was successful
var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingChance */ "b"])(server);
var rand = Math.random();
var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingExpGain */ "c"])(server);
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { // Success!
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] &&
_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] == server.ip) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].bitNodeN == null) {
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].bitNodeN = 1;
}
Object(_RedPill__WEBPACK_IMPORTED_MODULE_22__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].bitNodeN);
return;
}
server.manuallyHacked = true;
var moneyGained = Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculatePercentMoneyHacked */ "e"])(server);
moneyGained = Math.floor(server.moneyAvailable * moneyGained);
if (moneyGained <= 0) {moneyGained = 0;} // Safety check
server.moneyAvailable -= moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].gainMoney(moneyGained);
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].recordMoneySource(moneyGained, "hacking");
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].gainHackingExp(expGainedOnSuccess)
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].gainIntelligenceExp(expGainedOnSuccess / _Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].IntelligenceTerminalHackBaseExpGain);
server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_7__["CONSTANTS"].ServerFortifyAmount);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Hack successful! Gained " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(moneyGained, '($0,0.00)') + " and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(expGainedOnSuccess, '0.0000') + " hacking EXP");
} else { // Failure
// Player only gains 25% exp for failure? TODO Can change this later to balance
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].gainHackingExp(expGainedOnFailure)
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Failed to hack " + server.hostname + ". Gained " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(expGainedOnFailure, '0.0000') + " hacking EXP");
}
}
// Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
Terminal.resetTerminalInput();
$('input[class=terminal-input]').prop('disabled', false);
Terminal.hackFlag = false;
},
finishAnalyze: function(cancelled = false) {
if (cancelled == false) {
let currServ = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const isHacknet = currServ instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15__["HacknetServer"];
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(currServ.hostname + ": ");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Organization name: " + currServ.organizationName);
var rootAccess = "";
if (currServ.hasAdminRights) {rootAccess = "YES";}
else {rootAccess = "NO";}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Root Access: " + rootAccess);
if (!isHacknet) { Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Required hacking skill: " + currServ.requiredHackingSkill); }
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Server security level: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(currServ.hackDifficulty, '0.000a'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Chance to hack: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingChance */ "b"])(currServ), '0.00%'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Time to hack: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingTime */ "d"])(currServ), '0.000') + " seconds");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Total money available on server: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(currServ.moneyAvailable, '$0,0.00'));
if (!isHacknet) { Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Required number of open ports for NUKE: " + currServ.numOpenPortsRequired); }
if (currServ.sshPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SSH port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SSH port: Closed")
}
if (currServ.ftpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("FTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("FTP port: Closed")
}
if (currServ.smtpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SMTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SMTP port: Closed")
}
if (currServ.httpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("HTTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("HTTP port: Closed")
}
if (currServ.sqlPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SQL port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SQL port: Closed")
}
}
Terminal.analyzeFlag = false;
// Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
Terminal.resetTerminalInput();
$('input[class=terminal-input]').prop('disabled', false);
},
executeCommands : function(commands) {
// Sanitize input
commands = commands.trim();
commands = commands.replace(/\s\s+/g, ' '); // Replace all extra whitespace in command with a single space
// Handle Terminal History - multiple commands should be saved as one
if (Terminal.commandHistory[Terminal.commandHistory.length-1] != commands) {
Terminal.commandHistory.push(commands);
if (Terminal.commandHistory.length > 50) {
Terminal.commandHistory.splice(0, 1);
}
}
Terminal.commandHistoryIndex = Terminal.commandHistory.length;
// Split commands and execute sequentially
commands = commands.split(";");
for (let i = 0; i < commands.length; i++) {
if(commands[i].match(/^\s*$/)) { continue; } // Don't run commands that only have whitespace
Terminal.executeCommand(commands[i].trim());
}
},
parseCommandArguments : function(command) {
// This will be used to keep track of whether we're in a quote. This is for situations
// like the alias command:
// alias run="run NUKE.exe"
// We want the run="run NUKE.exe" to be parsed as a single command, so this flag
// will keep track of whether we have a quote in
let inQuote = ``;
// Returns an array with the command and its arguments in each index
// Properly handles quotation marks (e.g. `run foo.script "the sun"` will return [run, foo.script, the sun])
const args = [];
let start = 0, i = 0;
let prevChar = ''; // Previous character
while (i < command.length) {
let escaped = false; // Check for escaped quotation marks
if (i >= 1) {
prevChar = command.charAt(i - 1);
if (prevChar === "\\") { escaped = true; }
}
const c = command.charAt(i);
if (c === '"') { // Double quotes
if (!escaped && prevChar === " ") {
const endQuote = command.indexOf('"', i+1);
if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) {
args.push(command.substr(i+1, (endQuote - i - 1)));
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
start = i = endQuote+2; // Skip the space
}
continue;
}
} else {
if (inQuote === ``) {
inQuote = `"`;
} else if (inQuote === `"`) {
inQuote = ``;
}
}
} else if (c === "'") { // Single quotes, same thing as above
if (!escaped && prevChar === " ") {
const endQuote = command.indexOf("'", i+1);
if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) {
args.push(command.substr(i+1, (endQuote - i - 1)));
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
start = i = endQuote+2; // Skip the space
}
continue;
}
} else {
if (inQuote === ``) {
inQuote = `'`;
} else if (inQuote === `'`) {
inQuote = ``;
}
}
} else if (c === " " && inQuote === ``) {
let arg = command.substr(start, i-start);
// If this is a number, convert it from a string to number
if (isNumber(arg)) {
args.push(parseFloat(arg));
} else {
args.push(arg);
}
start = i+1;
}
++i;
}
// Add the last argument
if (start !== i) {
let arg = command.substr(start, i-start);
// If this is a number, convert it from string to number
if (isNumber(arg)) {
args.push(parseFloat(arg));
} else {
args.push(arg);
}
}
return args;
},
executeCommand : function(command) {
// Process any aliases
command = Object(_Alias__WEBPACK_IMPORTED_MODULE_4__["substituteAliases"])(command);
// Allow usage of ./
if (command.startsWith("./")) {
command = "run " + command.slice(2);
}
// Only split the first space
var commandArray = Terminal.parseCommandArguments(command);
if (commandArray.length == 0) { return; }
/****************** Interactive Tutorial Terminal Commands ******************/
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* ITutorial */ "a"].isRunning) {
var foodnstuffServ = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["GetServerByHostname"])("foodnstuff");
if (foodnstuffServ == null) {throw new Error("Could not get foodnstuff server"); return;}
switch(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* ITutorial */ "a"].currStep) {
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalHelp:
if (commandArray.length === 1 && commandArray[0] == "help") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["TerminalHelpText"]);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalLs:
if (commandArray.length === 1 && commandArray[0] == "ls") {
Terminal.executeListCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalScan:
if (commandArray.length === 1 && commandArray[0] == "scan") {
Terminal.executeScanCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalScanAnalyze1:
if (commandArray.length == 1 && commandArray[0] == "scan-analyze") {
Terminal.executeScanAnalyzeCommand(1);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalScanAnalyze2:
if (commandArray.length == 2 && commandArray[0] == "scan-analyze" &&
commandArray[1] === 2) {
Terminal.executeScanAnalyzeCommand(2);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalConnect:
if (commandArray.length == 2) {
if ((commandArray[0] == "connect") &&
(commandArray[1] == "foodnstuff" || commandArray[1] == foodnstuffServ.ip)) {
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].currentServer = foodnstuffServ.ip;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Connected to foodnstuff");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Wrong command! Try again!"); return;}
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalAnalyze:
if (commandArray.length === 1 && commandArray[0] === "analyze") {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Incorrect usage of analyze command. Usage: analyze");
return;
}
Terminal.startAnalyze();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalNuke:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "NUKE.exe") {
foodnstuffServ.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("NUKE successful! Gained root access to foodnstuff");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalManualHack:
if (commandArray.length == 1 && commandArray[0] == "hack") {
Terminal.startHack();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalCreateScript:
if (commandArray.length == 2 &&
commandArray[0] == "nano" && commandArray[1] == "foodnstuff.script") {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent("foodnstuff.script", "");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalFree:
if (commandArray.length == 1 && commandArray[0] == "free") {
Terminal.executeFreeCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].TerminalRunScript:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "foodnstuff.script") {
Terminal.runScript(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialSteps */ "d"].ActiveScriptsToTerminal:
if (commandArray.length == 2 &&
commandArray[0] == "tail" && commandArray[1] == "foodnstuff.script") {
// Check that the script exists on this machine
var runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__[/* findRunningScript */ "a"])("foodnstuff.script", [], _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer());
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Error: No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_41__[/* logBoxCreate */ "a"])(runningScript);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_16__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Bad command. Please follow the tutorial");}
break;
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Please follow the tutorial, or click 'Exit Tutorial' if you'd like to skip it");
return;
}
return;
}
/****************** END INTERACTIVE TUTORIAL ******************/
/* Command parser */
var s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
switch (commandArray[0].toLowerCase()) {
case "alias":
if (commandArray.length === 1) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_4__["printAliases"])();
return;
}
if (commandArray.length === 2) {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_4__["parseAliasDeclaration"])(commandArray[1])) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Set alias ${commandArray[1]}`);
return;
}
}
if (commandArray.length === 3) {
if (commandArray[1] === "-g") {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_4__["parseAliasDeclaration"])(commandArray[2], true)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Set global alias ${commandArray[1]}`);
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]');
break;
case "analyze":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Incorrect usage of analyze command. Usage: analyze");
return;
}
Terminal.startAnalyze();
break;
case "buy":
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) {
Object(_DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_9__[/* executeDarkwebTerminalCommand */ "b"])(commandArray);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("You need to be able to connect to the Dark Web to use the buy command. (Maybe there's a TOR router you can buy somewhere)");
}
break;
case "cat": {
try {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of cat command. Usage: cat [file]");
return;
}
const filename = Terminal.getFilepath(commandArray[1]);
if (!filename.endsWith(".msg") && !filename.endsWith(".lit") && !filename.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Only .msg, .txt, and .lit files are viewable with cat (filename must end with .msg, .txt, or .lit)");
return;
}
if (filename.endsWith(".msg") || filename.endsWith(".lit")) {
for (let i = 0; i < s.messages.length; ++i) {
if (filename.endsWith(".lit") && s.messages[i] === filename) {
Object(_Literature__WEBPACK_IMPORTED_MODULE_17__[/* showLiterature */ "b"])(s.messages[i]);
return;
} else if (filename.endsWith(".msg") && s.messages[i].filename === filename) {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_19__[/* showMessage */ "e"])(s.messages[i]);
return;
}
}
} else if (filename.endsWith(".txt")) {
const txt = Terminal.getTextFile(filename);
if (txt != null) {
txt.show();
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`No such file ${filename}`);
} catch(e) {
Terminal.postThrownError(e);
}
break;
}
case "cd": {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: cd [dir]");
} else {
let dir = commandArray[1];
let evaledDir;
if (dir === "/") {
evaledDir = "/";
} else {
// Ignore trailing slashes
dir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["removeTrailingSlash"])(dir);
evaledDir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateDirectoryPath"])(dir, Terminal.currDir);
if (evaledDir == null || evaledDir === "") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Invalid path. Failed to change directories");
return;
}
}
Terminal.currDir = evaledDir;
// Reset input to update current directory on UI
Terminal.resetTerminalInput();
}
break;
}
case "check": {
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...");
} else {
const scriptName = Terminal.getFilepath(commandArray[1]);
// Can only tail script files
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(scriptName)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("tail can only be called on .script files (filename must end with .script)");
return;
}
// Get args
let args = [];
for (var i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
}
// Check that the script exists on this machine
var runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__[/* findRunningScript */ "a"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such script exists");
return;
}
runningScript.displayLog();
}
} catch(e) {
Terminal.postThrownError(e);
}
break;
}
case "clear":
case "cls":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of clear/cls command. Usage: clear/cls");
return;
}
$("#terminal tr:not(:last)").remove();
postNetburnerText();
break;
case "connect": {
// Disconnect from current server in terminal and connect to new one
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of connect command. Usage: connect [ip/hostname]");
return;
}
let ip = commandArray[1];
for (let i = 0; i < s.serversOnNetwork.length; i++) {
if (Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(s, i).ip == ip || Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(s, i).hostname == ip) {
Terminal.connectToServer(ip);
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Host not found");
break;
}
case "download": {
try {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of download command. Usage: download [script/text file]");
return;
}
const fn = commandArray[1];
if (fn === "*" || fn === "*.script" || fn === "*.txt") {
// Download all scripts as a zip
var zip = new jszip__WEBPACK_IMPORTED_MODULE_45__();
if (fn === "*" || fn === "*.script") {
for (var i = 0; i < s.scripts.length; ++i) {
var file = new Blob([s.scripts[i].code], {type:"text/plain"});
zip.file(s.scripts[i].filename + ".js", file);
}
}
if (fn === "*" || fn === "*.txt") {
for (var i = 0; i < s.textFiles.length; ++i) {
var file = new Blob([s.textFiles[i].text], {type:"text/plain"});
zip.file(s.textFiles[i].fn, file);
}
}
let zipFn;
switch (fn) {
case "*.script":
zipFn = "bitburnerScripts.zip"; break;
case "*.txt":
zipFn = "bitburnerTexts.zip"; break;
default:
zipFn = "bitburnerFiles.zip"; break;
}
zip.generateAsync({type:"blob"}).then(function(content) {
file_saver__WEBPACK_IMPORTED_MODULE_46__["saveAs"](content, zipFn);
});
return;
} else if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(fn)) {
// Download a single script
const script = Terminal.getScript(fn);
if (script != null) {
return script.download();
}
} else if (fn.endsWith(".txt")) {
// Download a single text file
const txt = Terminal.getTextFile(fn);
if (txt != null) {
return txt.download();
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Cannot download this filetype`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`${fn} does not exist`);
} catch(e) {
Terminal.postThrownError(e);
}
break;
}
case "expr": {
if (commandArray.length <= 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of expr command. Usage: expr [math expression]");
return;
}
let expr = commandArray.slice(1).join("");
// Sanitize the math expression
let sanitizedExpr = expr.replace(/s+/g, '').replace(/[^-()\d/*+.]/g, '');
let result;
try {
result = eval(sanitizedExpr);
} catch(e) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Could not evaluate expression: ${sanitizedExpr}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(result);
break;
}
case "free":
Terminal.executeFreeCommand(commandArray);
break;
case "hack": {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of hack command. Usage: hack");
return;
}
// Hack the current PC (usually for money)
// You can't hack your home pc or servers you purchased
if (s.purchasedByPlayer) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (s.hasAdminRights == false ) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("You do not have admin rights for this machine! Cannot hack");
} else if (s.requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hacking_skill) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else if (s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15__["HacknetServer"]) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Cannot hack this type of Server")
} else {
Terminal.startHack();
}
break;
}
case "help":
if (commandArray.length !== 1 && commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of help command. Usage: help");
return;
}
if (commandArray.length === 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["TerminalHelpText"]);
} else {
var cmd = commandArray[1];
var txt = _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["HelpTexts"][cmd];
if (txt == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No help topics match '" + cmd + "'");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(txt);
}
break;
case "home":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of home command. Usage: home");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].currentServer = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getHomeComputer().ip;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Connected to home");
Terminal.currDir = "/";
Terminal.resetTerminalInput();
break;
case "hostname":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of hostname command. Usage: hostname");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().hostname);
break;
case "ifconfig":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of ifconfig command. Usage: ifconfig");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().ip);
break;
case "kill": {
Terminal.executeKillCommand(commandArray);
break;
}
case "killall": {
for (let i = s.runningScripts.length - 1; i >= 0; --i) {
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_20__[/* killWorkerScript */ "c"])(s.runningScripts[i], s.ip);
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Killing all running scripts. May take up to a few minutes for the scripts to die...");
break;
}
case "ls": {
Terminal.executeListCommand(commandArray);
break;
}
case "lscpu": {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().cpuCores + " Core(s)");
break;
}
case "mem": {
Terminal.executeMemCommand(commandArray);
break;
}
case "mv": {
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Incorrect number of arguments. Usage: mv [src] [dest]`);
return;
}
try {
const source = commandArray[1];
const dest = commandArray[2];
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(source) && !source.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`'mv' can only be used on scripts and text files (.txt)`);
return;
}
const srcFile = Terminal.getFile(source);
if (srcFile == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Source file ${source} does not exist`);
return;
}
const sourcePath = Terminal.getFilepath(source);
const destPath = Terminal.getFilepath(dest);
const destFile = Terminal.getFile(dest);
// 'mv' command only works on scripts and txt files.
// Also, you can't convert between different file types
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(source)) {
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(dest)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Source and destination files must have the same type`);
return;
}
// Command doesnt work if script is running
if (s.isRunning(sourcePath)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Cannot use 'mv' on a script that is running`);
return;
}
if (destFile != null) {
// Already exists, will be overwritten, so we'll delete it
const status = s.removeFile(destPath);
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Something went wrong...please contact game dev (probably a bug)`);
return;
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Warning: The destination file was overwritten");
}
}
srcFile.filename = destPath;
} else if (source.endsWith(".txt")) {
if (!dest.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Source and destination files must have the same type`);
return;
}
if (destFile != null) {
// Already exists, will be overwritten, so we'll delete it
const status = s.removeFile(destPath);
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Something went wrong...please contact game dev (probably a bug)`);
return;
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Warning: The destination file was overwritten");
}
}
srcFile.fn = destPath;
}
} catch(e) {
Terminal.postThrownError(e);
}
break;
}
case "nano":
Terminal.executeNanoCommand(commandArray);
break;
case "ps":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of ps command. Usage: ps");
return;
}
for (let i = 0; i < s.runningScripts.length; i++) {
let rsObj = s.runningScripts[i];
let res = rsObj.filename;
for (let j = 0; j < rsObj.args.length; ++j) {
res += (" " + rsObj.args[j].toString());
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(res);
}
break;
case "rm": {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: rm [program/script]");
return;
}
// Check programs
let delTarget = Terminal.getFilepath(commandArray[1]);
const status = s.removeFile(delTarget);
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(status.msg);
}
break;
}
case "run":
// Run a program or a script
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]...");
} else {
var executableName = commandArray[1];
// Secret Music player!
if (executableName === "musicplayer") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])('', false);
return;
}
// Check if its a script or just a program/executable
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(executableName)) {
Terminal.runScript(commandArray);
} else if (executableName.endsWith(".cct")) {
Terminal.runContract(executableName);
} else {
Terminal.runProgram(commandArray);
}
}
break;
case "scan":
Terminal.executeScanCommand(commandArray);
break;
case "scan-analyze":
if (commandArray.length === 1) {
Terminal.executeScanAnalyzeCommand(1);
} else {
// # of args must be 2 or 3
if (commandArray.length > 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]");
return;
}
let all = false;
if (commandArray.length === 3 && commandArray[2] === "-a") {
all = true;
}
let depth = parseInt(commandArray[1]);
if (isNaN(depth) || depth < 0) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of scan-analyze command. depth argument must be positive numeric");
return;
}
if (depth > 3 && !_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV1.name) &&
!_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 3");
return;
} else if (depth > 5 && !_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 5");
return;
} else if (depth > 10) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 10");
return;
}
Terminal.executeScanAnalyzeCommand(depth, all);
}
break;
/* eslint-disable no-case-declarations */
case "scp":
Terminal.executeScpCommand(commandArray);
break;
/* eslint-enable no-case-declarations */
case "sudov":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: sudov");
return;
}
if (s.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("You have ROOT access to this machine");
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("You do NOT have root access to this machine");
}
break;
case "tail": {
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]...");
} else {
const scriptName = Terminal.getFilepath(commandArray[1]);
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(scriptName)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("tail can only be called on .script files (filename must end with .script)");
return;
}
// Get script arguments
const args = [];
for (let i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
}
// Check that the script exists on this machine
const runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__[/* findRunningScript */ "a"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_41__[/* logBoxCreate */ "a"])(runningScript);
}
} catch(e) {
Terminal.postThrownError(e);
}
break;
}
case "theme": {
let args = commandArray.slice(1);
if (args.length !== 1 && args.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect number of arguments.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Usage: theme [default|muted|solarized] | #[background color hex] #[text color hex] #[highlight color hex]");
} else if(args.length === 1){
var themeName = args[0];
if (themeName == "default"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#000000");
document.body.style.setProperty('--my-prompt-color', "#f92672");
} else if (themeName == "muted"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#252527");
} else if (themeName == "solarized"){
document.body.style.setProperty('--my-highlight-color',"#6c71c4");
document.body.style.setProperty('--my-font-color',"#839496");
document.body.style.setProperty('--my-background-color',"#002b36");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Theme not found");
}
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_PROMPT_COLOR = document.body.style.getPropertyValue("--my-prompt-color");
} else {
var inputBackgroundHex = args[0];
var inputTextHex = args[1];
var inputHighlightHex = args[2];
if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputBackgroundHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputTextHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputHighlightHex)){
document.body.style.setProperty('--my-highlight-color',inputHighlightHex);
document.body.style.setProperty('--my-font-color',inputTextHex);
document.body.style.setProperty('--my-background-color',inputBackgroundHex);
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_13__["FconfSettings"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Invalid Hex Input for theme");
}
}
break;
}
case "top": {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of top command. Usage: top");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Script Threads RAM Usage");
let currRunningScripts = s.runningScripts;
// Iterate through scripts on current server
for (let i = 0; i < currRunningScripts.length; i++) {
let script = currRunningScripts[i];
// Calculate name padding
let numSpacesScript = 32 - script.filename.length; // 26 -> width of name column
if (numSpacesScript < 0) {numSpacesScript = 0;}
let spacesScript = Array(numSpacesScript+1).join(" ");
// Calculate thread padding
let numSpacesThread = 16 - (script.threads + "").length; // 16 -> width of thread column
let spacesThread = Array(numSpacesThread+1).join(" ");
// Calculate and transform RAM usage
let ramUsage = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_24__["getRamUsageFromRunningScript"])(script) * script.threads, '0.00') + " GB";
var entry = [script.filename, spacesScript, script.threads, spacesThread, ramUsage];
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(entry.join(""));
}
break;
}
case "unalias": {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])('Incorrect usage of unalias name. Usage: unalias [alias]');
return;
} else {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_4__["removeAlias"])(commandArray[1])) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Removed alias ${commandArray[1]}`);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`No such alias exists: ${commandArray[1]}`);
}
}
break;
}
case "wget": {
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of wget command. Usage: wget [url] [target file]");
return;
}
let url = commandArray[1];
let target = commandArray[2];
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(target) && !target.endsWith(".txt")) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`wget failed: Invalid target file. Target file must be script or text file`);
}
$.get(url, function(data) {
let res;
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(target)) {
res = s.writeToScriptFile(target, data);
} else {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("wget failed");
}
if (res.overwritten) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`wget successfully retrieved content and overwrote ${target}`);
}
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`wget successfully retrieved content to new file ${target}`);
}, 'text').fail(function(e) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("wget failed: " + JSON.stringify(e));
})
break;
}
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Command ${commandArray[0]} not found`);
}
},
connectToServer: function(ip) {
var serv = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServer"])(ip);
if (serv == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Invalid server. Connection failed.");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].currentServer = serv.ip;
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Connected to " + serv.hostname);
Terminal.currDir = "/";
if (_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().hostname == "darkweb") {
Object(_DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_9__[/* checkIfConnectedToDarkweb */ "a"])(); // Posts a 'help' message if connecting to dark web
}
Terminal.resetTerminalInput();
},
executeFreeCommand: function(commandArray) {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of free command. Usage: free");
return;
}
const ram = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().maxRam, '0.00');
const used = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().ramUsed, '0.00');
const avail = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().maxRam - _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().ramUsed, '0.00');
const maxLength = Math.max(ram.length, Math.max(used.length, avail.length));
const usedPercent = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().ramUsed/_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().maxRam*100, '0.00');
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Total: ${" ".repeat(maxLength-ram.length)}${ram} GB`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Used: ${" ".repeat(maxLength-used.length)}${used} GB (${usedPercent}%)`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Available: ${" ".repeat(maxLength-avail.length)}${avail} GB`);
},
executeKillCommand: function(commandArray) {
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]...");
return;
}
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const scriptName = Terminal.getFilepath(commandArray[1]);
const args = [];
for (let i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
}
const runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__[/* findRunningScript */ "a"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such script is running. Nothing to kill");
return;
}
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_20__[/* killWorkerScript */ "c"])(runningScript, s.ip);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Killing ${scriptName}. May take up to a few seconds for the scripts to die...`);
} catch(e) {
Terminal.postThrownError(e);
}
},
executeListCommand: function(commandArray) {
const numArgs = commandArray.length;
function incorrectUsage() {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of ls command. Usage: ls [dir] [| grep pattern]");
}
if (numArgs <= 0 || numArgs > 5 || numArgs === 3) {
return incorrectUsage();
}
// Grep
let filter = null; // Grep
// Directory path
let prefix = Terminal.currDir;
if (!prefix.endsWith("/")) {
prefix += "/";
}
// If there are 4+ arguments, then the last 3 must be for grep
if (numArgs >= 4) {
if (commandArray[numArgs - 2] !== "grep" || commandArray[numArgs - 3] !== "|") {
return incorrectUsage();
}
filter = commandArray[numArgs - 1];
}
// If the second argument is not a pipe, then it must be for listing a directory
if (numArgs >= 2 && commandArray[1] !== "|") {
prefix = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateDirectoryPath"])(commandArray[1], Terminal.currDir);
if (prefix != null) {
if (!prefix.endsWith("/")) {
prefix += "/";
}
if (!Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["isValidDirectoryPath"])(prefix)) {
return incorrectUsage();
}
}
}
// Root directory, which is the same as no 'prefix' at all
if (prefix === "/") {
prefix = null;
}
// Display all programs and scripts
let allFiles = [];
let folders = [];
function handleFn(fn) {
let parsedFn = fn;
if (prefix) {
if (!fn.startsWith(prefix)) {
return;
} else {
parsedFn = fn.slice(prefix.length, fn.length);
}
}
if (filter && !parsedFn.includes(filter)) {
return;
}
// If the fn includes a forward slash, it must be in a subdirectory.
// Therefore, we only list the "first" directory in its path
if (parsedFn.includes("/")) {
const firstParentDir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["getFirstParentDirectory"])(parsedFn);
if (filter && !firstParentDir.includes(filter)) {
return;
}
if (!folders.includes(firstParentDir)) {
folders.push(firstParentDir);
}
return;
}
allFiles.push(parsedFn);
}
// Get all of the programs and scripts on the machine into one temporary array
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
for (const program of s.programs) handleFn(program);
for (const script of s.scripts) handleFn(script.filename);
for (const txt of s.textFiles) handleFn(txt.fn);
for (const contract of s.contracts) handleFn(contract.fn);
for (const msgOrLit of s.messages) (msgOrLit instanceof _Message_Message__WEBPACK_IMPORTED_MODULE_18__["Message"]) ? handleFn(msgOrLit.filename) : handleFn(msgOrLit);
// Sort the files/folders alphabetically then print each
allFiles.sort();
folders.sort();
const config = { color: "#0000FF" };
for (const dir of folders) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postContent"])(dir, config);
}
for (const file of allFiles) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postContent"])(file);
}
},
executeMemCommand: function(commandArray) {
try {
if (commandArray.length !== 2 && commandArray.length !== 4) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]");
return;
}
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const scriptName = commandArray[1];
let numThreads = 1;
if (commandArray.length === 4 && commandArray[2] === "-t") {
numThreads = Math.round(parseInt(commandArray[3]));
if (isNaN(numThreads) || numThreads < 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Invalid number of threads specified. Number of threads must be greater than 1");
return;
}
}
const script = Terminal.getScript(scriptName);
if (script == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such script exists!");
return;
}
const ramUsage = script.ramUsage * numThreads;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`This script requires ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(ramUsage, '0.00')} GB of RAM to run for ${numThreads} thread(s)`);
} catch(e) {
Terminal.postThrownError(e);
}
},
executeNanoCommand: function(commandArray) {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of nano command. Usage: nano [scriptname]");
return;
}
try {
const filename = commandArray[1];
if (filename === ".fconf") {
let text = Object(_Fconf_Fconf__WEBPACK_IMPORTED_MODULE_12__[/* createFconf */ "a"])();
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filename, text);
return;
} else if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(filename)) {
const filepath = Terminal.getFilepath(filename);
const script = Terminal.getScript(filename);
if (script == null) {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath);
} else {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath, script.code);
}
} else if (filename.endsWith(".txt")) {
const filepath = Terminal.getFilepath(filename);
const txt = Terminal.getTextFile(filename);
if (txt == null) {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath);
} else {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath, txt.text);
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Invalid file. Only scripts (.script, .ns, .js), text files (.txt), or .fconf can be edited with nano"); return;
}
} catch(e) {
Terminal.postThrownError(e);
}
},
executeScanCommand: function(commandArray) {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of netstat/scan command. Usage: netstat/scan");
return;
}
// Displays available network connections using TCP
const currServ = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Hostname IP Root Access");
for (let i = 0; i < currServ.serversOnNetwork.length; i++) {
// Add hostname
let entry = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(currServ, i);
if (entry == null) { continue; }
entry = entry.hostname;
// Calculate padding and add IP
let numSpaces = 21 - entry.length;
let spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(currServ, i).ip;
// Calculate padding and add root access info
let hasRoot;
if (Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(currServ, i).hasAdminRights) {
hasRoot = 'Y';
} else {
hasRoot = 'N';
}
numSpaces = 21 - Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(currServ, i).ip.length;
spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += hasRoot;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(entry);
}
},
executeScanAnalyzeCommand: function(depth=1, all=false) {
// TODO Using array as stack for now, can make more efficient
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(" ");
// Map of all servers to keep track of which have been visited
var visited = {};
for (const ip in _Server_AllServers__WEBPACK_IMPORTED_MODULE_27__["AllServers"]) {
visited[ip] = 0;
}
const stack = [];
const depthQueue = [0];
const currServ = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
stack.push(currServ);
while(stack.length != 0) {
const s = stack.pop();
const d = depthQueue.pop();
const isHacknet = s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_15__["HacknetServer"];
if (!all && s.purchasedByPlayer && s.hostname != "home") {
continue; // Purchased server
} else if (visited[s.ip] || d > depth) {
continue; // Already visited or out-of-depth
} else if (!all && isHacknet) {
continue; // Hacknet Server
} else {
visited[s.ip] = 1;
}
for (var i = s.serversOnNetwork.length-1; i >= 0; --i) {
stack.push(Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServerOnNetwork"])(s, i));
depthQueue.push(d+1);
}
if (d == 0) {continue;} // Don't print current server
var titleDashes = Array((d-1) * 4 + 1).join("-");
if (_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].AutoLink.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("" + titleDashes + "> " + s.hostname + "", false);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("" + titleDashes + ">" + s.hostname + "");
}
var dashes = titleDashes + "--";
var c = "NO";
if (s.hasAdminRights) {c = "YES";}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`${dashes}Root Access: ${c}${!isHacknet ? ", Required hacking skill: " + s.requiredHackingSkill : ""}`);
if (!isHacknet) { Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(dashes + "Number of open ports required to NUKE: " + s.numOpenPortsRequired); }
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(dashes + "RAM: " + s.maxRam);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(" ");
}
var links = document.getElementsByClassName("scan-analyze-link");
for (let i = 0; i < links.length; ++i) {
(function() {
var hostname = links[i].innerHTML.toString();
links[i].onclick = function() {
if (Terminal.analyzeFlag || Terminal.hackFlag) {return;}
Terminal.connectToServer(hostname);
}
}());// Immediate invocation
}
},
executeScpCommand(commandArray) {
try {
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
const scriptname = Terminal.getFilepath(commandArray[1]);
if (!scriptname.endsWith(".lit") && !Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(scriptname) && !scriptname.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("scp only works for scripts, text files (.txt), and literature files (.lit)");
return;
}
const destServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServer"])(commandArray[2]);
if (destServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`Invalid destination. ${commandArray[2]} not found`);
return;
}
const ip = destServer.ip;
const currServ = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
// Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message_Message__WEBPACK_IMPORTED_MODULE_18__["Message"]) && currServ.messages[i] == scriptname) {
found = true;
break;
}
}
if (!found) { return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such file exists!"); }
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(scriptname + " copied over to " + destServer.hostname);
return; // Already exists
}
}
destServer.messages.push(scriptname);
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(scriptname + " copied over to " + destServer.hostname);
}
// Scp for txt files
if (scriptname.endsWith(".txt")) {
var found = false, txtFile;
for (var i = 0; i < currServ.textFiles.length; ++i) {
if (currServ.textFiles[i].fn === scriptname) {
found = true;
txtFile = currServ.textFiles[i];
break;
}
}
if (!found) { return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("No such file exists!"); }
let tRes = destServer.writeToTextFile(txtFile.fn, txtFile.text);
if (!tRes.success) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("scp failed");
return;
}
if (tRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwriten`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
return;
}
// Get the current script
let sourceScript = null;
for (let i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
sourceScript = currServ.scripts[i];
break;
}
}
if (sourceScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("scp() failed. No such script exists");
return;
}
let sRes = destServer.writeToScriptFile(scriptname, sourceScript.code);
if (!sRes.success) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(`scp failed`);
return;
}
if (sRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwritten`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
} catch(e) {
Terminal.postThrownError(e);
}
},
// First called when the "run [program]" command is called. Checks to see if you
// have the executable and, if you do, calls the executeProgram() function
runProgram: function(commandArray) {
if (commandArray.length < 2) { return; }
// Check if you have the program on your computer. If you do, execute it, otherwise
// display an error message
const programName = commandArray[1];
if (_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hasProgram(programName)) {
Terminal.executeProgram(commandArray);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)");
},
// Contains the implementations of all possible programs
executeProgram: function(commandArray) {
if (commandArray.length < 2) { return; }
var s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const programName = commandArray[1];
const splitArgs = commandArray.slice(1);
// TODO: refactor this/these out of Terminal. This logic could reside closer to the Programs themselves.
/**
* @typedef {function (server=, args=)} ProgramHandler
* @param {Server} server The current server the program is being executed against
* @param {string[]} args The command line arguments passed in to the program
* @returns {void}
*/
/**
* @type {Object. {
if (server.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("You already have root access to this computer. There is no reason to run NUKE.exe");
return;
}
if (server.openPortCount >= _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().numOpenPortsRequired) {
server.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("NUKE successful! Gained root access to " + _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().hostname);
// TODO: Make this take time rather than be instant
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("NUKE unsuccessful. Not enough ports have been opened");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].BruteSSHProgram.name] = (server) => {
if (server.sshPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SSH Port (22) is already open!");
return;
}
server.sshPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Opened SSH Port(22)!")
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].FTPCrackProgram.name] = (server) => {
if (server.ftpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("FTP Port (21) is already open!");
return;
}
server.ftpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Opened FTP Port (21)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].RelaySMTPProgram.name] = (server) => {
if (server.smtpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SMTP Port (25) is already open!");
return;
}
server.smtpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Opened SMTP Port (25)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].HTTPWormProgram.name] = (server) => {
if (server.httpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("HTTP Port (80) is already open!");
return;
}
server.httpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Opened HTTP Port (80)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].SQLInjectProgram.name] = (server) => {
if (server.sqlPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("SQL Port (1433) is already open!");
return;
}
server.sqlPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Opened SQL Port (1433)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].ServerProfiler.name] = (server, args) => {
if (args.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Must pass a server hostname or IP as an argument for ServerProfiler.exe");
return;
}
const targetServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__["getServer"])(args[1]);
if (targetServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Invalid server IP/hostname");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(targetServer.hostname + ":");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Server base security level: " + targetServer.baseDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Server current security level: " + targetServer.hackDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Server growth rate: " + targetServer.serverGrowth);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Netscript hack() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateHackingTime */ "d"])(targetServer), '0.0') + "s");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Netscript grow() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateGrowTime */ "a"])(targetServer), '0.0') + "s");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Netscript weaken() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_14__[/* calculateWeakenTime */ "f"])(targetServer), '0.0') + "s");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].AutoLink.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("When using scan-analyze, click on a server's hostname to connect to it.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV1.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV2.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].Flight.name] = () => {
const numAugReq = Math.round(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__["BitNodeMultipliers"].DaedalusAugsRequirement*30)
const fulfilled = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].augmentations.length >= numAugReq &&
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].money.gt(1e11) &&
((_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hacking_skill >= 2500)||
(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].strength >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].defense >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].dexterity >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].agility >= 1500));
if(!fulfilled) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Augmentations: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].augmentations.length} / ${numAugReq}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Money: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].money.toNumber(), '($0.000a)')} / ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_35__["numeralWrapper"].format(1e11, '($0.000a)')}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("One path below must be fulfilled...");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("----------HACKING PATH----------");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Hacking skill: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hacking_skill} / 2500`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("----------COMBAT PATH----------");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Strength: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].strength} / 1500`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Defense: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].defense} / 1500`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Dexterity: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].dexterity} / 1500`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Agility: ${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].agility} / 1500`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("We will contact you.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("-- Daedalus --");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].BitFlume.name] = () => {
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__["yesNoBoxGetYesButton"])();
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__["yesNoBoxGetNoButton"])();
yesBtn.innerHTML = "Travel to BitNode Nexus";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_22__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].bitNodeN, true);
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__["yesNoBoxClose"])();
});
noBtn.addEventListener("click", function() {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__["yesNoBoxClose"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_42__["yesNoBoxCreate"])("WARNING: USING THIS PROGRAM WILL CAUSE YOU TO LOSE ALL OF YOUR PROGRESS ON THE CURRENT BITNODE.
" +
"Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " +
"and select a new one.");
};
if (!programHandlers.hasOwnProperty(programName)){
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Invalid executable. Cannot be run");
return;
}
programHandlers[programName](s, splitArgs);
},
/**
* Given a filename, returns that file's full path. This takes into account
* the Terminal's current directory.
*/
getFilepath : function(filename) {
const path = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateFilePath"])(filename, Terminal.currDir);
if (path == null) {
throw new Error(`Invalid file path specified: ${filename}`);
}
if (Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["isInRootDirectory"])(path)) {
return Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["removeLeadingSlash"])(path);
}
return path;
},
/**
* Given a filename, searches and returns that file. File-type agnostic
*/
getFile: function (filename) {
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_26__["isScriptFilename"])(filename)) {
return Terminal.getScript(filename);
}
if (filename.endsWith(".lit")) {
return Terminal.getLitFile(filename);
}
if (filename.endsWith(".txt")) {
return Terminal.getTextFile(filename);
}
return null;
},
/**
* Processes a file path referring to a literature file, taking into account the terminal's
* current directory + server. Returns the lit file if it exists, and null otherwise
*/
getLitFile: function(filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const lit of s.messages) {
if (typeof lit === "string" && filepath === lit) {
return lit;
}
}
return null;
},
/**
* Processes a file path referring to a script, taking into account the terminal's
* current directory + server. Returns the script if it exists, and null otherwise.
*/
getScript: function(filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const script of s.scripts) {
if (filepath === script.filename) {
return script;
}
}
return null;
},
/**
* Processes a file path referring to a text file, taking into account the terminal's
* current directory + server. Returns the text file if it exists, and null otherwise.
*/
getTextFile: function(filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const txt of s.textFiles) {
if (filepath === txt.fn) {
return txt;
}
}
return null;
},
postThrownError: function(e) {
if (e instanceof Error) {
const errorLabel = "Error: ";
const errorString = e.toString();
if (errorString.startsWith(errorLabel)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(errorString.slice(errorLabel.length));
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])(errorString);
}
}
},
runScript: function(commandArray) {
if (commandArray.length < 2) {
dialogBoxCreate(`Bug encountered with Terminal.runScript(). Command array has a length of less than 2: ${commandArray}`);
return;
}
const server = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
let numThreads = 1;
const args = [];
const scriptName = Terminal.getFilepath(commandArray[1]);
if (commandArray.length > 2) {
if (commandArray.length >= 4 && commandArray[2] == "-t") {
numThreads = Math.round(parseFloat(commandArray[3]));
if (isNaN(numThreads) || numThreads < 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["postError"])("Invalid number of threads specified. Number of threads must be greater than 0");
return;
}
for (let i = 4; i < commandArray.length; ++i) {
args.push(commandArray[i]);
}
} else {
for (let i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i])
}
}
}
// Check if this script is already running
if (Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_25__[/* findRunningScript */ "a"])(scriptName, args, server) != null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("ERROR: This script is already running. Cannot run multiple instances");
return;
}
// Check if the script exists and if it does run it
for (var i = 0; i < server.scripts.length; i++) {
if (server.scripts[i].filename === scriptName) {
// Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage * numThreads;
var ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Need root access to run script");
return;
} else if (ramUsage > ramAvailable){
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("This machine does not have enough RAM to run this script with " +
numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
return;
} else {
// Able to run script
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Running script with " + numThreads + " thread(s) and args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(args) + ".");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("May take a few seconds to start up the process...");
var runningScriptObj = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_23__["RunningScript"](script, args);
runningScriptObj.threads = numThreads;
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_20__[/* addWorkerScript */ "b"])(runningScriptObj, server);
// This has to come after addWorkerScript() because that fn
// updates the RAM usage. This kinda sucks, address if possible
server.runScript(runningScriptObj, _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].hacknet_node_money_mult);
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("ERROR: No such script");
},
runContract: async function(contractName) {
// There's already an opened contract
if (Terminal.contractOpen) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("ERROR: There's already a Coding Contract in Progress");
}
const serv = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer();
const contract = serv.getContract(contractName);
if (contract == null) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("ERROR: No such contract");
}
Terminal.contractOpen = true;
const res = await contract.prompt();
switch (res) {
case _CodingContracts__WEBPACK_IMPORTED_MODULE_6__["CodingContractResult"].Success:
var reward = _Player__WEBPACK_IMPORTED_MODULE_21__["Player"].gainCodingContractReward(contract.reward, contract.getDifficulty());
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Contract SUCCESS - ${reward}`);
serv.removeContract(contract);
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_6__["CodingContractResult"].Failure:
++contract.tries;
if (contract.tries >= contract.getMaxNumTries()) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Contract
FAILED
- Contract is now self-destructing");
serv.removeContract(contract);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])(`Contract
FAILED
- ${contract.getMaxNumTries() - contract.tries} tries remaining`);
}
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_6__["CodingContractResult"].Cancelled:
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_43__["post"])("Contract cancelled");
break;
}
Terminal.contractOpen = false;
},
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 74 */
/*!*************************!*\
!*** ./src/Missions.js ***!
\*************************/
/*! exports provided: HackingMission, inMission, setInMission, currMission */
/*! exports used: HackingMission, currMission, inMission, setInMission */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HackingMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return inMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return setInMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return currMission; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 14);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 52);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 88);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 15);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/isString */ 51);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 27);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jsplumb */ 628);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_10__);
let inMission = false; // Flag to denote whether a mission is running
let currMission = null;
function setInMission(bool, mission) {
inMission = bool;
if (bool) {
currMission = mission;
} else {
currMission = null;
}
}
// Keyboard shortcuts
$(document).keydown(function(e) {
if (inMission && currMission && currMission.selectedNode.length != 0) {
switch (e.keyCode) {
case 65: // a for Attack
currMission.actionButtons[0].click();
break;
case 83: // s for Scan
currMission.actionButtons[1].click();
break;
case 87: // w for Weaken
currMission.actionButtons[2].click();
break;
case 70: // f for Fortify
currMission.actionButtons[3].click();
break;
case 82: // r for Overflow
currMission.actionButtons[4].click();
break;
case 68: // d for Detach connection
currMission.actionButtons[5].click();
break;
default:
break;
}
}
});
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
}
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
}
function Node(type, stats) {
this.type = type;
this.atk = stats.atk ? stats.atk : 0;
this.def = stats.def ? stats.def : 0;
this.hp = stats.hp ? stats.hp : 0;
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.action = null;
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)
*/
this.conn = null;
}
Node.prototype.setPosition = function(x, y) {
this.pos = [x, y];
}
Node.prototype.setControlledByPlayer = function() {
this.plyrCtrl = true;
this.enmyCtrl = false;
if (this.el) {
this.el.classList.remove("hack-mission-enemy-node");
this.el.classList.add("hack-mission-player-node");
}
}
Node.prototype.setControlledByEnemy = function() {
this.plyrCtrl = false;
this.enmyCtrl = true;
if (this.el) {
this.el.classList.remove("hack-mission-player-node");
this.el.classList.add("hack-mission-enemy-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
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button");
actionButtons[i].classList.add("a-link-button-inactive");
}
switch(this.type) {
case NodeTypes.Core:
// 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");
}
break;
case NodeTypes.Transfer:
actionButtons[1].classList.remove("a-link-button-inactive");
actionButtons[1].classList.add("a-link-button");
actionButtons[2].classList.remove("a-link-button-inactive");
actionButtons[2].classList.add("a-link-button");
actionButtons[3].classList.remove("a-link-button-inactive");
actionButtons[3].classList.add("a-link-button");
actionButtons[4].classList.remove("a-link-button-inactive");
actionButtons[4].classList.add("a-link-button");
actionButtons[5].classList.remove("a-link-button-inactive");
actionButtons[5].classList.add("a-link-button");
break;
case NodeTypes.Shield:
case NodeTypes.Firewall:
actionButtons[3].classList.remove("a-link-button-inactive");
actionButtons[3].classList.add("a-link-button");
break;
default:
break;
}
}
Node.prototype.deselect = function(actionButtons) {
this.el.classList.remove("hack-mission-player-node-active");
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button");
actionButtons[i].classList.add("a-link-button-inactive");
}
}
Node.prototype.untarget = function() {
if (this.targetedCount === 0) {
console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count");
return;
}
--this.targetedCount;
}
/**
* 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.playerCores = [];
this.playerNodes = []; // Non-core nodes
this.playerAtk = 0;
this.playerDef = 0;
this.enemyCores = [];
this.enemyDatabases = [];
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.actionButtons = []; // DOM buttons for actions
this.availablePositions = [];
for (var r = 0; r < 8; ++r) {
for (var c = 0; c < 8; ++c) {
this.availablePositions.push([r, c]);
}
}
this.map = [];
for (var i = 0; i < 8; ++i) {
this.map.push([null, null, null, null, null, null, null, null]);
}
this.jsplumbinstance = null;
this.difficulty = rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1;
console.log("difficulty: " + this.difficulty);
this.reward = 250 + (rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion);
}
HackingMission.prototype.init = function() {
// Create Header DOM
this.createPageDom();
// Create player starting nodes
var home = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer()
for (var i = 0; i < home.cpuCores; ++i) {
var stats = {
atk: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5) + 30,
def: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20),
hp: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4),
};
this.playerCores.push(new Node(NodeTypes.Core, stats));
this.playerCores[i].setControlledByPlayer();
this.setNodePosition(this.playerCores[i], i, 0);
this.removeAvailablePosition(i, 0);
}
// 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,
Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1));
var numDatabases = Math.min(10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1));
var totalNodes = numNodes + numFirewalls + numDatabases;
var xlimit = 7 - Math.floor(totalNodes / 8);
var randMult = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__["addOffset"])(0.8 + (this.difficulty / 5), 10);
for (var i = 0; i < numNodes; ++i) {
var stats = {
atk: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(80, 86),
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5, 10),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(210, 230)
}
this.enemyCores.push(new Node(NodeTypes.Core, stats));
this.enemyCores[i].setControlledByEnemy();
this.setNodeRandomPosition(this.enemyCores[i], xlimit);
}
for (var i = 0; i < numFirewalls; ++i) {
var stats = {
atk: 0,
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10, 20),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(275, 300)
}
this.enemyNodes.push(new Node(NodeTypes.Firewall, stats));
this.enemyNodes[i].setControlledByEnemy();
this.setNodeRandomPosition(this.enemyNodes[i], xlimit);
}
for (var i = 0; i < numDatabases; ++i) {
var stats = {
atk: 0,
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30, 55),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(210, 275)
}
var node = new Node(NodeTypes.Database, stats);
node.setControlledByEnemy();
this.setNodeRandomPosition(node, xlimit);
this.enemyDatabases.push(node);
}
this.calculateDefenses();
this.calculateAttacks();
this.createMap();
}
HackingMission.prototype.createPageDom = function() {
var container = document.getElementById("mission-container");
var favorMult = 1 + (this.faction.favor / 100);
var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult;
var headerText = document.createElement("p");
headerText.innerHTML = "You are about to start a hacking mission! You will gain " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name +
" if you win. For more information " +
"about how hacking missions work, click one of the guide links " +
"below (one opens up an in-game guide and the other opens up " +
"the guide from the wiki). Click the 'Start' button to begin.";
headerText.style.display = "block";
headerText.classList.add("hack-mission-header-element");
headerText.style.width = "80%";
var inGameGuideBtn = document.createElement("a");
inGameGuideBtn.innerText = "How to Play";
inGameGuideBtn.classList.add("a-link-button");
inGameGuideBtn.style.display = "inline-block";
inGameGuideBtn.classList.add("hack-mission-header-element");
inGameGuideBtn.addEventListener("click", function() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay);
return false;
});
var wikiGuideBtn = document.createElement("a");
wikiGuideBtn.innerText = "Wiki Guide";
wikiGuideBtn.classList.add("a-link-button");
wikiGuideBtn.style.display = "inline-block";
wikiGuideBtn.classList.add("hack-mission-header-element");
wikiGuideBtn.target = "_blank";
// TODO Add link to wiki page wikiGuideBtn.href =
// 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");
startBtn.classList.add("a-link-button");
startBtn.classList.add("hack-mission-header-element");
startBtn.style.display = "inline-block";
startBtn.addEventListener("click", ()=>{
this.start();
return false;
});
var forfeitMission = document.createElement("a");
forfeitMission.innerHTML = "Forfeit Mission (Exit)";
forfeitMission.classList.add("a-link-button");
forfeitMission.classList.add("hack-mission-header-element");
forfeitMission.style.display = "inline-block";
forfeitMission.addEventListener("click", ()=> {
this.finishMission(false);
return false;
});
var timer = document.createElement("p");
timer.setAttribute("id", "hacking-mission-timer");
timer.style.display = "inline-block";
timer.style.margin = "6px";
// 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("hack-mission-header-element");
actionsContainer.appendChild(this.actionButtons[i]);
}
this.actionButtons[0].innerText = "Attack(a)";
var atkTooltip = document.createElement("span");
atkTooltip.classList.add("tooltiptexthigh");
atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[0].appendChild(atkTooltip);
this.actionButtons[1].innerText = "Scan(s)";
var scanTooltip = document.createElement("span");
scanTooltip.classList.add("tooltiptexthigh");
scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[1].appendChild(scanTooltip);
this.actionButtons[2].innerText = "Weaken(w)";
var WeakenTooltip = document.createElement("span");
WeakenTooltip.classList.add("tooltiptexthigh");
WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[2].appendChild(WeakenTooltip);
this.actionButtons[3].innerText = "Fortify(f)";
var fortifyTooltip = document.createElement("span");
fortifyTooltip.classList.add("tooltiptexthigh");
fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " +
"your hacking level";
this.actionButtons[3].appendChild(fortifyTooltip);
this.actionButtons[4].innerText = "Overflow(r)";
var overflowTooltip = document.createElement("span");
overflowTooltip.classList.add("tooltiptexthigh");
overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " +
"of this depends on your hacking level.";
this.actionButtons[4].appendChild(overflowTooltip);
this.actionButtons[5].innerText = "Drop Connection(d)";
var dropconnTooltip = document.createElement("span");
dropconnTooltip.classList.add("tooltiptexthigh");
dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " +
"also be done by simply clicking the white connection line.";
this.actionButtons[5].appendChild(dropconnTooltip);
// Player/enemy defense displays will be in action container
var playerStats = document.createElement("p");
var enemyStats = document.createElement("p");
playerStats.style.display = "inline-block";
enemyStats.style.display = "inline-block";
playerStats.style.color = "#00ccff";
enemyStats.style.color = "red";
playerStats.style.margin = "4px";
enemyStats.style.margin = "4px";
playerStats.setAttribute("id", "hacking-mission-player-stats");
enemyStats.setAttribute("id", "hacking-mission-enemy-stats");
actionsContainer.appendChild(playerStats);
actionsContainer.appendChild(enemyStats);
// Set Action Button event listeners
this.actionButtons[0].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
if (this.selectedNode[0].type !== NodeTypes.Core) {return;}
this.setActionButtonsActive(this.selectedNode[0].type);
this.setActionButton(NodeActions.Attack, false); // Set attack button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Attack;
});
});
this.actionButtons[1].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
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
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
this.setActionButton(NodeActions.Scan, false); // Set scan button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Scan;
});
});
this.actionButtons[2].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
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
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
this.setActionButton(NodeActions.Weaken, false); // Set Weaken button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Weaken;
});
});
this.actionButtons[3].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
this.setActionButtonsActive(this.selectedNode[0].type);
this.setActionButton(NodeActions.Fortify, false); // Set Fortify button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Fortify;
});
});
this.actionButtons[4].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
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.selectedNode.forEach(function(node){
node.action = NodeActions.Overflow;
});
});
this.actionButtons[5].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
this.selectedNode.forEach(function(node){
if (node.conn) {
var endpoints = node.conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
}
node.action = NodeActions.Fortify;
});
});
var timeDisplay = document.createElement("p");
container.appendChild(headerText);
container.appendChild(inGameGuideBtn);
container.appendChild(wikiGuideBtn);
container.appendChild(startBtn);
container.appendChild(forfeitMission);
container.appendChild(timer);
container.appendChild(actionsContainer);
container.appendChild(timeDisplay);
}
HackingMission.prototype.setActionButtonsInactive = function() {
for (var i = 0; i < this.actionButtons.length; ++i) {
this.actionButtons[i].classList.remove("a-link-button");
this.actionButtons[i].classList.add("a-link-button-inactive");
}
}
HackingMission.prototype.setActionButtonsActive = function(nodeType=null) {
for (var i = 0; i < this.actionButtons.length; ++i) {
this.actionButtons[i].classList.add("a-link-button");
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
*/
if (nodeType) {
switch (nodeType) {
case NodeTypes.Firewall:
case NodeTypes.Shield:
this.actionButtons[0].classList.remove("a-link-button");
this.actionButtons[0].classList.add("a-link-button-inactive");
this.actionButtons[1].classList.remove("a-link-button");
this.actionButtons[1].classList.add("a-link-button-inactive");
this.actionButtons[2].classList.remove("a-link-button");
this.actionButtons[2].classList.add("a-link-button-inactive");
this.actionButtons[4].classList.remove("a-link-button");
this.actionButtons[4].classList.add("a-link-button-inactive");
this.actionButtons[5].classList.remove("a-link-button");
this.actionButtons[5].classList.add("a-link-button-inactive");
break;
case NodeTypes.Transfer:
this.actionButtons[0].classList.remove("a-link-button");
this.actionButtons[0].classList.add("a-link-button-inactive");
break;
default:
break;
}
}
}
// True for active, false for inactive
HackingMission.prototype.setActionButton = function(i, active=true) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_8__["isString"])(i)) {
switch (i) {
case NodeActions.Attack:
i = 0;
break;
case NodeActions.Scan:
i = 1;
break;
case NodeActions.Weaken:
i = 2;
break;
case NodeActions.Fortify:
i = 3;
break;
case NodeActions.Overflow:
default:
i = 4;
break;
}
}
if (active) {
this.actionButtons[i].classList.remove("a-link-button-inactive");
this.actionButtons[i].classList.add("a-link-button");
} else {
this.actionButtons[i].classList.remove("a-link-button");
this.actionButtons[i].classList.add("a-link-button-inactive");
}
}
HackingMission.prototype.calculateAttacks = function() {
var total = 0;
for (var i = 0; i < this.playerCores.length; ++i) {
total += this.playerCores[i].atk;
}
for (var i = 0; i < this.playerNodes.length; ++i) {
total += this.playerNodes[i].atk;
}
this.playerAtk = total;
document.getElementById("hacking-mission-player-stats").innerHTML =
"Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerAtk, 1) + " " +
"Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].atk;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].atk;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].atk;
}
this.enemyAtk = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML =
"Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyAtk, 1) + " " +
"Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyDef, 1);
}
HackingMission.prototype.calculateDefenses = function() {
var total = 0;
for (var i = 0; i < this.playerCores.length; ++i) {
total += this.playerCores[i].def;
}
for (var i = 0; i < this.playerNodes.length; ++i) {
total += this.playerNodes[i].def;
}
this.playerDef = total;
document.getElementById("hacking-mission-player-stats").innerHTML =
"Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerAtk, 1) + " " +
"Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].def;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].def;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].def;
}
this.enemyDef = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML =
"Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyAtk, 1) + " " +
"Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyDef, 1);
}
HackingMission.prototype.removeAvailablePosition = function(x, y) {
for (var i = 0; i < this.availablePositions.length; ++i) {
if (this.availablePositions[i][0] === x &&
this.availablePositions[i][1] === y) {
this.availablePositions.splice(i, 1);
return;
}
}
console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y);
}
HackingMission.prototype.setNodePosition = function(nodeObj, x, y) {
if (!(nodeObj instanceof Node)) {
console.log("WARNING: Non-Node object passed into setNodePOsition");
return;
}
if (isNaN(x) || isNaN(y)) {
console.log("ERR: Invalid values passed as x and y for setNodePosition");
console.log(x);
console.log(y);
return;
}
nodeObj.pos = [x, y];
this.map[x][y] = nodeObj;
}
HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) {
var i = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(0, this.availablePositions.length - 1);
if (this.availablePositions[i][1] < xlimit) {
// Recurse if not within limit
return this.setNodeRandomPosition(nodeObj, xlimit);
}
var pos = this.availablePositions.splice(i, 1);
pos = pos[0];
this.setNodePosition(nodeObj, pos[0], pos[1]);
}
HackingMission.prototype.createMap = function() {
// 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
var averageAttack = (this.playerAtk + this.enemyAtk) / 2;
for (var x = 0; x < 8; ++x) {
for (var y = 0; y < 8; ++y) {
if (!(this.map[x][y] instanceof Node)) {
var node, type = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(0, 2);
var randMult = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__["addOffset"])(0.85 + (this.difficulty / 2), 15);
switch (type) {
case 0: // Spam
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15, 45),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(200, 225)
}
node = new Node(NodeTypes.Spam, stats);
break;
case 1: // Transfer
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15, 45),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(250, 275)
}
node = new Node(NodeTypes.Transfer, stats);
break;
case 2: // Shield
default:
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30, 70),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(300, 320)
}
node = new Node(NodeTypes.Shield, stats);
break;
}
this.setNodePosition(node, x, y);
this.removeAvailablePosition(x, y);
this.miscNodes.push(node);
}
}
}
// 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
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);
}
}
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
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
nodeDiv.classList.add("hack-mission-node");
if (nodeObj.plyrCtrl) {
nodeDiv.classList.add("hack-mission-player-node");
} else if (nodeObj.enmyCtrl) {
nodeDiv.classList.add("hack-mission-enemy-node");
}
// Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-cpu-node");
break;
case NodeTypes.Firewall:
txt = "Firewall " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-firewall-node");
break;
case NodeTypes.Database:
txt = "Database " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-database-node");
break;
case NodeTypes.Spam:
txt = "Spam " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-spam-node");
break;
case NodeTypes.Transfer:
txt = "Transfer " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-transfer-node");
break;
case NodeTypes.Shield:
default:
txt = "Shield " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-shield-node");
break;
}
txt += " Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.atk, 1) +
" Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.def, 1);
txtEl.innerHTML = txt;
nodeDiv.appendChild(txtEl);
document.getElementById("hacking-mission-map").appendChild(nodeDiv);
}
HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
if (nodeObj.el == null) {
console.log("ERR: Calling updateNodeDomElement on a Node without an element");
return;
}
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
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Firewall:
txt = "Firewall " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Database:
txt = "Database " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Spam:
txt = "Spam " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Transfer:
txt = "Transfer " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Shield:
default:
txt = "Shield " + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
}
txt += " Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.atk, 1) +
" Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.def, 1);
if (nodeObj.action) {
txt += " " + nodeObj.action;
}
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
*/
HackingMission.prototype.getNodeFromElement = function(el) {
var id;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_8__["isString"])(el)) {
id = el;
} else {
id = el.id;
}
id = id.replace("hacking-mission-node-", "");
var res = id.split('-');
if (res.length != 2) {
console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates");
return null;
}
var x = res[0], y = res[1];
if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) {
console.log("ERROR: Unexpected values for x and y: " + x + ", " + y);
return null;
}
return this.map[x][y];
}
function selectNode(hackMissionInst, el) {
var nodeObj = hackMissionInst.getNodeFromElement(el);
if (nodeObj == null) {console.log("Error getting Node object");}
if (!nodeObj.plyrCtrl) {return;}
clearAllSelectedNodes(hackMissionInst);
nodeObj.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(nodeObj);
}
function multiselectNode(hackMissionInst, el) {
var nodeObj = hackMissionInst.getNodeFromElement(el);
if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");}
if (!nodeObj.plyrCtrl) {return;}
clearAllSelectedNodes(hackMissionInst);
var type = nodeObj.type;
if (type === NodeTypes.Core) {
hackMissionInst.playerCores.forEach(function(node) {
node.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(node);
});
} else {
hackMissionInst.playerNodes.forEach(function(node) {
if (node.type === type) {
node.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(node);
}
});
}
}
function clearAllSelectedNodes(hackMissionInst) {
if (hackMissionInst.selectedNode.length > 0) {
hackMissionInst.selectedNode.forEach(function(node){
node.deselect(hackMissionInst.actionButtons);
});
hackMissionInst.selectedNode.length = 0;
}
}
/**
* 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
var self = this;
function selectNodeWrapper() {
selectNode(self, el);
}
el.addEventListener("click", selectNodeWrapper);
function multiselectNodeWrapper() {
multiselectNode(self, el);
}
el.addEventListener("dblclick", multiselectNodeWrapper);
if (el.firstChild) {
el.firstChild.addEventListener("click", selectNodeWrapper);
}
}
/**
* 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
var nodeObj = this.getNodeFromElement(el);
for (var i = 0; i < this.selectedNode.length; ++i) {
if (this.selectedNode[i] == nodeObj) {
nodeObj.deselect(this.actionButtons);
this.selectedNode.splice(i, 1);
break;
}
}
}
/**
* 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;}
if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;}
if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;}
if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;}
return false;
}
HackingMission.prototype.nodeReachableByEnemy = function(node) {
if (node == null) {return false;}
var x = node.pos[0], y = node.pos[1];
if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;}
if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;}
if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;}
if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;}
return false;
}
HackingMission.prototype.start = function() {
this.started = true;
this.initJsPlumb();
var startBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_9__["clearEventListeners"])("hack-mission-start-btn");
startBtn.classList.remove("a-link-button");
startBtn.classList.add("a-link-button-inactive");
}
HackingMission.prototype.initJsPlumb = function() {
var instance = jsPlumb.getInstance({
DragOptions:{cursor:"pointer", zIndex:2000},
PaintStyle: {
gradient: { stops: [
[ 0, "#FFFFFF" ],
[ 1, "#FFFFFF" ]
] },
stroke: "#FFFFFF",
strokeWidth: 8
},
});
this.jsplumbinstance = instance;
// All player cores are sources
for (var i = 0; i < this.playerCores.length; ++i) {
instance.makeSource(this.playerCores[i].el, {
deleteEndpointsOnEmpty:true,
maxConnections:1,
anchor:"Continuous",
connector:"Flowchart"
});
}
// Everything else is a target
for (var i = 0; i < this.enemyCores.length; ++i) {
instance.makeTarget(this.enemyCores[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
instance.makeTarget(this.enemyDatabases[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:["Flowchart"]
});
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
instance.makeTarget(this.enemyNodes[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
for (var i = 0; i < this.miscNodes.length; ++i) {
instance.makeTarget(this.miscNodes[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
// Clicking a connection drops it
instance.bind("click", (conn, originalEvent) => {
// Cannot drop enemy's connections
const sourceNode = this.getNodeFromElement(conn.source);
if (sourceNode.enmyCtrl) { return; }
var endpoints = conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
});
// Connection events
instance.bind("connection", (info) => {
var targetNode = this.getNodeFromElement(info.target);
// 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 (!this.nodeReachable(targetNode)) {
info.sourceEndpoint.detachFrom(info.targetEndpoint);
return;
}
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = info.connection;
var targetNode = this.getNodeFromElement(info.target);
++targetNode.targetedCount;
});
// Detach Connection events
instance.bind("connectionDetached", (info, originalEvent)=>{
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = null;
var targetNode = this.getNodeFromElement(info.target);
targetNode.untarget();
});
}
// 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) {
if (allConns[i].source == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
}
// 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) {
if (allConns[i].target == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
node.beingTargeted = false;
}
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
var res = false;
// Process actions of all player nodes
this.playerCores.forEach((node)=>{
res |= this.processNode(node, storedCycles);
});
this.playerNodes.forEach((node)=>{
if (node.type === NodeTypes.Transfer ||
node.type === NodeTypes.Shield ||
node.type === NodeTypes.Firewall) {
res |= this.processNode(node, storedCycles);
}
});
// Process actions of all enemy nodes
this.enemyCores.forEach((node)=>{
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
});
this.enemyNodes.forEach((node)=>{
if (node.type === NodeTypes.Transfer ||
node.type === NodeTypes.Shield ||
node.type === NodeTypes.Firewall) {
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
}
});
// The hp of enemy databases increases slowly
this.enemyDatabases.forEach((node)=>{
node.maxhp += (0.1 * storedCycles);
node.hp += (0.1 * storedCycles);
});
if (res) {
this.calculateAttacks();
this.calculateDefenses();
}
// Win if all enemy databases are conquered
if (this.enemyDatabases.length === 0) {
this.finishMission(true);
return;
}
// 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
this.miscNodes.forEach((node)=>{
node.def += (0.1 * storedCycles);
node.maxhp += (0.05 * storedCycles);
node.hp += (0.1 * storedCycles);
if (node.hp > node.maxhp) {node.hp = node.maxhp;}
this.updateNodeDomElement(node);
});
// Update timer and check if player lost
this.time -= (storedCycles * _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed);
if (this.time <= 0) {
this.finishMission(false);
return;
}
this.updateTimer();
storedCycles = 0;
}
// Returns a bool representing whether defenses need to be re-calculated
HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
if (nodeObj.action == null) {
return;
}
var targetNode = null, def, atk;
if (nodeObj.conn) {
if (nodeObj.conn.target != null) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
} else {
targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
}
if (targetNode == null) {
// 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
def = targetNode.def;
nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk;
}
}
// Calculations are per second, so divide everything by 5
var calcStats = false, plyr = nodeObj.plyrCtrl;
var enmyHacking = this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking;
switch(nodeObj.action) {
case NodeActions.Attack:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.hp -= (dmg/5 * numCycles);
break;
case NodeActions.Scan:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var eff = this.calculateScanEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.def -= (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Weaken:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.atk -= (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Fortify:
var eff = this.calculateFortifyEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
nodeObj.def += (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Overflow:
var eff = this.calculateOverflowEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
if (nodeObj.def < eff) {break;}
nodeObj.def -= (eff/5 * numCycles);
nodeObj.atk += (eff/5 * numCycles);
calcStats = true;
break;
default:
console.log("ERR: Invalid Node Action: " + nodeObj.action);
break;
}
// 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
if (targetNode && targetNode.hp <= 0) {
var conqueredByPlayer = nodeObj.plyrCtrl;
targetNode.hp = targetNode.maxhp;
targetNode.action = null;
targetNode.conn = null;
if (this.selectedNode == targetNode) {
targetNode.deselect(this.actionButtons);
}
// The conquered node has its stats reduced
targetNode.atk /= 2;
targetNode.def /= 3.5;
// Flag for whether the target node was a misc node
var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl;
// Remove all connections from Node
this.dropAllConnectionsToNode(targetNode);
this.dropAllConnectionsFromNode(targetNode);
// Changes the css class and turn the node into a JsPlumb Source/Target
if (conqueredByPlayer) {
targetNode.setControlledByPlayer();
this.jsplumbinstance.unmakeTarget(targetNode.el);
this.jsplumbinstance.makeSource(targetNode.el, {
deleteEndpointsOnEmpty:true,
maxConnections:1,
anchor:"Continuous",
connector:"Flowchart"
});
} else {
targetNode.setControlledByEnemy();
nodeObj.conn = null; // Clear connection
this.jsplumbinstance.unmakeSource(targetNode.el);
this.jsplumbinstance.makeTarget(targetNode.el, {
maxConnections:-1,
anchor:"Continuous",
connector:["Flowchart"]
});
}
calcStats = true;
// 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) {
var node = orig.splice(i, 1);
node = node[0];
dest.push(node);
break;
}
}
}
switch(targetNode.type) {
case NodeTypes.Core:
if (conqueredByPlayer) {
swapNodes(this.enemyCores, this.playerCores, targetNode);
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(this.playerCores, this.enemyCores, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Firewall:
if (conqueredByPlayer) {
swapNodes(this.enemyNodes, this.playerNodes, targetNode);
} else {
swapNodes(this.playerNodes, this.enemyNodes, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Database:
if (conqueredByPlayer) {
swapNodes(this.enemyDatabases, this.playerNodes, targetNode);
} else {
swapNodes(this.playerNodes, this.enemyDatabases, targetNode);
}
break;
case NodeTypes.Spam:
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
// Conquering spam node increases time limit
this.time += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease;
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
}
break;
case NodeTypes.Transfer:
// 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) {
node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
});
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
this.enemyCores.forEach(function(node) {
node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
});
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Shield:
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
}
// 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) {
node.def *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease;
}
});
}
}
// Update node DOMs
this.updateNodeDomElement(nodeObj);
if (targetNode) {this.updateNodeDomElement(targetNode);}
return calcStats;
}
// 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
*/
if (nodeObj.conn == null) {
if (this.miscNodes.length === 0) {
// Randomly pick a player node and attack it if its reachable
var rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(0, this.playerNodes.length-1);
var node;
if (this.playerNodes.length === 0) {
node = null;
} else {
node = this.playerNodes[rand];
}
if (this.nodeReachableByEnemy(node)) {
// 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
rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(0, this.playerCores.length-1);
if (this.playerCores.length === 0) {
return; // No Misc Nodes, no player Nodes, no Player cores. Player lost
} else {
node = this.playerCores[rand];
}
if (this.nodeReachableByEnemy(node)) {
// Create connection
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el
});
++node.targetedCount;
}
}
} else {
// Randomly pick a misc node and attack it if its reachable
var rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(0, this.miscNodes.length-1);
var node = this.miscNodes[rand];
if (this.nodeReachableByEnemy(node)) {
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el,
});
++node.targetedCount;
}
}
// If no connection was made, set the Core to Fortify
nodeObj.action = NodeActions.Fortify;
} else {
// If this node has a selected target
var targetNode;
if (nodeObj.conn.target) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
} else {
targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
}
if (targetNode == null) {
console.log("Error getting Target node Object in enemyAISelectAction()");
}
if (targetNode.def > this.enemyAtk + 15) {
if (nodeObj.def < 50) {
nodeObj.action = NodeActions.Fortify;
} else {
nodeObj.action = NodeActions.Overflow;
}
} else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) {
nodeObj.action = NodeActions.Scan;
} else {
nodeObj.action = NodeActions.Attack;
}
}
break;
case NodeTypes.Transfer:
// Switch between fortifying and overflowing as necessary
if (nodeObj.def < 125) {
nodeObj.action = NodeActions.Fortify;
} else {
nodeObj.action = NodeActions.Overflow;
}
break;
case NodeTypes.Firewall:
case NodeTypes.Shield:
nodeObj.action = NodeActions.Fortify;
break;
default:
break;
}
}
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
HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) {
return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1);
}
HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) {
return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2);
}
HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) {
return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2);
}
HackingMission.prototype.calculateFortifyEffect = function(hacking=0) {
return 0.9 * hacking / hackEffWeightSelf;
}
HackingMission.prototype.calculateOverflowEffect = function(hacking=0) {
return 0.95 * hacking / hackEffWeightSelf;
}
// 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
var seconds = Math.round(this.time / 1000);
var minutes = Math.trunc(seconds / 60);
seconds %= 60;
var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
timer.innerText = "Time left: " + str;
}
// The 'win' argument is a bool for whether or not the player won
HackingMission.prototype.finishMission = function(win) {
inMission = false;
currMission = null;
if (win) {
var favorMult = 1 + (this.faction.favor / 100);
console.log("Hacking mission base reward: " + this.reward);
console.log("favorMult: " + favorMult);
console.log("rep mult: " + _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult);
var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name);
_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain);
this.faction.playerReputation += gain;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation.");
}
// Clear mission container
var container = document.getElementById("mission-container");
while(container.firstChild) {
container.removeChild(container.firstChild);
}
// Return to Faction page
document.getElementById("mainmenu-container").style.visibility = "visible";
document.getElementById("character-overview-wrapper").style.visibility = "visible";
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 84)))
/***/ }),
/* 75 */
/*!************************************!*\
!*** ./src/ui/React/StdButton.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Basic stateless button
* Uses the 'std-button' css class
*/
const React = __webpack_require__(/*! react */ 1);
class StdButton extends React.Component {
render() {
const hasTooltip = this.props.tooltip != null && this.props.tooltip !== "";
let className = this.props.disabled ? "std-button-disabled" : "std-button";
if (hasTooltip) {
className += " tooltip";
}
// Tooltip will be set using inner HTML
let tooltipMarkup;
if (hasTooltip) {
tooltipMarkup = {
__html: this.props.tooltip
};
}
return (React.createElement("button", { className: className, id: this.props.id, onClick: this.props.onClick, style: this.props.style },
this.props.text,
hasTooltip &&
React.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: tooltipMarkup })));
}
}
exports.StdButton = StdButton;
/***/ }),
/* 76 */
/*!******************************************!*\
!*** ./utils/uiHelpers/removeElement.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* For a given element, this function removes it AND its children
* @param elem The element to remove.
*/
function removeElement(elem) {
if (elem === null) {
// tslint:disable-next-line:no-console
console.debug("The element passed into 'removeElement' was null.");
return;
}
if (!(elem instanceof Element)) {
// tslint:disable-next-line:no-console
console.debug("The element passed into 'removeElement' was not an instance of an Element.");
return;
}
while (elem.firstChild !== null) {
elem.removeChild(elem.firstChild);
}
if (elem.parentNode !== null) {
elem.parentNode.removeChild(elem);
}
}
exports.removeElement = removeElement;
/***/ }),
/* 77 */
/*!****************************************!*\
!*** ./utils/helpers/arrayToString.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: arrayToString */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns the input array as a comma separated string.
*
* Does several things that Array.toString() doesn't do
* - Adds brackets around the array
* - Adds quotation marks around strings
*/
function arrayToString(a) {
const vals = [];
for (let i = 0; i < a.length; ++i) {
let elem = a[i];
if (Array.isArray(elem)) {
elem = arrayToString(elem);
}
else if (typeof elem === "string") {
elem = `"${elem}"`;
}
vals.push(elem);
}
return `[${vals.join(", ")}]`;
}
exports.arrayToString = arrayToString;
/***/ }),
/* 78 */
/*!*************************************************!*\
!*** ./src/Augmentation/AugmentationHelpers.js ***!
\*************************************************/
/*! exports provided: installAugmentations, initAugmentations, applyAugmentation, augmentationExists, displayAugmentationsContent */
/*! exports used: applyAugmentation, augmentationExists, displayAugmentationsContent, initAugmentations, installAugmentations */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return installAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return augmentationExists; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayAugmentationsContent; });
/* harmony import */ var _Augmentation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentation */ 16);
/* harmony import */ var _Augmentation__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations */ 11);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentations__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PlayerOwnedAugmentation */ 125);
/* harmony import */ var _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./data/AugmentationNames */ 4);
/* harmony import */ var _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 20);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Constants */ 8);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Faction/Factions */ 13);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../NetscriptWorker */ 42);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Prestige */ 139);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../SaveObject */ 98);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Script/RunningScript */ 137);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Script_Script__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Script/Script */ 116);
/* harmony import */ var _Script_Script__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Script_Script__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Server/Server */ 105);
/* harmony import */ var _Server_Server__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Server_Server__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Settings/SettingEnums */ 53);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Settings/Settings */ 19);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../SourceFile */ 100);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../utils/uiHelpers/createAccordionElement */ 109);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../utils/JSONReviver */ 17);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 5);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../utils/helpers/clearObject */ 111);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 3);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../utils/helpers/isString */ 51);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../utils/uiHelpers/removeChildrenFromElement */ 41);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24__);
function AddToAugmentations(aug) {
var name = aug.name;
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name] = aug;
}
function initAugmentations() {
for (var name in _Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"].hasOwnProperty(name)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["Factions"][name].augmentations = [];
}
}
//Reset Augmentations
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_21__["clearObject"])(_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"]);
//Combat stat augmentations
const HemoRecirculator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator, moneyCost: 9e6, repCost:4e3,
info:"A heart implant that greatly increases the body's ability to effectively use and pump " +
"blood.
" +
"This augmentation increases all of the player's combat stats by 8%.",
strength_mult: 1.08,
defense_mult: 1.08,
agility_mult: 1.08,
dexterity_mult: 1.08,
});
HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator];
}
AddToAugmentations(HemoRecirculator);
const Targeting1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1, moneyCost:3e6, repCost:2e3,
info:"This cranial implant is embedded within the player's inner ear structure and optic nerves. It regulates and enhances the user's " +
"balance and hand-eye coordination. It is also capable of augmenting reality by projecting digital information " +
"directly onto the retina. These enhancements allow the player to better lock-on and keep track of enemies.
" +
"This augmentation increases the player's dexterity by 10%.",
dexterity_mult: 1.1,
});
Targeting1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1];
}
AddToAugmentations(Targeting1);
const Targeting2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2, moneyCost:8.5e6, repCost:3.5e3,
info:"This is an upgrade of the Augmented Targeting I cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.
" +
"This augmentation increases the player's dexterity by 20%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1],
dexterity_mult: 1.2,
});
Targeting2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2];
}
AddToAugmentations(Targeting2);
const Targeting3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3, moneyCost:23e6, repCost:11e3,
info:"This is an upgrade of the Augmented Targeting II cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.
" +
"This augmentation increases the player's dexterity by 30%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2],
dexterity_mult: 1.3,
});
Targeting3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3];
}
AddToAugmentations(Targeting3);
const SyntheticHeart = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart, moneyCost:575e6, repCost:300e3,
info:"This advanced artificial heart, created from plasteel and graphene, is capable of pumping more blood " +
"at much higher efficiencies than a normal human heart.
" +
"This augmentation increases the player's agility and strength by 50%.",
agility_mult: 1.5,
strength_mult: 1.5,
});
SyntheticHeart.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart];
}
AddToAugmentations(SyntheticHeart);
const SynfibrilMuscle = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle, repCost:175e3, moneyCost:225e6,
info:"The myofibrils in human muscles are injected with special chemicals that react with the proteins inside " +
"the myofibrils, altering their underlying structure. The end result is muscles that are stronger and more elastic. " +
"Scientists have named these artificially enhanced units 'synfibrils'.
" +
"This augmentation increases the player's strength and defense by 30%.",
strength_mult: 1.3,
defense_mult: 1.3,
});
SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle];
}
AddToAugmentations(SynfibrilMuscle)
const CombatRib1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1, repCost:3e3, moneyCost:4750000,
info:"The human body's ribs are replaced with artificial ribs that automatically and continuously release cognitive " +
"and performance-enhancing drugs into the bloodstream, improving the user's abilities in combat.
" +
"This augmentation increases the player's strength and defense by 10%.",
strength_mult: 1.1,
defense_mult: 1.1,
});
CombatRib1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1];
}
AddToAugmentations(CombatRib1);
const CombatRib2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2, repCost:7.5e3, moneyCost:13e6,
info:"This is an upgrade to the Combat Rib I augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream.
" +
"This augmentation increases the player's strength and defense by 14%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1],
strength_mult: 1.14,
defense_mult: 1.14,
});
CombatRib2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2];
}
AddToAugmentations(CombatRib2);
const CombatRib3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3, repCost:14e3, moneyCost:24e6,
info:"This is an upgrade to the Combat Rib II augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream
." +
"This augmentation increases the player's strength and defense by 18%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2],
strength_mult: 1.18,
defense_mult: 1.18,
});
CombatRib3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3];
}
AddToAugmentations(CombatRib3);
const NanofiberWeave = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave, repCost:15e3, moneyCost:25e6,
info:"Synthetic nanofibers are woven into the skin's extracellular matrix using electrospinning. " +
"This improves the skin's ability to regenerate itself and protect the body from external stresses and forces.
" +
"This augmentation increases the player's strength and defense by 20%.",
strength_mult: 1.2,
defense_mult: 1.2,
});
NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead",
"Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave];
}
AddToAugmentations(NanofiberWeave);
const SubdermalArmor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor, repCost:350e3, moneyCost:650e6,
info:"The NEMEAN Subdermal Weave is a thin, light-weight, graphene plating that houses a dilatant fluid. " +
"The material is implanted underneath the skin, and is the most advanced form of defensive enhancement " +
"that has ever been created. The dilatant fluid, despite being thin and light, is extremely effective " +
"at stopping piercing blows and reducing blunt trauma. The properties of graphene allow the plating to " +
"mitigate damage from any fire-related or electrical traumas.
" +
"This augmentation increases the player's defense by 120%.",
defense_mult: 2.2,
});
SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus",
"The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor];
}
AddToAugmentations(SubdermalArmor);
const WiredReflexes = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes, repCost:500, moneyCost:500e3,
info:"Synthetic nerve-enhancements are injected into all major parts of the somatic nervous system, " +
"supercharging the body's ability to send signals through neurons. This results in increased reflex speed.
" +
"This augmentation increases the player's agility and dexterity by 5%.",
agility_mult: 1.05,
dexterity_mult: 1.05,
});
WiredReflexes.addToFactions(["Tian Di Hui", "Slum Snakes", "Sector-12", "Volhaven", "Aevum", "Ishima",
"The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes];
}
AddToAugmentations(WiredReflexes);
const GrapheneBoneLacings = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings, repCost:450e3, moneyCost:850e6,
info:"A graphene-based material is grafted and fused into the user's bones, significantly increasing " +
"their density and tensile strength.
" +
"This augmentation increases the player's strength and defense by 70%.",
strength_mult: 1.7,
defense_mult: 1.7,
});
GrapheneBoneLacings.addToFactions(["Fulcrum Secret Technologies", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings];
}
AddToAugmentations(GrapheneBoneLacings);
const BionicSpine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine, repCost:18e3, moneyCost:25e6,
info:"An artificial spine created from plasteel and carbon fibers that completely replaces the organic spine. " +
"Not only is the Bionic Spine physically stronger than a human spine, but it is also capable of digitally " +
"stimulating and regulating the neural signals that are sent and received by the spinal cord. This results in " +
"greatly improved senses and reaction speeds.
" +
"This augmentation increases all of the player's combat stats by 15%.",
strength_mult: 1.15,
defense_mult: 1.15,
agility_mult: 1.15,
dexterity_mult: 1.15,
});
BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine];
}
AddToAugmentations(BionicSpine);
const GrapheneBionicSpine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine, repCost:650e3, moneyCost:1200e6,
info:"An upgrade to the Bionic Spine augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.
" +
"This augmentation increases all of the player's combat stats by 60%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine],
strength_mult: 1.6,
defense_mult: 1.6,
agility_mult: 1.6,
dexterity_mult: 1.6,
});
GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine];
}
AddToAugmentations(GrapheneBionicSpine);
const BionicLegs = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs, repCost:60e3, moneyCost:75e6,
info:"Cybernetic legs created from plasteel and carbon fibers that completely replace the user's organic legs.
" +
"This augmentation increases the player's agility by 60%.",
agility_mult: 1.6,
});
BionicLegs.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs];
}
AddToAugmentations(BionicLegs);
const GrapheneBionicLegs = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs, repCost:300e3, moneyCost:900e6,
info:"An upgrade to the Bionic Legs augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.
" +
"This augmentation increases the player's agility by 150%.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs],
agility_mult: 2.5,
});
GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs];
}
AddToAugmentations(GrapheneBionicLegs);
// Work stat augmentations
const SpeechProcessor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor, repCost:3e3, moneyCost:10e6,
info:"A cochlear implant with an embedded computer that analyzes incoming speech. " +
"The embedded computer processes characteristics of incoming speech, such as tone " +
"and inflection, to pick up on subtle cues and aid in social interactions.
" +
"This augmentation increases the player's charisma by 20%.",
charisma_mult: 1.2,
});
SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Silhouette"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor];
}
AddToAugmentations(SpeechProcessor);
const TITN41Injection = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection, repCost:10e3, moneyCost:38e6,
info:"TITN is a series of viruses that targets and alters the sequences of human DNA in genes that " +
"control personality. The TITN-41 strain alters these genes so that the subject becomes more " +
"outgoing and socialable.
" +
"This augmentation increases the player's charisma and charisma experience gain rate by 15%.",
charisma_mult: 1.15,
charisma_exp_mult: 1.15,
});
TITN41Injection.addToFactions(["Silhouette"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection];
}
AddToAugmentations(TITN41Injection);
const EnhancedSocialInteractionImplant = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant, repCost:150e3, moneyCost:275e6,
info:"A cranial implant that greatly assists in the user's ability to analyze social situations " +
"and interactions. The system uses a wide variety of factors such as facial expression, body " +
"language, and the voice's tone/inflection to determine the best course of action during social" +
"situations. The implant also uses deep learning software to continuously learn new behavior" +
"patterns and how to best respond.
" +
"This augmentation increases the player's charisma and charisma experience gain rate by 60%.",
charisma_mult: 1.6,
charisma_exp_mult: 1.6,
});
EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant];
}
AddToAugmentations(EnhancedSocialInteractionImplant);
// Hacking augmentations
const BitWire = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire, repCost:1500, moneyCost:2e6,
info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " +
"capabilities.
" +
"This augmentation increases the player's hacking skill by 5%.",
hacking_mult: 1.05,
});
BitWire.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire];
}
AddToAugmentations(BitWire);
const ArtificialBioNeuralNetwork = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork, repCost:110e3, moneyCost:600e6,
info:"A network consisting of millions of nanoprocessors is embedded into the brain. " +
"The network is meant to mimick the way a biological brain solves a problem, which each " +
"nanoprocessor acting similar to the way a neuron would in a neural network. However, these " +
"nanoprocessors are programmed to perform computations much faster than organic neurons, " +
"allowing its user to solve much more complex problems at a much faster rate.
" +
"This augmentation: " +
"Increases the player's hacking speed by 3%. " +
"Increases the amount of money the player's gains from hacking by 15%. " +
"Increases the player's hacking skill by 12%.",
hacking_speed_mult: 1.03,
hacking_money_mult: 1.15,
hacking_mult: 1.12,
});
ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork];
}
AddToAugmentations(ArtificialBioNeuralNetwork);
const ArtificialSynapticPotentiation = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation, repCost:2500, moneyCost:16e6,
info:"The body is injected with a chemical that artificially induces synaptic potentiation, " +
"otherwise known as the strengthening of synapses. This results in a enhanced cognitive abilities.
" +
"This augmentation: " +
"Increases the player's hacking speed by 2% " +
"Increases the player's hacking chance by 5%. " +
"Increases the player's hacking experience gain rate by 5%.",
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.05,
hacking_exp_mult: 1.05,
});
ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation];
}
AddToAugmentations(ArtificialSynapticPotentiation);
const EnhancedMyelinSheathing = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing, repCost:40e3, moneyCost:275e6,
info:"Electrical signals are used to induce a new, artificial form of myelinogensis in the human body. " +
"This process results in the proliferation of new, synthetic myelin sheaths in the nervous " +
"system. These myelin sheaths can propogate neuro-signals much faster than their organic " +
"counterparts, leading to greater processing speeds and better brain function.
" +
"This augmentation: " +
"Increases the player's hacking speed by 3%. " +
"Increases the player's hacking skill by 8%. " +
"Increases the player's hacking experience gain rate by 10%.",
hacking_speed_mult: 1.03,
hacking_exp_mult: 1.1,
hacking_mult: 1.08,
});
EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing];
}
AddToAugmentations(EnhancedMyelinSheathing);
const SynapticEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement, repCost:800, moneyCost:1.5e6,
info:"A small cranial implant that continuously uses weak electric signals to stimulate the brain and " +
"induce stronger synaptic activity. This improves the user's cognitive abilities.
" +
"This augmentation increases the player's hacking speed by 3%.",
hacking_speed_mult: 1.03,
});
SynapticEnhancement.addToFactions(["CyberSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement];
}
AddToAugmentations(SynapticEnhancement);
const NeuralRetentionEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement, repCost:8e3, moneyCost:50e6,
info:"Chemical injections are used to permanently alter and strengthen the brain's neuronal " +
"circuits, strengthening its ability to retain information.
" +
"This augmentation increases the player's hacking experience gain rate by 25%.",
hacking_exp_mult: 1.25,
});
NeuralRetentionEnhancement.addToFactions(["NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement];
}
AddToAugmentations(NeuralRetentionEnhancement);
const DataJack = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack, repCost:45e3, moneyCost:90e6,
info:"A brain implant that provides an interface for direct, wireless communication between a computer's main " +
"memory and the mind. This implant allows the user to not only access a computer's memory, but also alter " +
"and delete it.
" +
"This augmentation increases the amount of money the player gains from hacking by 25%.",
hacking_money_mult: 1.25,
});
DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack];
}
AddToAugmentations(DataJack);
const ENM = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM, repCost:6e3, moneyCost:50e6,
info:"A thin device embedded inside the arm containing a wireless module capable of connecting " +
"to nearby networks. Once connected, the Netburner Module is capable of capturing and " +
"processing all of the traffic on that network. By itself, the Embedded Netburner Module does " +
"not do much, but a variety of very powerful upgrades can be installed that allow you to fully " +
"control the traffic on a network.
" +
"This augmentation increases the player's hacking skill by 8%.",
hacking_mult: 1.08,
});
ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM];
}
AddToAugmentations(ENM);
const ENMCore = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore, repCost:100e3, moneyCost:500e6,
info:"The Core library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgrade allows the Embedded Netburner Module to generate its own data on a network.
" +
"This augmentation: " +
"Increases the player's hacking speed by 3%. " +
"Increases the amount of money the player gains from hacking by 10%. " +
"Increases the player's chance of successfully performing a hack by 3%. " +
"Increases the player's hacking experience gain rate by 7%. " +
"Increases the player's hacking skill by 7%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_speed_mult: 1.03,
hacking_money_mult: 1.1,
hacking_chance_mult: 1.03,
hacking_exp_mult: 1.07,
hacking_mult: 1.07,
});
ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore];
}
AddToAugmentations(ENMCore);
const ENMCoreV2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2, repCost:400e3, moneyCost:900e6,
info:"The Core V2 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to control the information on " +
"a network by re-routing traffic, spoofing IP addresses, or altering the data inside network " +
"packets.
" +
"This augmentation: " +
"Increases the player's hacking speed by 5%. " +
"Increases the amount of money the player gains from hacking by 30%. " +
"Increases the player's chance of successfully performing a hack by 5%. " +
"Increases the player's hacking experience gain rate by 15%. " +
"Increases the player's hacking skill by 8%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore],
hacking_speed_mult: 1.05,
hacking_money_mult: 1.3,
hacking_chance_mult: 1.05,
hacking_exp_mult: 1.15,
hacking_mult: 1.08,
});
ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Blade Industries", "OmniTek Incorporated", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2];
}
AddToAugmentations(ENMCoreV2);
const ENMCoreV3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3, repCost:700e3, moneyCost:1500e6,
info:"The Core V3 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to seamlessly inject code into " +
"any device on a network.
" +
"This augmentation: " +
"Increases the player's hacking speed by 5%. " +
"Increases the amount of money the player gains from hacking by 40%. " +
"Increases the player's chance of successfully performing a hack by 10%. " +
"Increases the player's hacking experience gain rate by 25%. " +
"Increases the player's hacking skill by 10%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2],
hacking_speed_mult: 1.05,
hacking_money_mult: 1.4,
hacking_chance_mult: 1.1,
hacking_exp_mult: 1.25,
hacking_mult: 1.1,
});
ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3];
}
AddToAugmentations(ENMCoreV3);
const ENMAnalyzeEngine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine, repCost:250e3, moneyCost:1200e6,
info:"Installs the Analyze Engine for the Embedded Netburner Module, which is a CPU cluster " +
"that vastly outperforms the Netburner Module's native single-core processor.
" +
"This augmentation increases the player's hacking speed by 10%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_speed_mult: 1.1,
});
ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine];
}
AddToAugmentations(ENMAnalyzeEngine);
const ENMDMA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA, repCost:400e3, moneyCost:1400e6,
info:"This implant installs a Direct Memory Access (DMA) controller into the " +
"Embedded Netburner Module. This allows the Module to send and receive data " +
"directly to and from the main memory of devices on a network.
" +
"This augmentation: " +
"Increases the amount of money the player gains from hacking by 40%. " +
"Increases the player's chance of successfully performing a hack by 20%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_money_mult: 1.4,
hacking_chance_mult: 1.2,
});
ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA];
}
AddToAugmentations(ENMDMA);
const Neuralstimulator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator, repCost:20e3, moneyCost:600e6,
info:"A cranial implant that intelligently stimulates certain areas of the brain " +
"in order to improve cognitive functions.
" +
"This augmentation: " +
"Increases the player's hacking speed by 2%. " +
"Increases the player's chance of successfully performing a hack by 10%. " +
"Increases the player's hacking experience gain rate by 12%.",
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.1,
hacking_exp_mult: 1.12,
});
Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated",
"Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator];
}
AddToAugmentations(Neuralstimulator);
const NeuralAccelerator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator, repCost:80e3, moneyCost:350e6,
info:"A microprocessor that accelerates the processing " +
"speed of biological neural networks. This is a cranial implant that is embedded inside the brain.
" +
"This augmentation: " +
"Increases the player's hacking skill by 10%. " +
"Increases the player's hacking experience gain rate by 15%. " +
"Increases the amount of money the player gains from hacking by 20%.",
hacking_mult: 1.1,
hacking_exp_mult: 1.15,
hacking_money_mult: 1.2,
});
NeuralAccelerator.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator];
}
AddToAugmentations(NeuralAccelerator);
const CranialSignalProcessorsG1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1, repCost:4e3, moneyCost:14e6,
info:"The first generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation: " +
"Increases the player's hacking speed by 1%. " +
"Increases the player's hacking skill by 5%.",
hacking_speed_mult: 1.01,
hacking_mult: 1.05,
});
CranialSignalProcessorsG1.addToFactions(["CyberSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1];
}
AddToAugmentations(CranialSignalProcessorsG1);
const CranialSignalProcessorsG2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2, repCost:7500, moneyCost:25e6,
info:"The second generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation: " +
"Increases the player's hacking speed by 2%. " +
"Increases the player's chance of successfully performing a hack by 5%. " +
"Increases the player's hacking skill by 7%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1],
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.05,
hacking_mult: 1.07,
});
CranialSignalProcessorsG2.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2];
}
AddToAugmentations(CranialSignalProcessorsG2);
const CranialSignalProcessorsG3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3, repCost:20e3, moneyCost:110e6,
info:"The third generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation: " +
"Increases the player's hacking speed by 2%. " +
"Increases the amount of money the player gains from hacking by 15%. " +
"Increases the player's hacking skill by 9%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2],
hacking_speed_mult: 1.02,
hacking_money_mult: 1.15,
hacking_mult: 1.09,
});
CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand", "BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3];
}
AddToAugmentations(CranialSignalProcessorsG3);
const CranialSignalProcessorsG4 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4, repCost:50e3, moneyCost:220e6,
info:"The fourth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation: " +
"Increases the player's hacking speed by 2%. " +
"Increases the amount of money the player gains from hacking by 20%. " +
"Increases the amount of money the player can inject into servers using grow() by 25%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3],
hacking_speed_mult: 1.02,
hacking_money_mult: 1.2,
hacking_grow_mult: 1.25,
});
CranialSignalProcessorsG4.addToFactions(["The Black Hand", "BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4];
}
AddToAugmentations(CranialSignalProcessorsG4);
const CranialSignalProcessorsG5 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5, repCost:100e3, moneyCost:450e6,
info:"The fifth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation: " +
"Increases the player's hacking skill by 30%. " +
"Increases the amount of money the player gains from hacking by 25%. " +
"Increases the amount of money the player can inject into servers using grow() by 75%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4],
hacking_mult: 1.3,
hacking_money_mult: 1.25,
hacking_grow_mult: 1.75,
});
CranialSignalProcessorsG5.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5];
}
AddToAugmentations(CranialSignalProcessorsG5);
const NeuronalDensification = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification, repCost:75e3, moneyCost:275e6,
info:"The brain is surgically re-engineered to have increased neuronal density " +
"by decreasing the neuron gap junction. Then, the body is genetically modified " +
"to enhance the production and capabilities of its neural stem cells.
" +
"This augmentation: " +
"Increases the player's hacking skill by 15%. " +
"Increases the player's hacking experience gain rate by 10%. "+
"Increases the player's hacking speed by 3%.",
hacking_mult: 1.15,
hacking_exp_mult: 1.1,
hacking_speed_mult: 1.03,
});
NeuronalDensification.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification];
}
AddToAugmentations(NeuronalDensification);
// Work Augmentations
const NuoptimalInjectorImplant = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant, repCost:2e3, moneyCost:4e6,
info:"This torso implant automatically injects nootropic supplements into " +
"the bloodstream to improve memory, increase focus, and provide other " +
"cognitive enhancements.
" +
"This augmentation increases the amount of reputation the player gains " +
"when working for a company by 20%.",
company_rep_mult: 1.2,
});
NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Ishima",
"Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant];
}
AddToAugmentations(NuoptimalInjectorImplant);
const SpeechEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement, repCost:1e3, moneyCost:2.5e6,
info:"An advanced neural implant that improves your speaking abilities, making " +
"you more convincing and likable in conversations and overall improving your " +
"social interactions.
" +
"This augmentation: " +
"Increases the player's charisma by 10%. " +
"Increases the amount of reputation the player gains when working for a company by 10%.",
company_rep_mult: 1.1,
charisma_mult: 1.1,
});
SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International",
"Clarke Incorporated", "Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement];
}
AddToAugmentations(SpeechEnhancement);
const FocusWire = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire, repCost:30e3, moneyCost:180e6,
info:"A cranial implant that stops procrastination by blocking specific neural pathways " +
"in the brain.
" +
"This augmentation: " +
"Increases all experience gains by 5%. " +
"Increases the amount of money the player gains from working by 20%. " +
"Increases the amount of reputation the player gains when working for a company by 10%.",
hacking_exp_mult: 1.05,
strength_exp_mult: 1.05,
defense_exp_mult: 1.05,
dexterity_exp_mult: 1.05,
agility_exp_mult: 1.05,
charisma_exp_mult: 1.05,
company_rep_mult: 1.1,
work_money_mult: 1.2,
});
FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire];
}
AddToAugmentations(FocusWire)
const PCDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI, repCost:150e3, moneyCost:750e6,
info:"Installs a Direct-Neural Interface jack into your arm that is compatible with most " +
"computers. Connecting to a computer through this jack allows you to interface with " +
"it using the brain's electrochemical signals.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains when working for a company by 30%. " +
"Increases the player's hacking skill by 8%.",
company_rep_mult: 1.3,
hacking_mult: 1.08,
});
PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI];
}
AddToAugmentations(PCDNI);
const PCDNIOptimizer = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer, repCost:200e3, moneyCost:900e6,
info:"This is a submodule upgrade to the PC Direct-Neural Interface augmentation. It " +
"improves the performance of the interface and gives the user more control options " +
"to the connected computer.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains when working for a company by 75%. " +
"Increases the player's hacking skill by 10%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI],
company_rep_mult: 1.75,
hacking_mult: 1.1,
});
PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer];
}
AddToAugmentations(PCDNIOptimizer);
const PCDNINeuralNetwork = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork, repCost:600e3, moneyCost:1500e6,
info:"This is an additional installation that upgrades the functionality of the " +
"PC Direct-Neural Interface augmentation. When connected to a computer, " +
"The NeuroNet Injector upgrade allows the user to use his/her own brain's " +
"processing power to aid the computer in computational tasks.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains when working for a company by 100%. " +
"Increases the player's hacking skill by 10%. " +
"Increases the player's hacking speed by 5%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI],
company_rep_mult: 2,
hacking_mult: 1.1,
hacking_speed_mult: 1.05,
});
PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork];
}
AddToAugmentations(PCDNINeuralNetwork);
const ADRPheromone1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1, repCost:1500, moneyCost:3.5e6,
info:"The body is genetically re-engineered so that it produces the ADR-V1 pheromone, " +
"an artificial pheromone discovered by scientists. The ADR-V1 pheromone, when excreted, " +
"triggers feelings of admiration and approval in other people.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains when working for a company by 10% " +
"Increases the amount of reputation the player gains for a faction by 10%.",
company_rep_mult: 1.1,
faction_rep_mult: 1.1,
});
ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1];
}
AddToAugmentations(ADRPheromone1);
const ADRPheromone2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2, repCost:25e3, moneyCost:110e6,
info:"The body is genetically re-engineered so that it produces the ADR-V2 pheromone, " +
"which is similar to but more potent than ADR-V1. This pheromone, when excreted, " +
"triggers feelings of admiration, approval, and respect in others.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains for a faction and company by 20%.",
company_rep_mult: 1.2,
faction_rep_mult: 1.2,
});
ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2];
}
AddToAugmentations(ADRPheromone2);
const ShadowsSimulacrum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum, repCost: 15e3, moneyCost: 80e6,
info: "A crude but functional matter phase-shifter module that is embedded " +
"in the brainstem and cerebellum. This augmentation was developed by " +
"criminal organizations and allows the user to project and control holographic " +
"simulacrums within a large radius. These simulacrums are commonly used for " +
"espionage and surveillance work.
" +
"This augmentation: " +
"Increases the amount of reputation the player gains when working for a faction or company by 15%.",
company_rep_mult: 1.15,
faction_rep_mult: 1.15,
});
ShadowsSimulacrum.addToFactions(["The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum];
}
AddToAugmentations(ShadowsSimulacrum);
// HacknetNode Augmentations
const HacknetNodeCPUUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload, repCost:1500, moneyCost:2.2e6,
info:"Uploads the architecture and design details of a Hacknet Node's CPU into " +
"the brain. This allows the user to engineer custom hardware and software " +
"for the Hacknet Node that provides better performance.
" +
"This augmentation: " +
"Increases the amount of money produced by Hacknet Nodes by 15%. " +
"Decreases the cost of purchasing a Hacknet Node by 15%.",
hacknet_node_money_mult: 1.15,
hacknet_node_purchase_cost_mult: 0.85,
});
HacknetNodeCPUUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload];
}
AddToAugmentations(HacknetNodeCPUUpload);
const HacknetNodeCacheUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload, repCost:1e3, moneyCost:1.1e6,
info:"Uploads the architecture and design details of a Hacknet Node's main-memory cache " +
"into the brain. This allows the user to engineer custom cache hardware for the " +
"Hacknet Node that offers better performance.
" +
"This augmentation: " +
"Increases the amount of money produced by Hacknet Nodes by 10%. " +
"Decreases the cost of leveling up a Hacknet Node by 15%.",
hacknet_node_money_mult: 1.10,
hacknet_node_level_cost_mult: 0.85,
});
HacknetNodeCacheUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload];
}
AddToAugmentations(HacknetNodeCacheUpload);
const HacknetNodeNICUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload, repCost:750, moneyCost:900e3,
info:"Uploads the architecture and design details of a Hacknet Node's Network Interface Card (NIC) " +
"into the brain. This allows the user to engineer a custom NIC for the Hacknet Node that " +
"offers better performance.
" +
"This augmentation: " +
"Increases the amount of money produced by Hacknet Nodes by 10%. " +
"Decreases the cost of purchasing a Hacknet Node by 10%.",
hacknet_node_money_mult: 1.1,
hacknet_node_purchase_cost_mult: 0.9,
});
HacknetNodeNICUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload];
}
AddToAugmentations(HacknetNodeNICUpload);
const HacknetNodeKernelDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI, repCost:3e3, moneyCost:8e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting to a " +
"Hacknet Node. This lets the user access and manipulate the Node's kernel using the mind's " +
"electrochemical signals.
" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 25%.",
hacknet_node_money_mult: 1.25,
});
HacknetNodeKernelDNI.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI];
}
AddToAugmentations(HacknetNodeKernelDNI);
const HacknetNodeCoreDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI, repCost:5e3, moneyCost:12e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting " +
"to a Hacknet Node. This lets the user access and manipulate the Node's processing logic using " +
"the mind's electrochemical signals.
" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 45%.",
hacknet_node_money_mult: 1.45,
});
HacknetNodeCoreDNI.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI];
}
AddToAugmentations(HacknetNodeCoreDNI);
//Misc/Hybrid augmentations
const NeuroFluxGovernor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor, repCost:500, moneyCost: 750e3,
info:"A device that is embedded in the back of the neck. The NeuroFlux Governor " +
"monitors and regulates nervous impulses coming to and from the spinal column, " +
"essentially 'governing' the body. By doing so, it improves the functionality of the " +
"body's nervous system.
" +
"This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " +
"increases ALL of the player's multipliers by 1%.",
hacking_chance_mult: 1.01,
hacking_speed_mult: 1.01,
hacking_money_mult: 1.01,
hacking_grow_mult: 1.01,
hacking_mult: 1.01,
strength_mult: 1.01,
defense_mult: 1.01,
dexterity_mult: 1.01,
agility_mult: 1.01,
charisma_mult: 1.01,
hacking_exp_mult: 1.01,
strength_exp_mult: 1.01,
defense_exp_mult: 1.01,
dexterity_exp_mult: 1.01,
agility_exp_mult: 1.01,
charisma_exp_mult: 1.01,
company_rep_mult: 1.01,
faction_rep_mult: 1.01,
crime_money_mult: 1.01,
crime_success_mult: 1.01,
hacknet_node_money_mult: 1.01,
hacknet_node_purchase_cost_mult: 0.99,
hacknet_node_ram_cost_mult: 0.99,
hacknet_node_core_cost_mult: 0.99,
hacknet_node_level_cost_mult: 0.99,
work_money_mult: 1.01,
});
// Set the Augmentation's level to the currently-installed level
let currLevel = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].level;
}
}
NeuroFluxGovernor.level = currLevel;
// To set the price/rep req of the NeuroFlux, we have to take into account NeuroFlux
// levels that are purchased but not yet installed
let nextLevel = currLevel;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
++nextLevel;
}
}
let mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].AugmentationRepCost;
NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].AugmentationMoneyCost;
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor];
}
NeuroFluxGovernor.addToAllFactions();
AddToAugmentations(NeuroFluxGovernor);
const Neurotrainer1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1, repCost:400, moneyCost:800e3,
info:"A decentralized cranial implant that improves the brain's ability to learn. It is " +
"installed by releasing millions of nanobots into the human brain, each of which " +
"attaches to a different neural pathway to enhance the brain's ability to retain " +
"and retrieve information.
" +
"This augmentation increases the player's experience gain rate for all stats by 10%.",
hacking_exp_mult: 1.1,
strength_exp_mult: 1.1,
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
agility_exp_mult: 1.1,
charisma_exp_mult: 1.1,
});
Neurotrainer1.addToFactions(["CyberSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1];
}
AddToAugmentations(Neurotrainer1);
const Neurotrainer2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2, repCost:4e3, moneyCost:9e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I augmentation, but it does not " +
"require Neurotrainer I to be installed as a prerequisite.
" +
"This augmentation increases the player's experience gain rate for all stats by 15%.",
hacking_exp_mult: 1.15,
strength_exp_mult: 1.15,
defense_exp_mult: 1.15,
dexterity_exp_mult: 1.15,
agility_exp_mult: 1.15,
charisma_exp_mult: 1.15,
});
Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2];
}
AddToAugmentations(Neurotrainer2);
const Neurotrainer3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3, repCost:10e3, moneyCost:26e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I and Neurotrainer II augmentation, " +
"but it does not require either of them to be installed as a prerequisite.
" +
"This augmentation increases the player's experience gain rate for all stats by 20%.",
hacking_exp_mult: 1.2,
strength_exp_mult: 1.2,
defense_exp_mult: 1.2,
dexterity_exp_mult: 1.2,
agility_exp_mult: 1.2,
charisma_exp_mult: 1.2,
});
Neurotrainer3.addToFactions(["NWO", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3];
}
AddToAugmentations(Neurotrainer3);
const Hypersight = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight, repCost:60e3, moneyCost:550e6,
info:"A bionic eye implant that grants sight capabilities far beyond those of a natural human. " +
"Embedded circuitry within the implant provides the ability to detect heat and movement " +
"through solid objects such as wells, thus providing 'x-ray vision'-like capabilities.
" +
"This augmentation: " +
"Increases the player's dexterity by 40%. " +
"Increases the player's hacking speed by 3%. " +
"Increases the amount of money the player gains from hacking by 10%.",
dexterity_mult: 1.4,
hacking_speed_mult: 1.03,
hacking_money_mult: 1.1,
});
Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight];
}
AddToAugmentations(Hypersight);
const LuminCloaking1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1, repCost:600, moneyCost:1e6,
info:"A skin implant that reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, have a negative refractive index. As a result, they bend light " +
"around the skin, making the user much harder to see from the naked eye.
" +
"This augmentation: " +
"Increases the player's agility by 5% " +
"Increases the amount of money the player gains from crimes by 10%.",
agility_mult: 1.05,
crime_money_mult: 1.1,
});
LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1];
}
AddToAugmentations(LuminCloaking1);
const LuminCloaking2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2, repCost:2e3, moneyCost:6e6,
info:"This is a more advanced version of the LuminCloaking-V2 augmentation. This skin implant " +
"reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, are capable of not only bending light but also of bending heat, " +
"making the user more resilient as well as stealthy.
" +
"This augmentation: " +
"Increases the player's agility by 10% " +
"Increases the player's defense by 10% " +
"Increases the amount of money the player gains from crimes by 25%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1],
agility_mult: 1.1,
defense_mult: 1.1,
crime_money_mult: 1.25,
});
LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2];
}
AddToAugmentations(LuminCloaking2);
const SmartSonar = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar, repCost:9e3, moneyCost:15e6,
info:"A cochlear implant that helps the player detect and locate enemies " +
"using sound propagation.
" +
"This augmentation: " +
"Increases the player's dexterity by 10%. " +
"Increases the player's dexterity experience gain rate by 15%. " +
"Increases the amount of money the player gains from crimes by 25%.",
dexterity_mult: 1.1,
dexterity_exp_mult: 1.15,
crime_money_mult: 1.25,
});
SmartSonar.addToFactions(["Slum Snakes"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar];
}
AddToAugmentations(SmartSonar);
const PowerRecirculator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator, repCost:10e3, moneyCost:36e6,
info:"The body's nerves are attached with polypyrrole nanocircuits that " +
"are capable of capturing wasted energy (in the form of heat) " +
"and converting it back into usable power.
" +
"This augmentation: " +
"Increases all of the player's stats by 5%. " +
"Increases the player's experience gain rate for all stats by 10%.",
hacking_mult: 1.05,
strength_mult: 1.05,
defense_mult: 1.05,
dexterity_mult: 1.05,
agility_mult: 1.05,
charisma_mult: 1.05,
hacking_exp_mult: 1.1,
strength_exp_mult: 1.1,
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
agility_exp_mult: 1.1,
charisma_exp_mult: 1.1,
});
PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator];
}
AddToAugmentations(PowerRecirculator);
// Unique AUGS (Each Faction gets one unique augmentation)
// Factions that already have unique augs up to this point:
// Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies,
// Silhouette
// Illuminati
const QLink = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink, repCost:750e3, moneyCost:5e12,
info:"A brain implant that wirelessly connects you to the Illuminati's " +
"quantum supercomputer, allowing you to access and use its incredible " +
"computing power.
" +
"This augmentation: " +
"Increases the player's hacking skill by 75%. " +
"Increases the player's hacking speed by 100%. " +
"Increases the player's chance of successfully performing a hack by 150%. " +
"Increases the amount of money the player gains from hacking by 300%.",
hacking_mult: 1.75,
hacking_speed_mult: 2,
hacking_chance_mult: 2.5,
hacking_money_mult: 4,
});
QLink.addToFactions(["Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink];
}
AddToAugmentations(QLink);
// Daedalus
const RedPill = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill, repCost:1e6, moneyCost:0,
info:"It's time to leave the cave."
});
RedPill.addToFactions(["Daedalus"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill];
}
AddToAugmentations(RedPill);
// Covenant
const SPTN97 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97, repCost:500e3, moneyCost:975e6,
info:"The SPTN-97 gene is injected into the genome. The SPTN-97 gene is an " +
"artificially-synthesized gene that was developed by DARPA to create " +
"super-soldiers through genetic modification. The gene was outlawed in " +
"2056.
" +
"This augmentation: " +
"Increases all of the player's combat stats by 75%. " +
"Increases the player's hacking skill by 15%.",
strength_mult: 1.75,
defense_mult: 1.75,
dexterity_mult: 1.75,
agility_mult: 1.75,
hacking_mult: 1.15,
});
SPTN97.addToFactions(["The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97];
}
AddToAugmentations(SPTN97);
// ECorp
const HiveMind = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind, repCost:600e3, moneyCost:1100e6,
info:"A brain implant developed by ECorp. They do not reveal what " +
"exactly the implant does, but they promise that it will greatly " +
"enhance your abilities.",
hacking_grow_mult: 3,
});
HiveMind.addToFactions(["ECorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind];
}
AddToAugmentations(HiveMind);
// MegaCorp
const CordiARCReactor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor, repCost:450e3, moneyCost:1000e6,
info:"The thoracic cavity is equipped with a small chamber designed " +
"to hold and sustain hydrogen plasma. The plasma is used to generate " +
"fusion power through nuclear fusion, providing limitless amount of clean " +
"energy for the body.
" +
"This augmentation: " +
"Increases all of the player's combat stats by 35%. " +
"Increases all of the player's combat stat experience gain rate by 35%.",
strength_mult: 1.35,
defense_mult: 1.35,
dexterity_mult: 1.35,
agility_mult: 1.35,
strength_exp_mult: 1.35,
defense_exp_mult: 1.35,
dexterity_exp_mult: 1.35,
agility_exp_mult: 1.35,
});
CordiARCReactor.addToFactions(["MegaCorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor];
}
AddToAugmentations(CordiARCReactor);
// BachmanAndAssociates
const SmartJaw = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw, repCost:150e3, moneyCost:550e6,
info:"A bionic jaw that contains advanced hardware and software " +
"capable of psychoanalyzing and profiling the personality of " +
"others using optical imaging software.
" +
"This augmentation: " +
"Increases the player's charisma by 50%. " +
"Increases the player's charisma experience gain rate by 50%. " +
"Increases the amount of reputation the player gains for a company by 25%. " +
"Increases the amount of reputation the player gains for a faction by 25%.",
charisma_mult: 1.5,
charisma_exp_mult: 1.5,
company_rep_mult: 1.25,
faction_rep_mult: 1.25,
});
SmartJaw.addToFactions(["Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw];
}
AddToAugmentations(SmartJaw);
// BladeIndustries
const Neotra = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra, repCost:225e3, moneyCost:575e6,
info:"A highly-advanced techno-organic drug that is injected into the skeletal " +
"and integumentary system. The drug permanently modifies the DNA of the " +
"body's skin and bone cells, granting them the ability to repair " +
"and restructure themselves.
" +
"This augmentation increases the player's strength and defense by 55%.",
strength_mult: 1.55,
defense_mult: 1.55,
});
Neotra.addToFactions(["Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra];
}
AddToAugmentations(Neotra);
// NWO
const Xanipher = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher, repCost:350e3, moneyCost:850e6,
info:"A concoction of advanced nanobots that is orally ingested into the " +
"body. These nanobots induce physiological change and significantly " +
"improve the body's functionining in all aspects.
" +
"This augmentation: " +
"Increases all of the player's stats by 20%. " +
"Increases the player's experience gain rate for all stats by 15%.",
hacking_mult: 1.2,
strength_mult: 1.2,
defense_mult: 1.2,
dexterity_mult: 1.2,
agility_mult: 1.2,
charisma_mult: 1.2,
hacking_exp_mult: 1.15,
strength_exp_mult: 1.15,
defense_exp_mult: 1.15,
dexterity_exp_mult: 1.15,
agility_exp_mult: 1.15,
charisma_exp_mult: 1.15,
});
Xanipher.addToFactions(["NWO"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher];
}
AddToAugmentations(Xanipher);
// ClarkeIncorporated
const nextSENS = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS, repCost:175e3, moneyCost:385e6,
info:"The body is genetically re-engineered to maintain a state " +
"of negligible senescence, preventing the body from " +
"deteriorating with age.
" +
"This augmentation increases all of the player's stats by 20%.",
hacking_mult: 1.2,
strength_mult: 1.2,
defense_mult: 1.2,
dexterity_mult: 1.2,
agility_mult: 1.2,
charisma_mult: 1.2,
});
nextSENS.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS];
}
AddToAugmentations(nextSENS);
// OmniTekIncorporated
const OmniTekInfoLoad = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad, repCost:250e3, moneyCost:575e6,
info:"OmniTek's data and information repository is uploaded " +
"into your brain, enhancing your programming and " +
"hacking abilities.
" +
"This augmentation: " +
"Increases the player's hacking skill by 20%. " +
"Increases the player's hacking experience gain rate by 25%.",
hacking_mult: 1.2,
hacking_exp_mult: 1.25,
});
OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad];
}
AddToAugmentations(OmniTekInfoLoad);
// FourSigma
// TODO Later when Intelligence is added in . Some aug that greatly increases int
// KuaiGongInternational
const PhotosyntheticCells = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells, repCost:225e3, moneyCost:550e6,
info:"Chloroplasts are added to epidermal stem cells and are applied " +
"to the body using a skin graft. The result is photosynthetic " +
"skin cells, allowing users to generate their own energy " +
"and nutrition using solar power.
" +
"This augmentation increases the player's strength, defense, and agility by 40%.",
strength_mult: 1.4,
defense_mult: 1.4,
agility_mult: 1.4,
});
PhotosyntheticCells.addToFactions(["KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells];
}
AddToAugmentations(PhotosyntheticCells);
// BitRunners
const Neurolink = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink, repCost:350e3, moneyCost:875e6,
info:"A brain implant that provides a high-bandwidth, direct neural link between your " +
"mind and BitRunners' data servers, which reportedly contain " +
"the largest database of hacking tools and information in the world.
" +
"This augmentation: " +
"Increases the player's hacking skill by 15%. " +
"Increases the player's hacking experience gain rate by 20%. " +
"Increases the player's chance of successfully performing a hack by 10%. " +
"Increases the player's hacking speed by 5%. " +
"Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset.",
hacking_mult: 1.15,
hacking_exp_mult: 1.2,
hacking_chance_mult: 1.1,
hacking_speed_mult: 1.05,
});
Neurolink.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink];
}
AddToAugmentations(Neurolink);
// BlackHand
const TheBlackHand = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand, repCost:40e3, moneyCost:110e6,
info:"A highly advanced bionic hand. This prosthetic not only " +
"enhances strength and dexterity but it is also embedded " +
"with hardware and firmware that lets the user connect to, access and hack " +
"devices and machines just by touching them.
" +
"This augmentation: " +
"Increases the player's strength and dexterity by 15%. " +
"Increases the player's hacking skill by 10%. " +
"Increases the player's hacking speed by 2%. " +
"Increases the amount of money the player gains from hacking by 10%.",
strength_mult: 1.15,
dexterity_mult: 1.15,
hacking_mult: 1.1,
hacking_speed_mult: 1.02,
hacking_money_mult: 1.1,
});
TheBlackHand.addToFactions(["The Black Hand"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand];
}
AddToAugmentations(TheBlackHand);
// NiteSec
const CRTX42AA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA, repCost:18e3, moneyCost:45e6,
info:"The CRTX42-AA gene is injected into the genome. " +
"The CRTX42-AA is an artificially-synthesized gene that targets the visual and prefrontal " +
"cortex and improves cognitive abilities.
" +
"This augmentation: " +
"Improves the player's hacking skill by 8%. " +
"Improves the player's hacking experience gain rate by 15%.",
hacking_mult: 1.08,
hacking_exp_mult: 1.15,
});
CRTX42AA.addToFactions(["NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA];
}
AddToAugmentations(CRTX42AA);
// Chongqing
const Neuregen = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen, repCost:15e3, moneyCost:75e6,
info:"A drug that genetically modifies the neurons in the brain. " +
"The result is that these neurons never die and continuously " +
"regenerate and strengthen themselves.
" +
"This augmentation increases the player's hacking experience gain rate by 40%.",
hacking_exp_mult: 1.4,
});
Neuregen.addToFactions(["Chongqing"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen];
}
AddToAugmentations(Neuregen);
// Sector12
const CashRoot = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot, repCost:5e3, moneyCost:25e6,
info:"A collection of digital assets saved on a small chip. The chip is implanted " +
"into your wrist. A small jack in the chip allows you to connect it to a computer " +
"and upload the assets.
" +
"This augmentation: " +
"Lets the player start with $1,000,000 after a reset. " +
"Lets the player start with the BruteSSH.exe program after a reset."
});
CashRoot.addToFactions(["Sector-12"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot];
}
AddToAugmentations(CashRoot);
// NewTokyo
const NutriGen = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen, repCost:2500, moneyCost:500e3,
info:"A thermo-powered artificial nutrition generator. Endogenously " +
"synthesizes glucose, amino acids, and vitamins and redistributes them " +
"across the body. The device is powered by the body's naturally wasted " +
"energy in the form of heat.
" +
"This augmentation: " +
"Increases the player's experience gain rate for all combat stats by 20%.",
strength_exp_mult: 1.2,
defense_exp_mult: 1.2,
dexterity_exp_mult: 1.2,
agility_exp_mult: 1.2,
});
NutriGen.addToFactions(["New Tokyo"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen];
}
AddToAugmentations(NutriGen);
// Aevum
// TODO Later Something that lets you learn advanced math...this increases int
// and profits as a trader/from trading
// Ishima
const INFRARet = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet, repCost:3e3, moneyCost:6e6,
info:"A retina implant consisting of a tiny chip that sits behind the " +
"retina. This implant lets people visually detect infrared radiation.
" +
"This augmentation: " +
"Increases the player's crime success rate by 25%. " +
"Increases the amount of money the player gains from crimes by 10%. " +
"Increases the player's dexterity by 10%.",
crime_success_mult: 1.25,
crime_money_mult: 1.1,
dexterity_mult: 1.1,
});
INFRARet.addToFactions(["Ishima"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet];
}
AddToAugmentations(INFRARet);
// Volhaven
const DermaForce = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce, repCost:6e3, moneyCost:10e6,
info:"A synthetic skin is grafted onto the body. The skin consists of " +
"millions of nanobots capable of projecting high-density muon beams, " +
"creating an energy barrier around the user.
" +
"This augmentation increases the player's defense by 40%.",
defense_mult: 1.4,
});
DermaForce.addToFactions(["Volhaven"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce];
}
AddToAugmentations(DermaForce);
// SpeakersForTheDead
const GrapheneBrachiBlades = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades, repCost:90e3, moneyCost:500e6,
info:"An upgrade to the BrachiBlades augmentation. It infuses " +
"the retractable blades with an advanced graphene material " +
"to make them much stronger and lighter.
" +
"This augmentation: " +
"Increases the player's strength and defense by 40%. " +
"Increases the player's crime success rate by 10%. " +
"Increases the amount of money the player gains from crimes by 30%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades],
strength_mult: 1.4,
defense_mult: 1.4,
crime_success_mult: 1.1,
crime_money_mult: 1.3,
});
GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades];
}
AddToAugmentations(GrapheneBrachiBlades);
// DarkArmy
const GrapheneBionicArms = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms, repCost:200e3, moneyCost:750e6,
info:"An upgrade to the Bionic Arms augmentation. It infuses the " +
"prosthetic arms with an advanced graphene material " +
"to make them much stronger and lighter.
" +
"This augmentation increases the player's strength and dexterity by 85%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms],
strength_mult: 1.85,
dexterity_mult: 1.85,
});
GrapheneBionicArms.addToFactions(["The Dark Army"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms];
}
AddToAugmentations(GrapheneBionicArms);
// TheSyndicate
const BrachiBlades = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades, repCost:5e3, moneyCost:18e6,
info:"A set of retractable plasteel blades are implanted in the arm, underneath the skin.
" +
"This augmentation: " +
"Increases the player's strength and defense by 15%. " +
"Increases the player's crime success rate by 10%. " +
"Increases the amount of money the player gains from crimes by 15%.",
strength_mult: 1.15,
defense_mult: 1.15,
crime_success_mult: 1.1,
crime_money_mult: 1.15,
});
BrachiBlades.addToFactions(["The Syndicate"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades];
}
AddToAugmentations(BrachiBlades);
// Tetrads
const BionicArms = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms, repCost:25e3, moneyCost:55e6,
info:"Cybernetic arms created from plasteel and carbon fibers that completely replace " +
"the user's organic arms.
" +
"This augmentation increases the user's strength and dexterity by 30%.",
strength_mult: 1.3,
dexterity_mult: 1.3,
});
BionicArms.addToFactions(["Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms];
}
AddToAugmentations(BionicArms);
// TianDiHui
const SNA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA, repCost:2500, moneyCost:6e6,
info:"A cranial implant that affects the user's personality, making them better " +
"at negotiation in social situations.
" +
"This augmentation: " +
"Increases the amount of money the player earns at a company by 10%. " +
"Increases the amount of reputation the player gains when working for a " +
"company or faction by 15%.",
work_money_mult: 1.1,
company_rep_mult: 1.15,
faction_rep_mult: 1.15,
});
SNA.addToFactions(["Tian Di Hui"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA];
}
AddToAugmentations(SNA);
// Special Bladeburner Augmentations
const BladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_6__["factionExists"])(BladeburnersFactionName)) {
const EsperEyewear = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EsperEyewear, repCost:500, moneyCost:33e6,
info:"Ballistic-grade protective and retractable eyewear that was designed specially " +
"for Bladeburner units. This " +
"is implanted by installing a mechanical frame in the skull's orbit. " +
"This frame interfaces with the brain and allows the user to " +
"automatically extrude and extract the eyewear. The eyewear protects " +
"against debris, shrapnel, laser, flash, and gas. It is also " +
"embedded with a data processing chip that can be programmed to display an " +
"AR HUD and assist the user in field missions.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 3%. " +
"Increases the player's dexterity by 5%.",
bladeburner_success_chance_mult: 1.03,
dexterity_mult: 1.05,
isSpecial: true,
});
EsperEyewear.addToFactions([BladeburnersFactionName]);
resetAugmentation(EsperEyewear);
const EMS4Recombination = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EMS4Recombination, repCost: 1e3, moneyCost:55e6,
info:"A DNA recombination of the EMS-4 Gene. This genetic engineering " +
"technique was originally used on Bladeburners during the Synthoid uprising " +
"to induce wakefulness and concentration, suppress fear, reduce empathy, and " +
"improve reflexes and memory-recall among other things.
" +
"This augmentation: " +
"Increases the player's sucess chance in Bladeburner contracts/operations by 3%. " +
"Increases the player's effectiveness in Bladeburner Field Analysis by 5%. " +
"Increases the player's Bladeburner stamina gain rate by 2%.",
bladeburner_success_chance_mult: 1.03,
bladeburner_analysis_mult: 1.05,
bladeburner_stamina_gain_mult: 1.02,
isSpecial: true,
});
EMS4Recombination.addToFactions([BladeburnersFactionName]);
resetAugmentation(EMS4Recombination);
const OrionShoulder = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OrionShoulder, repCost:2.5e3, moneyCost:110e6,
info:"A bionic shoulder augmentation for the right shoulder. Using cybernetics, " +
"the ORION-MKIV shoulder enhances the strength and dexterity " +
"of the user's right arm. It also provides protection due to its " +
"crystallized graphene plating.
" +
"This augmentation: " +
"Increases the player's defense by 5%. " +
"Increases the player's strength and dexterity by 5%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 4%.",
defense_mult: 1.05,
strength_mult: 1.05,
dexterity_mult: 1.05,
bladeburner_success_chance_mult: 1.04,
isSpecial: true,
});
OrionShoulder.addToFactions([BladeburnersFactionName]);
resetAugmentation(OrionShoulder);
const HyperionV1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV1, repCost: 5e3, moneyCost:550e6,
info:"A pair of mini plasma cannons embedded into the hands. The Hyperion is capable " +
"of rapidly firing bolts of high-density plasma. The weapon is meant to " +
"be used against augmented enemies as the ionized " +
"nature of the plasma disrupts the electrical systems of Augmentations. However, " +
"it can also be effective against non-augmented enemies due to its high temperature " +
"and concussive force.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 6%.",
bladeburner_success_chance_mult: 1.06,
isSpecial: true,
});
HyperionV1.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV1);
const HyperionV2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV2, repCost:10e3, moneyCost:1.1e9,
info:"A pair of mini plasma cannons embedded into the hands. This augmentation " +
"is more advanced and powerful than the original V1 model. This V2 model is " +
"more power-efficiency, more accurate, and can fire plasma bolts at a much " +
"higher velocity than the V1 model.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 8%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV1],
bladeburner_success_chance_mult: 1.08,
isSpecial: true,
});
HyperionV2.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV2);
const GolemSerum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GolemSerum, repCost:12.5e3, moneyCost:2.2e9,
info:"A serum that permanently enhances many aspects of a human's capabilities, " +
"including strength, speed, immune system performance, and mitochondrial efficiency. The " +
"serum was originally developed by the Chinese military in an attempt to " +
"create super soldiers.
" +
"This augmentation: " +
"Increases all of the player's combat stats by 7%. " +
"Increases the player's Bladeburner stamina gain rate by 5%. ",
strength_mult: 1.07,
defense_mult: 1.07,
dexterity_mult: 1.07,
agility_mult: 1.07,
bladeburner_stamina_gain_mult: 1.05,
isSpecial: true,
});
GolemSerum.addToFactions([BladeburnersFactionName]);
resetAugmentation(GolemSerum);
const VangelisVirus = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus, repCost:7.5e3, moneyCost:550e6,
info:"A synthetic symbiotic virus that is injected into the human brain tissue. The Vangelis virus " +
"heightens the senses and focus of its host, and also enhances its intuition.
" +
"This augmentation: " +
"Increases the player's effectiveness in Bladeburner Field Analysis by 10%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 4%. " +
"Increases the player's dexterity experience gain rate by 10%.",
dexterity_exp_mult: 1.1,
bladeburner_analysis_mult: 1.1,
bladeburner_success_chance_mult: 1.04,
isSpecial: true,
});
VangelisVirus.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus);
const VangelisVirus3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus3, repCost:15e3, moneyCost:2.2e9,
info:"An improved version of Vangelis, a synthetic symbiotic virus that is " +
"injected into the human brain tissue. On top of the benefits of the original " +
"virus, this also grants an accelerated healing factor and enhanced " +
"agility/reflexes.
" +
"This augmentation: " +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%. " +
"Increases the player's defense and dexterity experience gain rate by 10%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 5%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus],
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
bladeburner_analysis_mult: 1.15,
bladeburner_success_chance_mult: 1.05,
isSpecial: true,
});
VangelisVirus3.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus3);
const INTERLINKED = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INTERLINKED, repCost:10e3, moneyCost:1.1e9,
info:"The DNA is genetically modified to enhance the human's body " +
"extracellular matrix (ECM). This improves the ECM's ability to " +
"structurally support the body and grants heightened strength and " +
"durability.
" +
"This augmentation: " +
"Increases the player's experience gain rate for all combat stats by 5%. " +
"Increases the player's Bladeburner max stamina by 10%.",
strength_exp_mult: 1.05,
defense_exp_mult: 1.05,
dexterity_exp_mult: 1.05,
agility_exp_mult: 1.05,
bladeburner_max_stamina_mult: 1.1,
isSpecial: true,
});
INTERLINKED.addToFactions([BladeburnersFactionName]);
resetAugmentation(INTERLINKED);
const BladeRunner = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeRunner, repCost:8e3, moneyCost:1.65e9,
info:"A cybernetic foot augmentation that was specially created for Bladeburners " +
"during the Synthoid Uprising. The organic musculature of the human foot " +
"is enhanced with flexible carbon nanotube matrices that are controlled by " +
"intelligent servo-motors.
" +
"This augmentation: " +
"Increases the player's agility by 5%. " +
"Increases the player's Bladeburner max stamina by 5%. " +
"Increases the player's Bladeburner stamina gain rate by 5%. ",
agility_mult: 1.05,
bladeburner_max_stamina_mult: 1.05,
bladeburner_stamina_gain_mult: 1.05,
isSpecial: true,
});
BladeRunner.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeRunner);
const BladeArmor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor, repCost:5e3, moneyCost:275e6,
info:"A powered exoskeleton suit (exosuit) designed as armor for Bladeburner units. This " +
"exoskeleton is incredibly adaptable and can protect the wearer from blunt, piercing, " +
"concussive, thermal, chemical, and electric trauma. It also enhances the user's " +
"strength and agility.
" +
"This augmentation: " +
"Increases all of the player's combat stats by 4%. " +
"Increases the player's Bladeburner stamina gain rate by 2%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 3%.",
strength_mult: 1.04,
defense_mult: 1.04,
dexterity_mult: 1.04,
agility_mult: 1.04,
bladeburner_stamina_gain_mult: 1.02,
bladeburner_success_chance_mult: 1.03,
isSpecial: true,
});
BladeArmor.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmor);
const BladeArmorPowerCells = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorPowerCells, repCost:7.5e3, moneyCost:550e6,
info:"Upgrades the BLADE-51b Tesla Armor with Ion Power Cells, which are capable of " +
"more efficiently storing and using power.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 5%. " +
"Increases the player's Bladeburner stamina gain rate by 2%. " +
"Increases the player's Bladeburner max stamina by 5%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_success_chance_mult: 1.05,
bladeburner_stamina_gain_mult: 1.02,
bladeburner_max_stamina_mult: 1.05,
isSpecial: true,
});
BladeArmorPowerCells.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorPowerCells);
const BladeArmorEnergyShielding = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorEnergyShielding, repCost:8.5e3, moneyCost:1.1e9,
info:"Upgrades the BLADE-51b Tesla Armor with a plasma energy propulsion system " +
"that is capable of projecting an energy shielding force field.
" +
"This augmentation: " +
"Increases the player's defense by 5%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 6%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
defense_mult: 1.05,
bladeburner_success_chance_mult: 1.06,
isSpecial: true,
});
BladeArmorEnergyShielding.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorEnergyShielding);
const BladeArmorUnibeam = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorUnibeam, repCost:12.5e3, moneyCost:3.3e9,
info:"Upgrades the BLADE-51b Tesla Armor with a concentrated deuterium-fluoride laser " +
"weapon. It's precision an accuracy makes it useful for quickly neutralizing " +
"threats while keeping casualties to a minimum.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 8%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_success_chance_mult: 1.08,
isSpecial: true,
});
BladeArmorUnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorUnibeam);
const BladeArmorOmnibeam = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorOmnibeam, repCost:25e3, moneyCost:5.5e9,
info:"Upgrades the BLADE-51b Tesla Armor Unibeam augmentation to use " +
"multiple-fiber system. The upgraded weapon uses multiple fiber laser " +
"modules that combine together to form a single, more powerful beam of up to " +
"2000MW.
" +
"This augmentation: " +
"Increases the player's success chance in Bladeburner contracts/operations by 10%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorUnibeam],
bladeburner_success_chance_mult: 1.1,
isSpecial: true,
});
BladeArmorOmnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorOmnibeam);
const BladeArmorIPU = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorIPU, repCost: 6e3, moneyCost:220e6,
info:"Upgrades the BLADE-51b Tesla Armor with an AI Information Processing " +
"Unit that was specially designed to analyze Synthoid related data and " +
"information.
" +
"This augmentation: " +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%. " +
"Increases the player's success chance in Bladeburner contracts/operations by 2%.",
prereqs:[_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_analysis_mult: 1.15,
bladeburner_success_chance_mult: 1.02,
isSpecial: true,
});
BladeArmorIPU.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorIPU);
const BladesSimulacrum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name:_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladesSimulacrum, repCost: 500, moneyCost: 30e9,
info:"A highly-advanced matter phase-shifter module that is embedded " +
"in the brainstem and cerebellum. This augmentation allows " +
"the user to project and control a holographic simulacrum within an " +
"extremely large radius. These specially-modified holograms were specially " +
"weaponized by Bladeburner units to be used against Synthoids.
" +
"This augmentation allows you to perform Bladeburner actions and other " +
"actions (such as working, commiting crimes, etc.) at the same time.",
isSpecial: true,
});
BladesSimulacrum.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladesSimulacrum);
}
// Update costs based on how many have been purchased
mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MultipleAugMultiplier, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length);
for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"]) {
if (_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"].hasOwnProperty(name)) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name].baseCost *= mult;
}
}
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].reapplyAllAugmentations();
}
//Resets an Augmentation during (re-initizliation)
function resetAugmentation(newAugObject) {
if (!(newAugObject instanceof _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"])) {
throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation");
}
var name = newAugObject.name;
if (augmentationExists(name)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name];
}
AddToAugmentations(newAugObject);
}
function applyAugmentation(aug, reapply=false) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name].owned = true;
const augObj = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name];
// Apply multipliers
for (const mult in augObj.mults) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"][mult] == null) {
console.warn(`Augmentation has unrecognized multiplier property: ${mult}`);
} else {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"][mult] *= augObj.mults[mult];
}
}
// Special logic for NeuroFlux Governor
if (aug.name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
if (!reapply) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name].level = aug.level;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].name == _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].level = aug.level;
return;
// break;
}
}
}
}
/*
if (aug.name === AugmentationNames.NeuroFluxGovernor) {
for (var i = 0; i < Player.augmentations.length; ++i) {
if (Player.augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
//Already have this aug, just upgrade the level
return;
}
}
}
*/
// Push onto Player's Augmentation list
if (!reapply) {
var ownedAug = new _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__["PlayerOwnedAugmentation"](aug.name);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.push(ownedAug);
}
}
function installAugmentations(cbScript=null) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length == 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("You have not purchased any Augmentations to install!");
return false;
}
var augmentationList = "";
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length; ++i) {
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].name];
if (aug == null) {
console.log("ERROR. Invalid augmentation");
continue;
}
applyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i]);
augmentationList += (aug.name + " ");
}
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations = [];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " +
"to install the following Augmentations: " + augmentationList +
" You wake up in your home...you feel different...");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_9__[/* prestigeAugmentation */ "a"])();
//Run a script after prestiging
if (cbScript && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_23__["isString"])(cbScript)) {
var home = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer();
for (var i = 0; i < home.scripts.length; ++i) {
if (home.scripts[i].filename === cbScript) {
var script = home.scripts[i];
var ramUsage = script.ramUsage;
var ramAvailable = home.maxRam - home.ramUsed;
if (ramUsage > ramAvailable) {
return; //Not enough RAM
}
var runningScriptObj = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_11__["RunningScript"](script, []); //No args
runningScriptObj.threads = 1; //Only 1 thread
home.runScript(runningScriptObj, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hacknet_node_money_mult);
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_7__[/* addWorkerScript */ "b"])(runningScriptObj, home);
}
}
}
}
function augmentationExists(name) {
return _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"].hasOwnProperty(name);
}
function displayAugmentationsContent(contentEl) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24__["removeChildrenFromElement"])(contentEl);
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("h1", {
innerText:"Purchased Augmentations",
}));
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("pre", {
width:"70%", whiteSpace:"pre-wrap", display:"block",
innerText:"Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them.\n" +
"WARNING: Installing your Augmentations resets most of your progress, including:\n\n" +
"Stats/Skill levels and Experience\n" +
"Money\n" +
"Scripts on every computer but your home computer\n" +
"Purchased servers\n" +
"Hacknet Nodes\n" +
"Faction/Company reputation\n" +
"Stocks\n" +
"Installing Augmentations lets you start over with the perks and benefits granted by all " +
"of the Augmentations you have ever installed. Also, you will keep any scripts and RAM/Core upgrades " +
"on your home computer (but you will lose all programs besides NUKE.exe)."
}));
//Install Augmentations button
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button", innerText:"Install Augmentations",
tooltip:"'I never asked for this'",
clickListener:()=>{
installAugmentations();
return false;
}
}));
//Backup button
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button flashing-button", innerText:"Backup Save (Export)",
tooltip:"It's always a good idea to backup/export your save!",
clickListener:()=>{
_SaveObject__WEBPACK_IMPORTED_MODULE_10__[/* saveObject */ "b"].exportGame();
return false;
}
}));
//Purchased/queued augmentations list
var queuedAugmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("ul", {class:"augmentations-list"});
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length; ++i) {
var augName = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].name;
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][augName];
var displayName = augName;
if (augName === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
displayName += " - Level " + (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].level);
}
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
queuedAugmentationsList.appendChild(accordion[0]);
}
contentEl.appendChild(queuedAugmentationsList);
//Installed augmentations list
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("h1", {
innerText:"Installed Augmentations", marginTop:"8px",
}));
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("p", {
width:"70%", whiteSpace:"pre-wrap",
innerText:"List of all Augmentations (including Source Files) that have been " +
"installed. You have gained the effects of these Augmentations."
}));
var augmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("ul", {class:"augmentations-list"});
//Expand/Collapse All buttons
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Expand All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (!allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Collapse All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
//Sort Buttons
const sortInOrderButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort in Order",
tooltip:"Sorts the Augmentations alphabetically and Source Files in numerical order (1, 2, 3,...)",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24__["removeChildrenFromElement"])(augmentationsList);
//Create a copy of Player's Source Files and augs array and sort them
var sourceFiles = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].sourceFiles.slice();
var augs = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.slice();
sourceFiles.sort((sf1, sf2)=>{
return sf1.n - sf2.n;
});
augs.sort((aug1, aug2)=>{
return aug1.name <= aug2.name ? -1 : 1;
});
displaySourceFiles(augmentationsList, sourceFiles);
displayAugmentations(augmentationsList, augs);
_Settings_Settings__WEBPACK_IMPORTED_MODULE_15__["Settings"].OwnedAugmentationsOrder = _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["OwnedAugmentationsOrderSetting"].Alphabetically;
}
});
contentEl.appendChild(sortInOrderButton);
const sortByAcquirementTimeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort by Acquirement Time",
tooltip:"Sorts the Augmentations and Source Files based on when you acquired them (same as default)",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_24__["removeChildrenFromElement"])(augmentationsList);
displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].sourceFiles);
displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations);
_Settings_Settings__WEBPACK_IMPORTED_MODULE_15__["Settings"].OwnedAugmentationsOrder = _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["OwnedAugmentationsOrderSetting"].AcquirementTime;
}
});
contentEl.appendChild(sortByAcquirementTimeButton);
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_15__["Settings"].OwnedAugmentationsOrder === _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_14__["OwnedAugmentationsOrderSetting"].Alphabetically) {
sortInOrderButton.click();
} else {
sortByAcquirementTimeButton.click();
}
contentEl.appendChild(augmentationsList);
// Display multiplier information at the bottom
contentEl.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_22__["createElement"])("p", {
display: "block",
innerHTML:
`
',
}))
}
//Creates the accordion elements to display Augmentations
// @listElement - List DOM element to append accordion elements to
// @augs - Array of Augmentation objects
function displayAugmentations(listElement, augs) {
for (var i = 0; i < augs.length; ++i) {
var augName = augs[i].name;
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][augName];
var displayName = augName;
if (augName === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
displayName += " - Level " + (augs[i].level);
}
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
listElement.appendChild(accordion[0]);
}
}
//Creates the accordion elements to display Source Files
// @listElement - List DOM element to append accordion elements to
// @sourceFiles - Array of Source File objects
function displaySourceFiles(listElement, sourceFiles) {
for (var i = 0; i < sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + sourceFiles[i].n;
var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_16__[/* SourceFiles */ "a"][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + sourceFiles[i].n);
continue;
}
const maxLevel = sourceFiles[i].n == 12 ? "∞" : "3";
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_18__["createAccordionElement"])({
hdrText:sourceFileObject.name + " " + "Level " + (sourceFiles[i].lvl) + " / "+maxLevel,
panelText:sourceFileObject.info
});
listElement.appendChild(accordion[0]);
}
}
/***/ }),
/* 79 */
/*!************************!*\
!*** ./utils/acorn.js ***!
\************************/
/*! no static exports found */
/*! exports used: Node, parse */
/***/ (function(module, exports, __webpack_require__) {
/*
acorn.js
https://github.com/ternjs/acorn
Copyright (C) 2012-2017 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global, factory) {
true ? factory(exports) :
undefined;
}(this, (function (exports) { 'use strict';
// Reserved word lists for various dialects of the language
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
}
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"
var keywords = {
5: ecma5AndLessKeywords,
6: ecma5AndLessKeywords + " const class extends export import super"
}
// ## Character categories
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
// Generated by `bin/generate-identifier-regex.js`.
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range. They were
// generated by bin/generate-identifier-regex.js
// eslint-disable-next-line comma-spacing
var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541]
// eslint-disable-next-line comma-spacing
var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
var pos = 0x10000
for (var i = 0; i < set.length; i += 2) {
pos += set[i]
if (pos > code) return false
pos += set[i + 1]
if (pos >= code) return true
}
}
// Test whether a given character code starts an identifier.
function isIdentifierStart(code, astral) {
if (code < 65) return code === 36
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36
if (code < 58) return true
if (code < 65) return false
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
var TokenType = function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label
this.keyword = conf.keyword
this.beforeExpr = !!conf.beforeExpr
this.startsExpr = !!conf.startsExpr
this.isLoop = !!conf.isLoop
this.isAssign = !!conf.isAssign
this.prefix = !!conf.prefix
this.postfix = !!conf.postfix
this.binop = conf.binop || null
this.updateContext = null
};
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true};
var startsExpr = {startsExpr: true};
// Map keyword names to token types.
var keywordTypes = {}
// Succinct definitions of keyword token types
function kw(name, options) {
if ( options === void 0 ) options = {};
options.keyword = name
return keywordTypes[name] = new TokenType(name, options)
}
var tt = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=", 6),
relational: binop(">", 7),
bitShift: binop("<>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", {beforeExpr: true}),
// Keyword token types.
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {isLoop: true, beforeExpr: true}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", {isLoop: true}),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", {isLoop: true}),
_with: kw("with"),
_new: kw("new", {beforeExpr: true, startsExpr: true}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class"),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import"),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {beforeExpr: true, binop: 7}),
_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
}
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/
var lineBreakG = new RegExp(lineBreak.source, "g")
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
// Checks if an object has a property.
function has(obj, propName) {
return hasOwnProperty.call(obj, propName)
}
var isArray = Array.isArray || (function (obj) { return (
toString.call(obj) === "[object Array]"
); })
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = function Position(line, col) {
this.line = line
this.column = col
};
Position.prototype.offset = function offset (n) {
return new Position(this.line, this.column + n)
};
var SourceLocation = function SourceLocation(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
};
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
var match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
var defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
// for strict mode, the set of reserved words, and support for
// new syntax features. The default is 7.
ecmaVersion: 7,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {}
}
// Interpret and default an options object
function getOptions(opts) {
var options = {}
for (var opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (options.ecmaVersion >= 2015)
options.ecmaVersion -= 2009
if (options.allowReserved == null)
options.allowReserved = options.ecmaVersion < 5
if (isArray(options.onToken)) {
var tokens = options.onToken
options.onToken = function (token) { return tokens.push(token); }
}
if (isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start: start,
end: end
}
if (options.locations)
comment.loc = new SourceLocation(this, startLoc, endLoc)
if (options.ranges)
comment.range = [start, end]
array.push(comment)
}
}
// Registered plugins
var plugins = {}
function keywordRegexp(words) {
return new RegExp("^(" + words.replace(/ /g, "|") + ")$")
}
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options)
this.sourceFile = options.sourceFile
this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])
var reserved = ""
if (!options.allowReserved) {
for (var v = options.ecmaVersion;; v--)
if (reserved = reservedWords[v]) break
if (options.sourceType == "module") reserved += " await"
}
this.reservedWords = keywordRegexp(reserved)
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict
this.reservedWordsStrict = keywordRegexp(reservedStrict)
this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind)
this.input = String(input)
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false
// Load plugins
this.loadPlugins(options.plugins)
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
} else {
this.pos = this.lineStart = 0
this.curLine = 1
}
// Properties of the current token:
// Its type
this.type = tt.eof
// For tokens that include more information than their type, the value
this.value = null
// Its start and end offset
this.start = this.end = this.pos
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition()
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null
this.lastTokStart = this.lastTokEnd = this.pos
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext()
this.exprAllowed = true
// Figure out if it's a module code.
this.inModule = options.sourceType === "module"
this.strict = this.inModule || this.strictDirective(this.pos)
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1
// Flags to track whether we are in a function, a generator, an async function.
this.inFunction = this.inGenerator = this.inAsync = false
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = 0
// Labels in scope.
this.labels = []
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
this.skipLineComment(2)
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = []
this.enterFunctionScope()
};
// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
Parser.prototype.extend = function extend (name, f) {
this[name] = f(this[name])
};
Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
var this$1 = this;
for (var name in pluginConfigs) {
var plugin = plugins[name]
if (!plugin) throw new Error("Plugin '" + name + "' not found")
plugin(this$1, pluginConfigs[name])
}
};
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode()
this.nextToken()
return this.parseTopLevel(node)
};
var pp = Parser.prototype
// ## Parser utilities
var literal = /^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/
pp.strictDirective = function(start) {
var this$1 = this;
for (;;) {
skipWhiteSpace.lastIndex = start
start += skipWhiteSpace.exec(this$1.input)[0].length
var match = literal.exec(this$1.input.slice(start))
if (!match) return false
if ((match[1] || match[2]) == "use strict") return true
start += match[0].length
}
}
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next()
return true
} else {
return false
}
}
// Tests whether parsed token is a contextual keyword.
pp.isContextual = function(name) {
return this.type === tt.name && this.value === name
}
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
return this.value === name && this.eat(tt.name)
}
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) this.unexpected()
}
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === tt.eof ||
this.type === tt.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
return true
}
}
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
}
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type == tokType) {
if (this.options.onTrailingComma)
this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
if (!notNext)
this.next()
return true
}
}
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp.expect = function(type) {
this.eat(type) || this.unexpected()
}
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token")
}
var DestructuringErrors = function DestructuringErrors() {
this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = -1
};
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) return
if (refDestructuringErrors.trailingComma > -1)
this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element")
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind
if (parens > -1) this.raiseRecoverable(parens, "Parenthesized pattern")
}
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1
if (!andThrow) return pos >= 0
if (pos > -1) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns")
}
pp.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
this.raise(this.yieldPos, "Yield expression cannot be a default value")
if (this.awaitPos)
this.raise(this.awaitPos, "Await expression cannot be a default value")
}
pp.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
return this.isSimpleAssignTarget(expr.expression)
return expr.type === "Identifier" || expr.type === "MemberExpression"
}
var pp$1 = Parser.prototype
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$1.parseTopLevel = function(node) {
var this$1 = this;
var exports = {}
if (!node.body) node.body = []
while (this.type !== tt.eof) {
var stmt = this$1.parseStatement(true, true, exports)
node.body.push(stmt)
}
this.next()
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType
}
return this.finishNode(node, "Program")
}
var loopLabel = {kind: "loop"};
var switchLabel = {kind: "switch"};
pp$1.isLet = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
if (nextCh === 91 || nextCh == 123) return true // '{' and '['
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1
while (isIdentifierChar(this.input.charCodeAt(pos), true)) ++pos
var ident = this.input.slice(next, pos)
if (!this.isKeyword(ident)) return true
}
return false
}
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$1.isAsyncFunction = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async")
return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$1.parseStatement = function(declaration, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind
if (this.isLet()) {
starttype = tt._var
kind = "let"
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case tt._debugger: return this.parseDebuggerStatement(node)
case tt._do: return this.parseDoStatement(node)
case tt._for: return this.parseForStatement(node)
case tt._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
return this.parseFunctionStatement(node, false)
case tt._class:
if (!declaration) this.unexpected()
return this.parseClass(node, true)
case tt._if: return this.parseIfStatement(node)
case tt._return: return this.parseReturnStatement(node)
case tt._switch: return this.parseSwitchStatement(node)
case tt._throw: return this.parseThrowStatement(node)
case tt._try: return this.parseTryStatement(node)
case tt._const: case tt._var:
kind = kind || this.value
if (!declaration && kind != "var") this.unexpected()
return this.parseVarStatement(node, kind)
case tt._while: return this.parseWhileStatement(node)
case tt._with: return this.parseWithStatement(node)
case tt.braceL: return this.parseBlock()
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
if (!this.inModule)
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction() && declaration) {
this.next()
return this.parseFunctionStatement(node, true)
}
var maybeName = this.value, expr = this.parseExpression()
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
return this.parseLabeledStatement(node, maybeName, expr)
else return this.parseExpressionStatement(node, expr)
}
}
pp$1.parseBreakContinueStatement = function(node, keyword) {
var this$1 = this;
var isBreak = keyword == "break"
this.next()
if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
else if (this.type !== tt.name) this.unexpected()
else {
node.label = this.parseIdent()
this.semicolon()
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0
for (; i < this.labels.length; ++i) {
var lab = this$1.labels[i]
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break
if (node.label && isBreak) break
}
}
if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}
pp$1.parseDebuggerStatement = function(node) {
this.next()
this.semicolon()
return this.finishNode(node, "DebuggerStatement")
}
pp$1.parseDoStatement = function(node) {
this.next()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
this.eat(tt.semi)
else
this.semicolon()
return this.finishNode(node, "DoWhileStatement")
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp$1.parseForStatement = function(node) {
this.next()
this.labels.push(loopLabel)
this.enterLexicalScope()
this.expect(tt.parenL)
if (this.type === tt.semi) return this.parseFor(node, null)
var isLet = this.isLet()
if (this.type === tt._var || this.type === tt._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value
this.next()
this.parseVar(init$1, true, kind)
this.finishNode(init$1, "VariableDeclaration")
if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
!(kind !== "var" && init$1.declarations[0].init))
return this.parseForIn(node, init$1)
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors
var init = this.parseExpression(true, refDestructuringErrors)
if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.toAssignable(init)
this.checkLVal(init)
this.checkPatternErrors(refDestructuringErrors, true)
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true)
}
return this.parseFor(node, init)
}
pp$1.parseFunctionStatement = function(node, isAsync) {
this.next()
return this.parseFunction(node, true, false, isAsync)
}
pp$1.isFunction = function() {
return this.type === tt._function || this.isAsyncFunction()
}
pp$1.parseIfStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement(!this.strict && this.isFunction())
node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null
return this.finishNode(node, "IfStatement")
}
pp$1.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
this.raise(this.start, "'return' outside of function")
this.next()
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
else { node.argument = this.parseExpression(); this.semicolon() }
return this.finishNode(node, "ReturnStatement")
}
pp$1.parseSwitchStatement = function(node) {
var this$1 = this;
this.next()
node.discriminant = this.parseParenExpression()
node.cases = []
this.expect(tt.braceL)
this.labels.push(switchLabel)
this.enterLexicalScope()
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur
for (var sawDefault = false; this.type != tt.braceR;) {
if (this$1.type === tt._case || this$1.type === tt._default) {
var isCase = this$1.type === tt._case
if (cur) this$1.finishNode(cur, "SwitchCase")
node.cases.push(cur = this$1.startNode())
cur.consequent = []
this$1.next()
if (isCase) {
cur.test = this$1.parseExpression()
} else {
if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses")
sawDefault = true
cur.test = null
}
this$1.expect(tt.colon)
} else {
if (!cur) this$1.unexpected()
cur.consequent.push(this$1.parseStatement(true))
}
}
this.exitLexicalScope()
if (cur) this.finishNode(cur, "SwitchCase")
this.next() // Closing brace
this.labels.pop()
return this.finishNode(node, "SwitchStatement")
}
pp$1.parseThrowStatement = function(node) {
this.next()
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
this.raise(this.lastTokEnd, "Illegal newline after throw")
node.argument = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ThrowStatement")
}
// Reused empty array added for node fields that are always empty.
var empty = []
pp$1.parseTryStatement = function(node) {
this.next()
node.block = this.parseBlock()
node.handler = null
if (this.type === tt._catch) {
var clause = this.startNode()
this.next()
this.expect(tt.parenL)
clause.param = this.parseBindingAtom()
this.enterLexicalScope()
this.checkLVal(clause.param, "let")
this.expect(tt.parenR)
clause.body = this.parseBlock(false)
this.exitLexicalScope()
node.handler = this.finishNode(clause, "CatchClause")
}
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
if (!node.handler && !node.finalizer)
this.raise(node.start, "Missing catch or finally clause")
return this.finishNode(node, "TryStatement")
}
pp$1.parseVarStatement = function(node, kind) {
this.next()
this.parseVar(node, false, kind)
this.semicolon()
return this.finishNode(node, "VariableDeclaration")
}
pp$1.parseWhileStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "WhileStatement")
}
pp$1.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode")
this.next()
node.object = this.parseParenExpression()
node.body = this.parseStatement(false)
return this.finishNode(node, "WithStatement")
}
pp$1.parseEmptyStatement = function(node) {
this.next()
return this.finishNode(node, "EmptyStatement")
}
pp$1.parseLabeledStatement = function(node, maybeName, expr) {
var this$1 = this;
for (var i = 0; i < this.labels.length; ++i)
if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared")
var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) {
var label = this$1.labels[i$1]
if (label.statementStart == node.start) {
label.statementStart = this$1.start
label.kind = kind
} else break
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
node.body = this.parseStatement(true)
if (node.body.type == "ClassDeclaration" ||
node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
this.raiseRecoverable(node.body.start, "Invalid labeled declaration")
this.labels.pop()
node.label = expr
return this.finishNode(node, "LabeledStatement")
}
pp$1.parseExpressionStatement = function(node, expr) {
node.expression = expr
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp$1.parseBlock = function(createNewLexicalScope) {
var this$1 = this;
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
var node = this.startNode()
node.body = []
this.expect(tt.braceL)
if (createNewLexicalScope) {
this.enterLexicalScope()
}
while (!this.eat(tt.braceR)) {
var stmt = this$1.parseStatement(true)
node.body.push(stmt)
}
if (createNewLexicalScope) {
this.exitLexicalScope()
}
return this.finishNode(node, "BlockStatement")
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp$1.parseFor = function(node, init) {
node.init = init
this.expect(tt.semi)
node.test = this.type === tt.semi ? null : this.parseExpression()
this.expect(tt.semi)
node.update = this.type === tt.parenR ? null : this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "ForStatement")
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp$1.parseForIn = function(node, init) {
var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
this.next()
node.left = init
node.right = this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, type)
}
// Parse a list of variable declarations.
pp$1.parseVar = function(node, isFor, kind) {
var this$1 = this;
node.declarations = []
node.kind = kind
for (;;) {
var decl = this$1.startNode()
this$1.parseVarId(decl, kind)
if (this$1.eat(tt.eq)) {
decl.init = this$1.parseMaybeAssign(isFor)
} else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
this$1.unexpected()
} else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) {
this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value")
} else {
decl.init = null
}
node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"))
if (!this$1.eat(tt.comma)) break
}
return node
}
pp$1.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom(kind)
this.checkLVal(decl.id, kind, false)
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node)
if (this.options.ecmaVersion >= 6 && !isAsync)
node.generator = this.eat(tt.star)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
if (isStatement) {
node.id = isStatement === "nullableID" && this.type != tt.name ? null : this.parseIdent()
if (node.id) {
this.checkLVal(node.id, "var")
}
}
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
if (!isStatement)
node.id = this.type == tt.name ? this.parseIdent() : null
this.parseFunctionParams(node)
this.parseFunctionBody(node, allowExpressionBody)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
}
pp$1.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true)
this.checkYieldAwaitInDefaultParams()
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
var this$1 = this;
this.next()
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
var classBody = this.startNode()
var hadConstructor = false
classBody.body = []
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (this$1.eat(tt.semi)) continue
var method = this$1.startNode()
var isGenerator = this$1.eat(tt.star)
var isAsync = false
var isMaybeStatic = this$1.type === tt.name && this$1.value === "static"
this$1.parsePropertyName(method)
method.static = isMaybeStatic && this$1.type !== tt.parenL
if (method.static) {
if (isGenerator) this$1.unexpected()
isGenerator = this$1.eat(tt.star)
this$1.parsePropertyName(method)
}
if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL &&
!this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(method)
}
method.kind = "method"
var isGetSet = false
if (!method.computed) {
var key = method.key;
if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true
method.kind = key.name
key = this$1.parsePropertyName(method)
}
if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class")
if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier")
if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator")
if (isAsync) this$1.raise(key.start, "Constructor can't be an async method")
method.kind = "constructor"
hadConstructor = true
}
}
this$1.parseClassMethod(classBody, method, isGenerator, isAsync)
if (isGetSet) {
var paramCount = method.kind === "get" ? 0 : 1
if (method.value.params.length !== paramCount) {
var start = method.value.start
if (method.kind === "get")
this$1.raiseRecoverable(start, "getter should have no params")
else
this$1.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (method.kind === "set" && method.value.params[0].type === "RestElement")
this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params")
}
}
}
node.body = this.finishNode(classBody, "ClassBody")
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}
pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync)
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
pp$1.parseClassId = function(node, isStatement) {
node.id = this.type === tt.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null
}
pp$1.parseClassSuper = function(node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
}
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
var this$1 = this;
this.next()
// export * from '...'
if (this.eat(tt.star)) {
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.semicolon()
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(tt._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart)
var isAsync
if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode()
this.next()
if (isAsync) this.next()
node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync)
} else if (this.type === tt._class) {
var cNode = this.startNode()
node.declaration = this.parseClass(cNode, "nullableID")
} else {
node.declaration = this.parseMaybeAssign()
this.semicolon()
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(true)
if (node.declaration.type === "VariableDeclaration")
this.checkVariableExport(exports, node.declaration.declarations)
else
this.checkExport(exports, node.declaration.id.name, node.declaration.id.start)
node.specifiers = []
node.source = null
} else { // export { x, y as z } [from '...']
node.declaration = null
node.specifiers = this.parseExportSpecifiers(exports)
if (this.eatContextual("from")) {
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
} else {
// check for keywords used as local names
for (var i = 0; i < node.specifiers.length; i++) {
if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) {
this$1.unexpected(node.specifiers[i].local.start)
}
}
node.source = null
}
this.semicolon()
}
return this.finishNode(node, "ExportNamedDeclaration")
}
pp$1.checkExport = function(exports, name, pos) {
if (!exports) return
if (has(exports, name))
this.raiseRecoverable(pos, "Duplicate export '" + name + "'")
exports[name] = true
}
pp$1.checkPatternExport = function(exports, pat) {
var this$1 = this;
var type = pat.type
if (type == "Identifier")
this.checkExport(exports, pat.name, pat.start)
else if (type == "ObjectPattern")
for (var i = 0; i < pat.properties.length; ++i)
this$1.checkPatternExport(exports, pat.properties[i].value)
else if (type == "ArrayPattern")
for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) {
var elt = pat.elements[i$1]
if (elt) this$1.checkPatternExport(exports, elt)
}
else if (type == "AssignmentPattern")
this.checkPatternExport(exports, pat.left)
else if (type == "ParenthesizedExpression")
this.checkPatternExport(exports, pat.expression)
}
pp$1.checkVariableExport = function(exports, decls) {
var this$1 = this;
if (!exports) return
for (var i = 0; i < decls.length; i++)
this$1.checkPatternExport(exports, decls[i].id)
}
pp$1.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
}
// Parses a comma-separated list of module exports.
pp$1.parseExportSpecifiers = function(exports) {
var this$1 = this;
var nodes = [], first = true
// export { x, y as z } [from '...']
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node = this$1.startNode()
node.local = this$1.parseIdent(true)
node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local
this$1.checkExport(exports, node.exported.name, node.exported.start)
nodes.push(this$1.finishNode(node, "ExportSpecifier"))
}
return nodes
}
// Parses import declaration.
pp$1.parseImport = function(node) {
this.next()
// import '...'
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
} else {
node.specifiers = this.parseImportSpecifiers()
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
}
this.semicolon()
return this.finishNode(node, "ImportDeclaration")
}
// Parses a comma-separated list of module imports.
pp$1.parseImportSpecifiers = function() {
var this$1 = this;
var nodes = [], first = true
if (this.type === tt.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode()
node.local = this.parseIdent()
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
if (!this.eat(tt.comma)) return nodes
}
if (this.type === tt.star) {
var node$1 = this.startNode()
this.next()
this.expectContextual("as")
node$1.local = this.parseIdent()
this.checkLVal(node$1.local, "let")
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"))
return nodes
}
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node$2 = this$1.startNode()
node$2.imported = this$1.parseIdent(true)
if (this$1.eatContextual("as")) {
node$2.local = this$1.parseIdent()
} else {
node$2.local = node$2.imported
if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start)
if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved")
}
this$1.checkLVal(node$2.local, "let")
nodes.push(this$1.finishNode(node$2, "ImportSpecifier"))
}
return nodes
}
var pp$2 = Parser.prototype
// Convert existing expression atom to assignable pattern
// if possible.
pp$2.toAssignable = function(node, isBinding) {
var this$1 = this;
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
this.raise(node.start, "Can not use 'await' as identifier inside an async function")
break
case "ObjectPattern":
case "ArrayPattern":
break
case "ObjectExpression":
node.type = "ObjectPattern"
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i]
if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter")
this$1.toAssignable(prop.value, isBinding)
}
break
case "ArrayExpression":
node.type = "ArrayPattern"
this.toAssignableList(node.elements, isBinding)
break
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern"
delete node.operator
this.toAssignable(node.left, isBinding)
// falls through to AssignmentPattern
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
break
}
case "AssignmentPattern":
break
case "ParenthesizedExpression":
node.expression = this.toAssignable(node.expression, isBinding)
break
case "MemberExpression":
if (!isBinding) break
default:
this.raise(node.start, "Assigning to rvalue")
}
}
return node
}
// Convert list of expression atoms to binding list.
pp$2.toAssignableList = function(exprList, isBinding) {
var this$1 = this;
var end = exprList.length
if (end) {
var last = exprList[end - 1]
if (last && last.type == "RestElement") {
--end
} else if (last && last.type == "SpreadElement") {
last.type = "RestElement"
var arg = last.argument
this.toAssignable(arg, isBinding)
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern")
this.unexpected(arg.start)
--end
}
if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
this.unexpected(last.argument.start)
}
for (var i = 0; i < end; i++) {
var elt = exprList[i]
if (elt) this$1.toAssignable(elt, isBinding)
}
return exprList
}
// Parses spread element.
pp$2.parseSpread = function(refDestructuringErrors) {
var node = this.startNode()
this.next()
node.argument = this.parseMaybeAssign(false, refDestructuringErrors)
return this.finishNode(node, "SpreadElement")
}
pp$2.parseRest = function(allowNonIdent) {
var node = this.startNode()
this.next()
// RestElement inside of a function parameter must be an identifier
if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected()
else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected()
return this.finishNode(node, "RestElement")
}
// Parses lvalue (assignable) atom.
pp$2.parseBindingAtom = function() {
if (this.options.ecmaVersion < 6) return this.parseIdent()
switch (this.type) {
case tt.name:
return this.parseIdent()
case tt.bracketL:
var node = this.startNode()
this.next()
node.elements = this.parseBindingList(tt.bracketR, true, true)
return this.finishNode(node, "ArrayPattern")
case tt.braceL:
return this.parseObj(true)
default:
this.unexpected()
}
}
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (first) first = false
else this$1.expect(tt.comma)
if (allowEmpty && this$1.type === tt.comma) {
elts.push(null)
} else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
break
} else if (this$1.type === tt.ellipsis) {
var rest = this$1.parseRest(allowNonIdent)
this$1.parseBindingListItem(rest)
elts.push(rest)
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
this$1.expect(close)
break
} else {
var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc)
this$1.parseBindingListItem(elem)
elts.push(elem)
}
}
return elts
}
pp$2.parseBindingListItem = function(param) {
return param
}
// Parses assignment pattern around given atom if possible.
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom()
if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.right = this.parseMaybeAssign()
return this.finishNode(node, "AssignmentPattern")
}
// Verify that a node is an lval — something that can be assigned
// to.
// bindingType can be either:
// 'var' indicating that the lval creates a 'var' binding
// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
var this$1 = this;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
if (checkClashes) {
if (has(checkClashes, expr.name))
this.raiseRecoverable(expr.start, "Argument name clash")
checkClashes[expr.name] = true
}
if (bindingType && bindingType !== "none") {
if (
bindingType === "var" && !this.canDeclareVarName(expr.name) ||
bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
) {
this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"))
}
if (bindingType === "var") {
this.declareVarName(expr.name)
} else {
this.declareLexicalName(expr.name)
}
}
break
case "MemberExpression":
if (bindingType) this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression")
break
case "ObjectPattern":
for (var i = 0; i < expr.properties.length; i++)
this$1.checkLVal(expr.properties[i].value, bindingType, checkClashes)
break
case "ArrayPattern":
for (var i$1 = 0; i$1 < expr.elements.length; i$1++) {
var elem = expr.elements[i$1]
if (elem) this$1.checkLVal(elem, bindingType, checkClashes)
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, bindingType, checkClashes)
break
case "RestElement":
this.checkLVal(expr.argument, bindingType, checkClashes)
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, bindingType, checkClashes)
break
default:
this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue")
}
}
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
var pp$3 = Parser.prototype
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp$3.checkPropClash = function(prop, propHash) {
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
return
var key = prop.key;
var name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
propHash.proto = true
}
return
}
name = "$" + name
var other = propHash[name]
if (other) {
var redefinition
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set
} else {
redefinition = other.init || other[kind]
}
if (redefinition)
this.raiseRecoverable(key.start, "Redefinition of property")
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
}
}
other[kind] = true
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
if (this.type === tt.comma) {
var node = this.startNodeAt(startPos, startLoc)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.inGenerator && this.isContextual("yield")) return this.parseYield()
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign
oldTrailingComma = refDestructuringErrors.trailingComma
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
} else {
refDestructuringErrors = new DestructuringErrors
ownDestructuringErrors = true
}
var startPos = this.start, startLoc = this.startLoc
if (this.type == tt.parenL || this.type == tt.name)
this.potentialArrowAt = this.start
var left = this.parseMaybeConditional(noIn, refDestructuringErrors)
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
if (this.type.isAssign) {
this.checkPatternErrors(refDestructuringErrors, true)
if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
var node = this.startNodeAt(startPos, startLoc)
node.operator = this.value
node.left = this.type === tt.eq ? this.toAssignable(left) : left
refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
}
if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
return left
}
// Parse a ternary conditional (`?:`) operator.
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprOps(noIn, refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
if (this.eat(tt.question)) {
var node = this.startNodeAt(startPos, startLoc)
node.test = expr
node.consequent = this.parseMaybeAssign()
this.expect(tt.colon)
node.alternate = this.parseMaybeAssign(noIn)
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeUnary(refDestructuringErrors, false)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
var prec = this.type.binop
if (prec != null && (!noIn || this.type !== tt._in)) {
if (prec > minPrec) {
var logical = this.type === tt.logicalOR || this.type === tt.logicalAND
var op = this.value
this.next()
var startPos = this.start, startLoc = this.startLoc
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
}
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.operator = op
node.right = right
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
}
// Parse unary operators, both prefix and postfix.
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, expr
if (this.inAsync && this.isContextual("await")) {
expr = this.parseAwait(refDestructuringErrors)
sawUnary = true
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === tt.incDec
node.operator = this.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(null, true)
this.checkExpressionErrors(refDestructuringErrors, true)
if (update) this.checkLVal(node.argument)
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
else sawUnary = true
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else {
expr = this.parseExprSubscripts(refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.operator = this$1.value
node$1.prefix = false
node$1.argument = expr
this$1.checkLVal(expr)
this$1.next()
expr = this$1.finishNode(node$1, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar))
return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
else
return expr
}
// Parse call, dot, and `[]`-subscript expressions.
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprAtom(refDestructuringErrors)
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
var result = this.parseSubscripts(expr, startPos, startLoc)
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
}
return result
}
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
var this$1 = this;
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd == base.end && !this.canInsertSemicolon()
for (var computed;;) {
if ((computed = this$1.eat(tt.bracketL)) || this$1.eat(tt.dot)) {
var node = this$1.startNodeAt(startPos, startLoc)
node.object = base
node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true)
node.computed = !!computed
if (computed) this$1.expect(tt.bracketR)
base = this$1.finishNode(node, "MemberExpression")
} else if (!noCalls && this$1.eat(tt.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos
this$1.yieldPos = 0
this$1.awaitPos = 0
var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors)
if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) {
this$1.checkPatternErrors(refDestructuringErrors, false)
this$1.checkYieldAwaitInDefaultParams()
this$1.yieldPos = oldYieldPos
this$1.awaitPos = oldAwaitPos
return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
}
this$1.checkExpressionErrors(refDestructuringErrors, true)
this$1.yieldPos = oldYieldPos || this$1.yieldPos
this$1.awaitPos = oldAwaitPos || this$1.awaitPos
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.callee = base
node$1.arguments = exprList
base = this$1.finishNode(node$1, "CallExpression")
} else if (this$1.type === tt.backQuote) {
var node$2 = this$1.startNodeAt(startPos, startLoc)
node$2.tag = base
node$2.quasi = this$1.parseTemplate()
base = this$1.finishNode(node$2, "TaggedTemplateExpression")
} else {
return base
}
}
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$3.parseExprAtom = function(refDestructuringErrors) {
var node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._super:
if (!this.inFunction)
this.raise(this.start, "'super' outside of function or class")
case tt._this:
var type = this.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
var startPos = this.start, startLoc = this.startLoc
var id = this.parseIdent(this.type !== tt.name)
if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true)
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) {
id = this.parseIdent()
if (this.canInsertSemicolon() || !this.eat(tt.arrow))
this.unexpected()
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case tt.regexp:
var value = this.value
node = this.parseLiteral(value.value)
node.regex = {pattern: value.pattern, flags: value.flags}
return node
case tt.num: case tt.string:
return this.parseLiteral(this.value)
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.type === tt._null ? null : this.type === tt._true
node.raw = this.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
refDestructuringErrors.parenthesizedAssign = start
if (refDestructuringErrors.parenthesizedBind < 0)
refDestructuringErrors.parenthesizedBind = start
}
return expr
case tt.bracketL:
node = this.startNode()
this.next()
node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj(false, refDestructuringErrors)
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._class:
return this.parseClass(this.startNode(), false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
this.unexpected()
}
}
pp$3.parseLiteral = function(value) {
var node = this.startNode()
node.value = value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "Literal")
}
pp$3.parseParenExpression = function() {
this.expect(tt.parenL)
var val = this.parseExpression()
this.expect(tt.parenR)
return val
}
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
if (this.options.ecmaVersion >= 6) {
this.next()
var innerStartPos = this.start, innerStartLoc = this.startLoc
var exprList = [], first = true, lastIsComma = false
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart
this.yieldPos = 0
this.awaitPos = 0
while (this.type !== tt.parenR) {
first ? first = false : this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) {
lastIsComma = true
break
} else if (this$1.type === tt.ellipsis) {
spreadStart = this$1.start
exprList.push(this$1.parseParenItem(this$1.parseRest()))
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
break
} else {
if (this$1.type === tt.parenL && !innerParenStart) {
innerParenStart = this$1.start
}
exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem))
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc
this.expect(tt.parenR)
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
if (innerParenStart) this.unexpected(innerParenStart)
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
if (spreadStart) this.unexpected(spreadStart)
this.checkExpressionErrors(refDestructuringErrors, true)
this.yieldPos = oldYieldPos || this.yieldPos
this.awaitPos = oldAwaitPos || this.awaitPos
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc)
val.expressions = exprList
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
} else {
val = exprList[0]
}
} else {
val = this.parseParenExpression()
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc)
par.expression = val
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
}
pp$3.parseParenItem = function(item) {
return item
}
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty$1 = []
pp$3.parseNew = function() {
var node = this.startNode()
var meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
if (node.property.name !== "target")
this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
if (!this.inFunction)
this.raiseRecoverable(node.start, "new.target can only be used in functions")
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
else node.arguments = empty$1
return this.finishNode(node, "NewExpression")
}
// Parse template expression.
pp$3.parseTemplateElement = function() {
var elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
}
this.next()
elem.tail = this.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
pp$3.parseTemplate = function() {
var this$1 = this;
var node = this.startNode()
this.next()
node.expressions = []
var curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this$1.expect(tt.dollarBraceL)
node.expressions.push(this$1.parseExpression())
this$1.expect(tt.braceR)
node.quasis.push(curElt = this$1.parseTemplateElement())
}
this.next()
return this.finishNode(node, "TemplateLiteral")
}
// Parse an object literal or binding pattern.
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
var this$1 = this;
var node = this.startNode(), first = true, propHash = {}
node.properties = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc
if (this$1.options.ecmaVersion >= 6) {
prop.method = false
prop.shorthand = false
if (isPattern || refDestructuringErrors) {
startPos = this$1.start
startLoc = this$1.startLoc
}
if (!isPattern)
isGenerator = this$1.eat(tt.star)
}
this$1.parsePropertyName(prop)
if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed &&
prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL &&
this$1.type !== tt.colon && !this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(prop, refDestructuringErrors)
} else {
isAsync = false
}
this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors)
this$1.checkPropClash(prop, propHash)
node.properties.push(this$1.finishNode(prop, "Property"))
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
if ((isGenerator || isAsync) && this.type === tt.colon)
this.unexpected()
if (this.eat(tt.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
prop.kind = "init"
} else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
if (isPattern) this.unexpected()
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator, isAsync)
} else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type != tt.comma && this.type != tt.braceR)) {
if (isGenerator || isAsync || isPattern) this.unexpected()
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
var paramCount = prop.kind === "get" ? 0 : 1
if (prop.value.params.length !== paramCount) {
var start = prop.value.start
if (prop.kind === "get")
this.raiseRecoverable(start, "getter should have no params")
else
this.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (this.keywords.test(prop.key.name) ||
(this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) ||
(this.inGenerator && prop.key.name == "yield") ||
(this.inAsync && prop.key.name == "await"))
this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property")
prop.kind = "init"
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else if (this.type === tt.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
refDestructuringErrors.shorthandAssign = this.start
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else {
prop.value = prop.key
}
prop.shorthand = true
} else this.unexpected()
}
pp$3.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return prop.key
} else {
prop.computed = false
}
}
return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
}
// Initialize empty function node.
pp$3.initFunction = function(node) {
node.id = null
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
if (this.options.ecmaVersion >= 8)
node.async = false
}
// Parse object or class method.
pp$3.parseMethod = function(isGenerator, isAsync) {
var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.initFunction(node)
if (this.options.ecmaVersion >= 6)
node.generator = isGenerator
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
this.checkYieldAwaitInDefaultParams()
this.parseFunctionBody(node, false)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "FunctionExpression")
}
// Parse arrow function expression with given parameters.
pp$3.parseArrowExpression = function(node, params, isAsync) {
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.enterFunctionScope()
this.initFunction(node)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = false
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
node.params = this.toAssignableList(params, true)
this.parseFunctionBody(node, true)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "ArrowFunctionExpression")
}
// Parse function body and check parameters.
pp$3.parseFunctionBody = function(node, isArrowFunction) {
var isExpression = isArrowFunction && this.type !== tt.braceL
var oldStrict = this.strict, useStrict = false
if (isExpression) {
node.body = this.parseMaybeAssign()
node.expression = true
this.checkParams(node, false)
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end)
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list")
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels
this.labels = []
if (useStrict) this.strict = true
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params))
node.body = this.parseBlock(false)
node.expression = false
this.labels = oldLabels
}
this.exitFunctionScope()
if (this.strict && node.id) {
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
this.checkLVal(node.id, "none")
}
this.strict = oldStrict
}
pp$3.isSimpleParamList = function(params) {
for (var i = 0; i < params.length; i++)
if (params[i].type !== "Identifier") return false
return true
}
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp$3.checkParams = function(node, allowDuplicates) {
var this$1 = this;
var nameHash = {}
for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], "var", allowDuplicates ? null : nameHash)
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (!first) {
this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(close)) break
} else first = false
var elt
if (allowEmpty && this$1.type === tt.comma)
elt = null
else if (this$1.type === tt.ellipsis) {
elt = this$1.parseSpread(refDestructuringErrors)
if (refDestructuringErrors && this$1.type === tt.comma && refDestructuringErrors.trailingComma < 0)
refDestructuringErrors.trailingComma = this$1.start
} else {
elt = this$1.parseMaybeAssign(false, refDestructuringErrors)
}
elts.push(elt)
}
return elts
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp$3.parseIdent = function(liberal) {
var node = this.startNode()
if (liberal && this.options.allowReserved == "never") liberal = false
if (this.type === tt.name) {
if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) &&
(this.options.ecmaVersion >= 6 ||
this.input.slice(this.start, this.end).indexOf("\\") == -1))
this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved")
if (this.inGenerator && this.value === "yield")
this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator")
if (this.inAsync && this.value === "await")
this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function")
node.name = this.value
} else if (liberal && this.type.keyword) {
node.name = this.type.keyword
} else {
this.unexpected()
}
this.next()
return this.finishNode(node, "Identifier")
}
// Parses yield expression inside generator.
pp$3.parseYield = function() {
if (!this.yieldPos) this.yieldPos = this.start
var node = this.startNode()
this.next()
if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
pp$3.parseAwait = function() {
if (!this.awaitPos) this.awaitPos = this.start
var node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(null, true)
return this.finishNode(node, "AwaitExpression")
}
var pp$4 = Parser.prototype
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos)
message += " (" + loc.line + ":" + loc.column + ")"
var err = new SyntaxError(message)
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
throw err
}
pp$4.raiseRecoverable = pp$4.raise
pp$4.curPosition = function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
}
var pp$5 = Parser.prototype
// Object.assign polyfill
var assign = Object.assign || function(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
for (var i = 0; i < sources.length; i++) {
var source = sources[i]
for (var key in source) {
if (has(source, key)) {
target[key] = source[key]
}
}
}
return target
}
// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
pp$5.enterFunctionScope = function() {
// var: a hash of var-declared names in the current lexical scope
// lexical: a hash of lexically-declared names in the current lexical scope
// childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
// parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}})
}
pp$5.exitFunctionScope = function() {
this.scopeStack.pop()
}
pp$5.enterLexicalScope = function() {
var parentScope = this.scopeStack[this.scopeStack.length - 1]
var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}}
this.scopeStack.push(childScope)
assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical)
}
pp$5.exitLexicalScope = function() {
var childScope = this.scopeStack.pop()
var parentScope = this.scopeStack[this.scopeStack.length - 1]
assign(parentScope.childVar, childScope.var, childScope.childVar)
}
/**
* A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
* in the current lexical scope or any of the parent lexical scopes in this function.
*/
pp$5.canDeclareVarName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
}
/**
* A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
* in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
* any child lexical scopes in this function.
*/
pp$5.canDeclareLexicalName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
}
pp$5.declareVarName = function(name) {
this.scopeStack[this.scopeStack.length - 1].var[name] = true
}
pp$5.declareLexicalName = function(name) {
this.scopeStack[this.scopeStack.length - 1].lexical[name] = true
}
var Node = function Node(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
};
// Start an AST node, attaching a start offset.
var pp$6 = Parser.prototype
pp$6.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp$6.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp$6.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp$6.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token
this.isExpr = !!isExpr
this.preserveSpace = !!preserveSpace
this.override = override
this.generator = !!generator
};
var types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
}
var pp$7 = Parser.prototype
pp$7.initialContext = function() {
return [types.b_stat]
}
pp$7.braceIsBlock = function(prevType) {
if (prevType === tt.colon) {
var parent = this.curContext()
if (parent === types.b_stat || parent === types.b_expr)
return !parent.isExpr
}
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR || prevType == tt.arrow)
return true
if (prevType == tt.braceL)
return this.curContext() === types.b_stat
return !this.exprAllowed
}
pp$7.inGeneratorContext = function() {
var this$1 = this;
for (var i = this.context.length - 1; i >= 0; i--)
if (this$1.context[i].generator) return true
return false
}
pp$7.updateContext = function(prevType) {
var update, type = this.type
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false
else if (update = type.updateContext)
update.call(this, prevType)
else
this.exprAllowed = type.beforeExpr
}
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true
return
}
var out = this.context.pop(), cur
if (out === types.b_stat && (cur = this.curContext()) && cur.token === "function") {
this.context.pop()
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
}
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr)
this.exprAllowed = true
}
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl)
this.exprAllowed = true
}
tt.parenL.updateContext = function(prevType) {
var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while
this.context.push(statementParens ? types.p_stat : types.p_expr)
this.exprAllowed = true
}
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
}
tt._function.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else &&
!((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat))
this.context.push(types.f_expr)
this.exprAllowed = false
}
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop()
else
this.context.push(types.q_tmpl)
this.exprAllowed = false
}
tt.star.updateContext = function(prevType) {
if (prevType == tt._function) {
if (this.curContext() === types.f_expr)
this.context[this.context.length - 1] = types.f_expr_gen
else
this.context.push(types.f_gen)
}
this.exprAllowed = true
}
tt.name.updateContext = function(prevType) {
var allowed = false
if (this.options.ecmaVersion >= 6) {
if (this.value == "of" && !this.exprAllowed ||
this.value == "yield" && this.inGeneratorContext())
allowed = true
}
this.exprAllowed = allowed
}
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
var Token = function Token(p) {
this.type = p.type
this.value = p.value
this.start = p.start
this.end = p.end
if (p.options.locations)
this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
if (p.options.ranges)
this.range = [p.start, p.end]
};
// ## Tokenizer
var pp$8 = Parser.prototype
// Are we running under Rhino?
var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
// Move to the next token
pp$8.next = function() {
if (this.options.onToken)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end
this.lastTokStart = this.start
this.lastTokEndLoc = this.endLoc
this.lastTokStartLoc = this.startLoc
this.nextToken()
}
pp$8.getToken = function() {
this.next()
return new Token(this)
}
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
pp$8[Symbol.iterator] = function() {
var this$1 = this;
return {
next: function () {
var token = this$1.getToken()
return {
done: token.type === tt.eof,
value: token
}
}
}
}
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp$8.curContext = function() {
return this.context[this.context.length - 1]
}
// Read a single token, updating the parser object's token-related
// properties.
pp$8.nextToken = function() {
var curContext = this.curContext()
if (!curContext || !curContext.preserveSpace) this.skipSpace()
this.start = this.pos
if (this.options.locations) this.startLoc = this.curPosition()
if (this.pos >= this.input.length) return this.finishToken(tt.eof)
if (curContext.override) return curContext.override(this)
else this.readToken(this.fullCharCodeAtPos())
}
pp$8.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
return this.readWord()
return this.getTokenFromCode(code)
}
pp$8.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos)
if (code <= 0xd7ff || code >= 0xe000) return code
var next = this.input.charCodeAt(this.pos + 1)
return (code << 10) + next - 0x35fdc00
}
pp$8.skipBlockComment = function() {
var this$1 = this;
var startLoc = this.options.onComment && this.curPosition()
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + 2
if (this.options.locations) {
lineBreakG.lastIndex = start
var match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this$1.curLine
this$1.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
}
pp$8.skipLineComment = function(startSkip) {
var this$1 = this;
var start = this.pos
var startLoc = this.options.onComment && this.curPosition()
var ch = this.input.charCodeAt(this.pos += startSkip)
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this$1.pos
ch = this$1.input.charCodeAt(this$1.pos)
}
if (this.options.onComment)
this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition())
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp$8.skipSpace = function() {
var this$1 = this;
loop: while (this.pos < this.input.length) {
var ch = this$1.input.charCodeAt(this$1.pos)
switch (ch) {
case 32: case 160: // ' '
++this$1.pos
break
case 13:
if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
++this$1.pos
}
case 10: case 8232: case 8233:
++this$1.pos
if (this$1.options.locations) {
++this$1.curLine
this$1.lineStart = this$1.pos
}
break
case 47: // '/'
switch (this$1.input.charCodeAt(this$1.pos + 1)) {
case 42: // '*'
this$1.skipBlockComment()
break
case 47:
this$1.skipLineComment(2)
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this$1.pos
} else {
break loop
}
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp$8.finishToken = function(type, val) {
this.end = this.pos
if (this.options.locations) this.endLoc = this.curPosition()
var prevType = this.type
this.type = type
this.value = val
this.updateContext(prevType)
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$8.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1)
if (next >= 48 && next <= 57) return this.readNumber(true)
var next2 = this.input.charCodeAt(this.pos + 2)
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3
return this.finishToken(tt.ellipsis)
} else {
++this.pos
return this.finishToken(tt.dot)
}
}
pp$8.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1)
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.slash, 1)
}
pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
var tokentype = code === 42 ? tt.star : tt.modulo
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && next === 42) {
++size
tokentype = tt.starstar
next = this.input.charCodeAt(this.pos + 2)
}
if (next === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tokentype, size)
}
pp$8.readToken_pipe_amp = function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
}
pp$8.readToken_caret = function() { // '^'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.bitwiseXOR, 1)
}
pp$8.readToken_plus_min = function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3)
this.skipSpace()
return this.nextToken()
}
return this.finishOp(tt.incDec, 2)
}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.plusMin, 1)
}
pp$8.readToken_lt_gt = function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tt.bitShift, size)
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected()
// `