diff --git a/dist/engine.bundle.js b/dist/engine.bundle.js index f4a0d43ed..2a25c8efb 100644 --- a/dist/engine.bundle.js +++ b/dist/engine.bundle.js @@ -1,74647 +1,2 @@ -/******/ (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.Energy, "$0.000a") + "
" + - "Recommended starting Industry: NO", - Utilities: "Distributes water and provides wastewater services.

" + - "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.Food, "$0.000a") + "
" + - "Recommended starting Industry: YES", - Tobacco: "Create and distribute tobacco and tobacco-related products.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Tobacco, "$0.000a") + "
" + - "Recommended starting Industry: YES", - Chemical: "Product industrial chemicals

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Chemical, "$0.000a") + "
" + - "Recommended starting Industry: NO", - Pharmaceutical: "Discover, develop, and create new pharmaceutical drugs.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Pharmaceutical, "$0.000a") + "
" + - "Recommended starting Industry: NO", - Computer: "Develop and manufacture new computer hardware and networking infrastructures.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Computer, "$0.000a") + "
" + - "Recommended starting Industry: NO", - Robotics: "Develop and create robots.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Robotics, "$0.000a") + "
" + - "Recommended starting Industry: NO", - Software: "Develop computer software and create AI Cores.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Software, "$0.000a") + "
" + - "Recommended starting Industry: YES", - Healthcare: "Create and manage hospitals.

" + - "Starting cost: " + numeralFormat_1.numeralWrapper.format(exports.IndustryStartingCosts.Healthcare, "$0.000a") + "
" + - "Recommended starting Industry: NO", - RealEstate: "Develop and manage real estate properties.

" + - "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:

" + - "skill level [skill name]", - start:"start [type] [name]

" + - "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:

" + - "[general, contract, op, blackop]

" + - "Examples:

" + - 'start contract Tracking
' + - 'start op "Undercover Operation"
', - stop:"stop

" + - "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) + "%

" + - "Team Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.teamSize, 0) + "
" + - "Team Members Lost: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.teamLost, 0) + "

" + - "Num Times Hospitalized: " + this.numHosp + "
" + - "Money Lost From Hospitalizations: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__["numeralWrapper"].format(this.moneyLost, "$0.000a") + "

" + - "Current City: " + this.city + "
"; - - DomElems.overviewEstPop.childNodes[0].nodeValue = "Est. Synthoid Population: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__["numeralWrapper"].format(this.getCurrentCity().popEst, "0.000a"); - DomElems.overviewEstComms.childNodes[0].nodeValue = "Est. Synthoid Communities: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.getCurrentCity().comms, 0); - DomElems.overviewChaos.childNodes[0].nodeValue = "City Chaos: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.getCurrentCity().chaos); - DomElems.overviewSkillPoints.innerText = "Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.skillPoints, 0); - DomElems.overviewBonusTime.childNodes[0].nodeValue = "Bonus time: " + this.storedCycles/CyclesPerSecond; - DomElems.overviewAugSuccessMult.innerText = "Aug. Success Chance Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_success_chance_mult*100, 1) + "%"; - DomElems.overviewAugMaxStaminaMult.innerText = "Aug. Max Stamina Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_max_stamina_mult*100, 1) + "%"; - DomElems.overviewAugStaminaGainMult.innerText = "Aug. Stamina Gain Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_stamina_gain_mult*100, 1) + "%"; - DomElems.overviewAugAnalysisMult.innerText = "Aug. Field Analysis Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner_analysis_mult*100, 1) + "%"; -} - -Bladeburner.prototype.updateActionAndSkillsContent = function() { - if (DomElems.currentTab == null) {DomElems.currentTab = "general";} - switch(DomElems.currentTab.toLowerCase()) { - case "general": - var actionElems = Object.keys(DomElems.generalActions); - for (var i = 0; i < actionElems.length; ++i) { - var actionElem = DomElems.generalActions[actionElems[i]]; - var name = actionElem.name; - var actionObj = GeneralActions[name]; - if (actionObj == null) { - throw new Error("Could not find Object " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - if (this.action.type === ActionTypes[name]) { - actionElem.classList.add(ActiveActionCssClass); - } else { - actionElem.classList.remove(ActiveActionCssClass); - } - this.updateGeneralActionsUIElement(actionElem, actionObj); - } - break; - case "contracts": - var contractElems = Object.keys(DomElems.contracts); - for (var i = 0; i < contractElems.length; ++i) { - var contractElem = DomElems.contracts[contractElems[i]]; - var name = contractElem.name; - if (this.action.type === ActionTypes["Contract"] && name === this.action.name) { - contractElem.classList.add(ActiveActionCssClass); - } else { - contractElem.classList.remove(ActiveActionCssClass); - } - var contract = this.contracts[name]; - if (contract == null) { - throw new Error("Could not find Contract " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateContractsUIElement(contractElem, contract); - } - break; - case "operations": - var operationElems = Object.keys(DomElems.operations); - for (var i = 0; i < operationElems.length; ++i) { - var operationElem = DomElems.operations[operationElems[i]]; - var name = operationElem.name; - if (this.action.type === ActionTypes["Operation"] && name === this.action.name) { - operationElem.classList.add(ActiveActionCssClass); - } else { - operationElem.classList.remove(ActiveActionCssClass); - } - var operation = this.operations[name]; - if (operation == null) { - throw new Error("Could not find Operation " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateOperationsUIElement(operationElem, operation); - } - break; - case "blackops": - var blackopsElems = Object.keys(DomElems.blackops); - for (var i = 0; i < blackopsElems.length; ++i) { - var blackopElem = DomElems.blackops[blackopsElems[i]]; - var name = blackopElem.name; - if (this.action.type === ActionTypes["BlackOperation"] && name === this.action.name) { - blackopElem.classList.add(ActiveActionCssClass); - } else { - blackopElem.classList.remove(ActiveActionCssClass); - } - var blackop = BlackOperations[name]; - if (blackop == null) { - throw new Error("Could not find BlackOperation " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateBlackOpsUIElement(blackopElem, blackop); - } - break; - case "skills": - DomElems.skillPointsDisplay.innerHTML = "
Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.skillPoints, 0) + ""; - - var skillElems = Object.keys(DomElems.skills); - for (var i = 0; i < skillElems.length; ++i) { - var skillElem = DomElems.skills[skillElems[i]]; - var name = skillElem.name; - var skill = Skills[name]; - if (skill == null) { - throw new Error("Could not find Skill " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateSkillsUIElement(skillElem, skill); - } - break; - default: - throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent"); - } -} - -Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { // Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block", - })); - - if (isActive) { // Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", - innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__["createProgressBarText"])({progress:progress}) - })); - } else { - // Start button - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - this.action.type = ActionTypes[action.name]; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - } - - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", { // Info - innerHTML:action.desc, display:"inline-block" - })); - - -} - -Bladeburner.prototype.updateContractsUIElement = function(el, action) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { // Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block" - })); - - if (isActive) { // Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", - innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__["createProgressBarText"])({progress:progress}) - })); - } else { // Start button - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - padding:"3px", margin:"3px", - clickListener:()=>{ - this.action.type = ActionTypes.Contract; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - } - - // Level and buttons to change level - var maxLevel = (action.level >= action.maxLevel); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", { - display:"inline-block", - innerText:"Level: " + action.level + " / " + action.maxLevel, - tooltip:action.getSuccessesNeededForNextLevel(ContractSuccessesPerLevel) + " successes " + - "needed for next level" - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", - display:"inline", - clickListener:()=>{ - ++action.level; - if (isActive) {this.startAction(this.action);} // Restart Action - this.updateContractsUIElement(el, action); - return false; - } - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", - display:"inline", - clickListener:()=>{ - --action.level; - if (isActive) {this.startAction(this.action);} // Restart Action - this.updateContractsUIElement(el, action); - return false; - } - })); - - var actionTime = action.getActionTime(this); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", { // Info - display:"inline-block", - innerHTML:action.desc + "\n\n" + - `Estimated success chance: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(estimatedSuccessChance*100, 1)}% ${action.isStealth?stealthIcon:''}${action.isKill?killIcon:''}\n` + - - "Time Required (s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(actionTime, 0) + "\n" + - "Contracts remaining: " + Math.floor(action.count) + "\n" + - "Successes: " + action.successes + "\n" + - "Failures: " + action.failures, - })); - - // Autolevel Checkbox - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("br")); - var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("label", { - for:autolevelCheckboxId, innerText:"Autolevel",color:"white", - tooltip:"Automatically increase contract level when possible" - })); - - const checkboxDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", { class: "bbcheckbox" }); - const checkboxInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", { - type:"checkbox", - id: autolevelCheckboxId, - checked: action.autoLevel, - changeListener: () => { - action.autoLevel = checkboxInput.checked; - }, - }); - const checkmarkLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("label", { for: autolevelCheckboxId }); - checkboxDiv.appendChild(checkboxInput); - checkboxDiv.appendChild(checkmarkLabel); - - el.appendChild(checkboxDiv); -} - -Bladeburner.prototype.updateOperationsUIElement = function(el, action) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { // Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block" - })); - - if (isActive) { // Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", - innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__["createProgressBarText"])({progress:progress}) - })); - } else { // Start button and set Team Size button - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - this.action.type = ActionTypes.Operation; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - var popupId = "bladeburner-operation-set-team-size-popup"; - var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - innerText:"Enter the amount of team members you would like to take on these " + - "operations. If you do not have the specified number of team members, " + - "then as many as possible will be used. Note that team members may " + - "be lost during operations." - - }); - var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", { - type:"number", placeholder: "Team Members" - }); - var setBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Confirm", class:"a-link-button", - clickListener:()=>{ - var num = Math.round(parseFloat(input.value)); - if (isNaN(num)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") - } else { - action.teamCount = num; - this.updateOperationsUIElement(el, action); - } - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId); - return false; - } - }); - var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Cancel", class:"a-link-button", - clickListener:()=>{ - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId); - return false; - } - }); - Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); - } - })); - } - - // Level and buttons to change level - var maxLevel = (action.level >= action.maxLevel); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", { - display:"inline-block", - innerText:"Level: " + action.level + " / " + action.maxLevel, - tooltip:action.getSuccessesNeededForNextLevel(OperationSuccessesPerLevel) + " successes " + - "needed for next level" - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", - display:"inline", - clickListener:()=>{ - ++action.level; - if (isActive) {this.startAction(this.action);} // Restart Action - this.updateOperationsUIElement(el, action); - return false; - } - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", - display:"inline", - clickListener:()=>{ - --action.level; - if (isActive) {this.startAction(this.action);} // Restart Action - this.updateOperationsUIElement(el, action); - return false; - } - })); - - // General Info - var difficulty = action.getDifficulty(); - var actionTime = action.getActionTime(this); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("pre", { - display:"inline-block", - innerHTML:action.desc + "\n\n" + - `Estimated success chance: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(estimatedSuccessChance*100, 1)}% ${action.isStealth?stealthIcon:''}${action.isKill?killIcon:''}\n` + - "Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(actionTime, 0) + "\n" + - "Operations remaining: " + Math.floor(action.count) + "\n" + - "Successes: " + action.successes + "\n" + - "Failures: " + action.failures, - })); - - // Autolevel Checkbox - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("br")); - var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("label", { - for:autolevelCheckboxId, innerText:"Autolevel",color:"white", - tooltip:"Automatically increase operation level when possible" - })); - - const checkboxDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("div", { class: "bbcheckbox" }); - const checkboxInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", { - type:"checkbox", - id: autolevelCheckboxId, - checked: action.autoLevel, - changeListener: () => { - action.autoLevel = checkboxInput.checked; - }, - }); - const checkmarkLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("label", { for: autolevelCheckboxId }); - checkboxDiv.appendChild(checkboxInput); - checkboxDiv.appendChild(checkmarkLabel); - - el.appendChild(checkboxDiv); -} - -Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var isCompleted = (this.blackops[action.name] != null); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - var difficulty = action.getDifficulty(); - var actionTime = action.getActionTime(this); - var hasReqdRank = this.rank >= action.reqdRank; - - // UI for Completed Black Op - if (isCompleted) { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { - innerText:action.name + " (COMPLETED)", display:"block", - })); - return; - } - - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { // Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block", - })); - - if (isActive) { // Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", - innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_18__["createProgressBarText"])({progress:progress}) - })); - } else { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { // Start button - innerText:"Start", margin:"3px", padding:"3px", - class:hasReqdRank ? "a-link-button" : "a-link-button-inactive", - clickListener:()=>{ - this.action.type = ActionTypes.BlackOperation; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { // Set Team Size Button - innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - var popupId = "bladeburner-operation-set-team-size-popup"; - var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - innerText:"Enter the amount of team members you would like to take on this " + - "BlackOp. If you do not have the specified number of team members, " + - "then as many as possible will be used. Note that team members may " + - "be lost during operations." - - }); - var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("input", { - type:"number", placeholder: "Team Members" - }); - var setBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Confirm", class:"a-link-button", - clickListener:()=>{ - var num = Math.round(parseFloat(input.value)); - if (isNaN(num)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") - } else { - action.teamCount = num; - this.updateBlackOpsUIElement(el, action); - } - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId); - return false; - } - }); - var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { - innerText:"Cancel", class:"a-link-button", - clickListener:()=>{ - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId); - return false; - } - }); - Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_26__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); - } - })); - } - - // Info - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"inline-block", - innerHTML:"
" + action.desc + "

", - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", color:hasReqdRank ? "white" : "red", - innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(action.reqdRank, 0) + "
" - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"inline-block", - innerHTML:`Estimated Success Chance: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(estimatedSuccessChance*100, 1)}% ${action.isStealth?stealthIcon:''}${action.isKill?killIcon:''}\n` + - "Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(actionTime, 0), - })) -} - -Bladeburner.prototype.updateSkillsUIElement = function(el, skill) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_23__["removeChildrenFromElement"])(el); - var skillName = skill.name; - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var pointCost = skill.calculateCost(currentLevel); - - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("h2", { // Header - innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block" - })); - - var canLevel = this.skillPoints >= pointCost; - var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("a", { // Level up button - innerText:"Level", display:"inline-block", - class: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive", - margin:"3px", padding:"3px", - clickListener:()=>{ - if (this.skillPoints < pointCost) {return;} - this.skillPoints -= pointCost; - this.upgradeSkill(skill); - this.createActionAndSkillsContent(); - return false; - } - })); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_24__["appendLineBreaks"])(el, 2); - if (maxLvl) { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - color:"red", display:"block", - innerText:"MAX LEVEL" - })); - } else { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { - display:"block", - innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["formatNumber"])(pointCost, 0), - })); - } - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_25__["createElement"])("p", { // Info/Description - innerHTML:skill.desc, display:"inline-block", - })); -} - -// Bladeburner Console Window -Bladeburner.prototype.postToConsole = function(input, saveToLogs=true) { - const MaxConsoleEntries = 100; - if (saveToLogs === true) { - this.consoleLogs.push(input); - if (this.consoleLogs.length > MaxConsoleEntries) { - this.consoleLogs.shift(); - } - } - - if (input == null || DomElems.consoleDiv == null) {return;} - $("#bladeubrner-console-input-row").before('' + input + ''); - - 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.

" + - "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", - baseDifficulty:70e3, reqdRank:300e3, - rankGain:15e3, rankLoss:5e3, 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}, - }); - BlackOperations["Operation Vindictus"] = new BlackOperation({ - name:"Operation Vindictus", - desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)

" + - "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:

" + - "while(true) {
" + - "  hack('foodnstuff');
" + - "}

" + - "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!

" + - "Getting Started Guide" + - "Documentation

" + - "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 + "

" + - "Filename: " + (e.fileName || "UNKNOWN FILE NAME") + "

" + - "Line Number: " + (e.lineNumber || "UNKNOWN LINE NUMBER") + "

" + - "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 = - `
[${_Player__WEBPACK_IMPORTED_MODULE_21__["Player"].getCurrentServer().hostname} ~${dir}]$
` + - '"; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; -} )(); -var documentElement = document.documentElement; - - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 only -// See #13393 for more info -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = {}; - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - // Make a writable jQuery.Event from the native event object - var event = jQuery.event.fix( nativeEvent ); - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || Date.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Includes all common event props including KeyEvent and MouseEvent specific props -jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - - which: function( event ) { - var button = event.button; - - // Add which for key events - if ( event.which == null && rkeyEvent.test( event.type ) ) { - return event.charCode != null ? event.charCode : event.keyCode; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { - if ( button & 1 ) { - return 1; - } - - if ( button & 2 ) { - return 3; - } - - if ( button & 4 ) { - return 2; - } - - return 0; - } - - return event.which; - } -}, jQuery.event.addProp ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - - /* eslint-disable max-len */ - - // See https://github.com/eslint/eslint/issues/3229 - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, - - /* eslint-enable */ - - // Support: IE <=10 - 11, Edge 12 - 13 only - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows -function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( elem ).children( "tbody" )[ 0 ] || elem; - } - - return elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { - elem.type = elem.type.slice( 5 ); - } else { - elem.removeAttribute( "type" ); - } - - return elem; -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.access( src ); - pdataCur = dataPriv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - valueIsFunction = isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( valueIsFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( valueIsFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node ); - } - } - } - } - } - } - - return collection; -} - -function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; -} - -jQuery.extend( { - htmlPrefilter: function( html ) { - return html.replace( rxhtmlTag, "<$1>" ); - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } -} ); - -jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } -} ); - -jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -} ); -var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - -var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - -var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); - - - -( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - container.style.cssText = "position:absolute;left:-11111px;width:60px;" + - "margin-top:1px;padding:0;border:0"; - div.style.cssText = - "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + - "margin:auto;border:1px;padding:1px;" + - "width:60%;top:1%"; - documentElement.appendChild( container ).appendChild( div ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - - // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 - // Some styles come back with percentage values, even though they shouldn't - div.style.right = "60%"; - pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; - - // Support: IE 9 - 11 only - // Detect misreporting of content dimensions for box-sizing:border-box elements - boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; - - // Support: IE 9 only - // Detect overflow:scroll screwiness (gh-3699) - div.style.position = "absolute"; - scrollboxSizeVal = div.offsetWidth === 36 || "absolute"; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - function roundPixelMeasures( measure ) { - return Math.round( parseFloat( measure ) ); - } - - var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, - reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - jQuery.extend( support, { - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelBoxStyles: function() { - computeStyleTests(); - return pixelBoxStylesVal; - }, - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - }, - scrollboxSize: function() { - computeStyleTests(); - return scrollboxSizeVal; - } - } ); -} )(); - - -function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; -} - - -function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; -} - - -var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }, - - cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style; - -// Return a css property mapped to a potentially vendor prefixed property -function vendorPropName( name ) { - - // Shortcut for names that are not vendor prefixed - if ( name in emptyStyle ) { - return name; - } - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } -} - -// Return a property mapped along what jQuery.cssProps suggests or to -// a vendor prefixed property. -function finalPropName( name ) { - var ret = jQuery.cssProps[ name ]; - if ( !ret ) { - ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; - } - return ret; -} - -function setPositiveNumber( elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; -} - -function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { - var i = dimension === "width" ? 1 : 0, - extra = 0, - delta = 0; - - // Adjustment may not be necessary - if ( box === ( isBorderBox ? "border" : "content" ) ) { - return 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin - if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); - } - - // If we get here with a content-box, we're seeking "padding" or "border" or "margin" - if ( !isBorderBox ) { - - // Add padding - delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // For "border" or "margin", add border - if ( box !== "padding" ) { - delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - - // But still keep track of it otherwise - } else { - extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - - // If we get here with a border-box (content + padding + border), we're seeking "content" or - // "padding" or "margin" - } else { - - // For "content", subtract padding - if ( box === "content" ) { - delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // For "content" or "padding", subtract border - if ( box !== "margin" ) { - delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - // Account for positive content-box scroll gutter when requested by providing computedVal - if ( !isBorderBox && computedVal >= 0 ) { - - // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border - // Assuming integer scroll gutter, subtract the rest and round down - delta += Math.max( 0, Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - computedVal - - delta - - extra - - 0.5 - ) ); - } - - return delta; -} - -function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - val = curCSS( elem, dimension, styles ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox; - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - // Check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = valueIsBorderBox && - ( support.boxSizingReliable() || val === elem.style[ dimension ] ); - - // Fall back to offsetWidth/offsetHeight when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - // Support: Android <=4.1 - 4.3 only - // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) - if ( val === "auto" || - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) { - - val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ]; - - // offsetWidth/offsetHeight provide border-box values - valueIsBorderBox = true; - } - - // Normalize "" and auto - val = parseFloat( val ) || 0; - - // Adjust for the element's box model - return ( val + - boxModelAdjustment( - elem, - dimension, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles, - - // Provide the current computed size to request scroll gutter calculation (gh-3589) - val - ) - ) + "px"; -} - -jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: {}, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - if ( type === "number" ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } -} ); - -jQuery.each( [ "height", "width" ], function( i, dimension ) { - jQuery.cssHooks[ dimension ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = getStyles( elem ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra && boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ); - - // Account for unreliable border-box dimensions by comparing offset* to computed and - // faking a content-box to get border and padding (gh-3699) - if ( isBorderBox && support.scrollboxSize() === styles.position ) { - subtract -= Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - parseFloat( styles[ dimension ] ) - - boxModelAdjustment( elem, dimension, "border", false, styles ) - - 0.5 - ); - } - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ dimension ] = value; - value = jQuery.css( elem, dimension ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; -} ); - -jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } -); - -// These hooks are used by animate to expand properties -jQuery.each( { - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( prefix !== "margin" ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -} ); - -jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } -} ); - - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && - ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || - jQuery.cssHooks[ tween.prop ] ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" -}; - -jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point -jQuery.fx.step = {}; - - - - -var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - -function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } -} - -// Animations created synchronously will run synchronously -function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = Date.now() ); -} - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } -} - -function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 15 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY and Edge just mirrors - // the overflowX value there. - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } -} - -function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - result.stop.bind( result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } -} ); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue && type !== false ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } -} ); - -jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -} ); - -// Generate shortcuts for custom animations -jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -} ); - -jQuery.timers = []; -jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = Date.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); -}; - -jQuery.fx.interval = 13; -jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); -}; - -jQuery.fx.stop = function() { - inProgress = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 -}; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ -jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); -}; - - -( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; -} )(); - - -var boolHook, - attrHandle = jQuery.expr.attrHandle; - -jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } -} ); - -jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } -} ); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; - -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; -} ); - - - - -var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - -jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } -} ); - -jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } -} ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop -if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; -} - -jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -} ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - -function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; -} - -function classesToArray( value ) { - if ( Array.isArray( value ) ) { - return value; - } - if ( typeof value === "string" ) { - return value.match( rnothtmlwhite ) || []; - } - return []; -} - -jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isValidValue = type === "string" || Array.isArray( value ); - - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( isValidValue ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = classesToArray( value ); - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } -} ); - - - - -var rreturn = /\r/g; - -jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, valueIsFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - valueIsFunction = isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( valueIsFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } -} ); - -jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } -} ); - -// Radios and checkboxes getter/setter -jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } -} ); - - - - -// Return jQuery for attributes-only inclusion - - -support.focusin = "onfocusin" in window; - - -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - stopPropagationCallback = function( e ) { - e.stopPropagation(); - }; - -jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = lastElement = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - lastElement = cur; - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - - if ( event.isPropagationStopped() ) { - lastElement.addEventListener( type, stopPropagationCallback ); - } - - elem[ type ](); - - if ( event.isPropagationStopped() ) { - lastElement.removeEventListener( type, stopPropagationCallback ); - } - - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - -} ); - -jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -} ); - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = Date.now(); - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; -}; - - -var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && toType( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } -} - -// Serialize an array of form elements or a set of -// key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); -}; - -jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ) - .filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ) - .map( function( i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } -} ); - - -var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -/* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -/* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ -function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; -} - -jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; - } - } - match = responseHeaders[ key.toLowerCase() ]; - } - return match == null ? null : match; - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 15 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available and should be processed, append data to url - if ( s.data && ( s.processData || typeof s.data === "string" ) ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } -} ); - -jQuery.each( [ "get", "post" ], function( i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; -} ); - - -jQuery._evalUrl = function( url ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - "throws": true - } ); -}; - - -jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var htmlIsFunction = isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } -} ); - - -jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); -}; -jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); -}; - - - - -jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} -}; - -var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - -support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -support.ajax = xhrSupported = !!xhrSupported; - -jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.ontimeout = - xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } -} ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) -jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } -} ); - -// Install script dataType -jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -} ); - -// Handle cache's special case and crossDomain -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } -} ); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain requests - if ( s.crossDomain ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( "