bitburner-src/dist/engine.bundle.js

58892 lines
2.8 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/******/ (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([8,0]);
/******/ // run deferred modules when ready
/******/ return checkDeferredModules();
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!***********************!*\
!*** ./src/Player.js ***!
\***********************/
/*! exports provided: Player, loadPlayer */
/*! exports used: Player, loadPlayer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Player; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return loadPlayer; });
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CodingContracts */ 40);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Company/Company */ 71);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Company_Company__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company/GetNextCompanyPosition */ 94);
/* harmony import */ var _Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Company/GetJobRequirementText */ 88);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Company/CompanyPositions */ 26);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Company/data/CompanyPositionNames */ 34);
/* harmony import */ var _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CompanyManagement */ 58);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Crimes */ 35);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Faction/Faction */ 54);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Gang */ 48);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./SourceFile */ 66);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! decimal.js */ 31);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/IPAddress */ 57);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__);
const CYCLES_PER_SEC = 1000 / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MilliPerCycle;
function PlayerObject() {
//Skills and stats
this.hacking_skill = 1;
//Combat stats
this.hp = 10;
this.max_hp = 10;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
//Labor stats
this.charisma = 1;
//Special stats
this.intelligence = 0;
//Hacking multipliers
this.hacking_chance_mult = 1;
this.hacking_speed_mult = 1;
this.hacking_money_mult = 1;
this.hacking_grow_mult = 1;
//Experience and multipliers
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.intelligence_exp= 0;
this.hacking_mult = 1;
this.strength_mult = 1;
this.defense_mult = 1;
this.dexterity_mult = 1;
this.agility_mult = 1;
this.charisma_mult = 1;
this.hacking_exp_mult = 1;
this.strength_exp_mult = 1;
this.defense_exp_mult = 1;
this.dexterity_exp_mult = 1;
this.agility_exp_mult = 1;
this.charisma_exp_mult = 1;
this.company_rep_mult = 1;
this.faction_rep_mult = 1;
//Money
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](1000);
this.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](0); //Total money ever earned in this "simulation"
this.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](0); //Total money ever earned
//IP Address of Starting (home) computer
this.homeComputer = "";
//Location information
this.city = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12;
this.location = "";
//Company Information
this.companyName = ""; // Name of Company. Must match a key value in Companies map
this.companyPosition = ""; // Name of Company Position. Must match a key value in CompanyPositions map
//Servers
this.currentServer = ""; //IP address of Server currently being accessed through terminal
this.purchasedServers = []; //IP Addresses of purchased servers
this.hacknetNodes = [];
this.totalHacknetNodeProduction = 0;
//Factions
this.factions = []; //Names of all factions player has joined
this.factionInvitations = []; //Outstanding faction invitations
//Augmentations
this.queuedAugmentations = [];
this.augmentations = [];
this.sourceFiles = [];
//Crime statistics
this.numPeopleKilled = 0;
this.karma = 0;
this.crime_money_mult = 1;
this.crime_success_mult = 1;
//Flags/variables for working (Company, Faction, Creating Program, Taking Class)
this.isWorking = false;
this.workType = "";
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workMoneyLossRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.createProgramName = "";
this.createProgramReqLvl = 0;
this.className = "";
this.crimeType = "";
this.timeWorked = 0; //in ms
this.timeWorkedCreateProgram = 0;
this.timeNeededToCompleteWork = 0;
this.work_money_mult = 1;
//Hacknet Node multipliers
this.hacknet_node_money_mult = 1;
this.hacknet_node_purchase_cost_mult = 1;
this.hacknet_node_ram_cost_mult = 1;
this.hacknet_node_core_cost_mult = 1;
this.hacknet_node_level_cost_mult = 1;
//Stock Market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
this.has4SData = false;
this.has4SDataTixApi = false;
//Gang
this.gang = 0;
//Corporation
this.corporation = 0;
//Bladeburner
this.bladeburner = 0;
this.bladeburner_max_stamina_mult = 1;
this.bladeburner_stamina_gain_mult = 1;
this.bladeburner_analysis_mult = 1; //Field Analysis Only
this.bladeburner_success_chance_mult = 1;
//bitnode
this.bitNodeN = 1;
//Flags for determining whether certain "thresholds" have been achieved
this.firstFacInvRecvd = false;
this.firstAugPurchased = false;
this.firstTimeTraveled = false;
this.firstProgramAvailable = false;
//Used to store the last update time.
this.lastUpdate = 0;
this.totalPlaytime = 0;
this.playtimeSinceLastAug = 0;
this.playtimeSinceLastBitnode = 0;
//Production since last Augmentation installation
this.scriptProdSinceLastAug = 0;
this.stockProdSinceLastAug = 0;
this.crimeProdSinceLastAug = 0;
this.jobProdSinceLastAug = 0;
};
PlayerObject.prototype.init = function() {
/* Initialize Player's home computer */
var t_homeComp = new _Server__WEBPACK_IMPORTED_MODULE_20__[/* Server */ "d"]({
ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_28__[/* createRandomIp */ "a"])(), hostname:"home", organizationName:"Home PC",
isConnectedTo:true, adminRights:true, purchasedByPlayer:true, maxRam:8
});
this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
Object(_Server__WEBPACK_IMPORTED_MODULE_20__[/* AddToAllServers */ "a"])(t_homeComp);
this.getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_11__[/* Programs */ "a"].NukeProgram.name);
}
PlayerObject.prototype.prestigeAugmentation = function() {
var homeComp = this.getHomeComputer();
this.currentServer = homeComp.ip;
this.homeComputer = homeComp.ip;
this.numPeopleKilled = 0;
this.karma = 0;
//Reset stats
this.hacking_skill = 1;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
this.charisma = 1;
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](1000);
this.city = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.isWorking = false;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
this.crimeType = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.lastUpdate = new Date().getTime();
this.playtimeSinceLastAug = 0;
this.scriptProdSinceLastAug = 0;
this.hacknetNodes.length = 0;
this.totalHacknetNodeProduction = 0;
//Re-calculate skills and reset HP
this.updateSkillLevels();
this.hp = this.max_hp;
}
PlayerObject.prototype.prestigeSourceFile = function() {
var homeComp = this.getHomeComputer();
this.currentServer = homeComp.ip;
this.homeComputer = homeComp.ip;
this.numPeopleKilled = 0;
this.karma = 0;
//Reset stats
this.hacking_skill = 1;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
this.charisma = 1;
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](1000);
this.city = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.augmentations = [];
this.isWorking = false;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
this.crimeType = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.lastUpdate = new Date().getTime();
this.hacknetNodes.length = 0;
this.totalHacknetNodeProduction = 0;
//Gang
this.gang = null;
Object(_Gang__WEBPACK_IMPORTED_MODULE_17__[/* resetGangs */ "d"])();
//Reset Stock market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
this.has4SData = false;
this.has4SDataTixApi = false;
//BitNode 3: Corporatocracy
if (this.bitNodeN === 3) {this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](150e9);}
this.corporation = 0;
this.playtimeSinceLastAug = 0;
this.playtimeSinceLastBitnode = 0;
this.scriptProdSinceLastAug = 0;
this.updateSkillLevels();
this.hp = this.max_hp;
}
PlayerObject.prototype.getCurrentServer = function() {
return _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][this.currentServer];
}
PlayerObject.prototype.getHomeComputer = function() {
return _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][this.homeComputer];
}
PlayerObject.prototype.getUpgradeHomeRamCost = function() {
//Calculate how many times ram has been upgraded (doubled)
const currentRam = Player.getHomeComputer().maxRam;
const numUpgrades = Math.log2(currentRam);
//Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded
const mult = Math.pow(1.58, numUpgrades);
var cost = currentRam * _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].BaseCostFor1GBOfRamHome * mult;
return cost;
}
PlayerObject.prototype.receiveInvite = function(factionName) {
if(this.factionInvitations.includes(factionName) || this.factions.includes(factionName)) {
return;
}
this.firstFacInvRecvd = true;
this.factionInvitations.push(factionName);
}
//Calculates skill level based on experience. The same formula will be used for every skill
PlayerObject.prototype.calculateSkill = function(exp, mult=1) {
return Math.max(Math.floor(mult*(32 * Math.log(exp + 534.5) - 200)), 1);
}
PlayerObject.prototype.updateSkillLevels = function() {
this.hacking_skill = Math.max(1, Math.floor(this.calculateSkill(this.hacking_exp, this.hacking_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackingLevelMultiplier)));
this.strength = this.calculateSkill(this.strength_exp, this.strength_mult);
this.defense = this.calculateSkill(this.defense_exp, this.defense_mult);
this.dexterity = this.calculateSkill(this.dexterity_exp, this.dexterity_mult);
this.agility = this.calculateSkill(this.agility_exp, this.agility_mult);
this.charisma = this.calculateSkill(this.charisma_exp, this.charisma_mult);
if (this.intelligence > 0) {
this.intelligence = Math.floor(this.calculateSkill(this.intelligence_exp));
} else {
this.intelligence = 0;
}
var ratio = this.hp / this.max_hp;
this.max_hp = Math.floor(10 + this.defense / 10);
Player.hp = Math.round(this.max_hp * ratio);
}
PlayerObject.prototype.resetMultipliers = function() {
this.hacking_chance_mult = 1;
this.hacking_speed_mult = 1;
this.hacking_money_mult = 1;
this.hacking_grow_mult = 1;
this.hacking_mult = 1;
this.strength_mult = 1;
this.defense_mult = 1;
this.dexterity_mult = 1;
this.agility_mult = 1;
this.charisma_mult = 1;
this.hacking_exp_mult = 1;
this.strength_exp_mult = 1;
this.defense_exp_mult = 1;
this.dexterity_exp_mult = 1;
this.agility_exp_mult = 1;
this.charisma_exp_mult = 1;
this.company_rep_mult = 1;
this.faction_rep_mult = 1;
this.crime_money_mult = 1;
this.crime_success_mult = 1;
this.hacknet_node_money_mult = 1;
this.hacknet_node_purchase_cost_mult = 1;
this.hacknet_node_ram_cost_mult = 1;
this.hacknet_node_core_cost_mult = 1;
this.hacknet_node_level_cost_mult = 1;
this.work_money_mult = 1;
this.bladeburner_max_stamina_mult = 1;
this.bladeburner_stamina_gain_mult = 1;
this.bladeburner_analysis_mult = 1;
this.bladeburner_success_chance_mult = 1;
}
PlayerObject.prototype.hasProgram = function(programName) {
var home = Player.getHomeComputer();
if (home == null) {return false;}
for (var i = 0; i < home.programs.length; ++i) {
if (programName.toLowerCase() == home.programs[i].toLowerCase()) {return true;}
}
return false;
}
PlayerObject.prototype.setMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.setMoney()"); return;
}
this.money = money;
}
PlayerObject.prototype.gainMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.gainMoney()"); return;
}
this.money = this.money.plus(money);
this.total_money = this.total_money.plus(money);
this.lifetime_money = this.lifetime_money.plus(money);
}
PlayerObject.prototype.loseMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.loseMoney()"); return;
}
this.money = this.money.minus(money);
}
PlayerObject.prototype.gainHackingExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainHackingExp()"); return;
}
this.hacking_exp += exp;
if(this.hacking_exp < 0) {
this.hacking_exp = 0;
}
}
PlayerObject.prototype.gainStrengthExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainStrengthExp()"); return;
}
this.strength_exp += exp;
if(this.strength_exp < 0) {
this.strength_exp = 0;
}
}
PlayerObject.prototype.gainDefenseExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into player.gainDefenseExp()"); return;
}
this.defense_exp += exp;
if(this.defense_exp < 0) {
this.defense_exp = 0;
}
}
PlayerObject.prototype.gainDexterityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainDexterityExp()"); return;
}
this.dexterity_exp += exp;
if(this.dexterity_exp < 0) {
this.dexterity_exp = 0;
}
}
PlayerObject.prototype.gainAgilityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainAgilityExp()"); return;
}
this.agility_exp += exp;
if(this.agility_exp < 0) {
this.agility_exp = 0;
}
}
PlayerObject.prototype.gainCharismaExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainCharismaExp()"); return;
}
this.charisma_exp += exp;
if(this.charisma_exp < 0) {
this.charisma_exp = 0;
}
}
PlayerObject.prototype.gainIntelligenceExp = function(exp) {
if (isNaN(exp)) {
console.log("ERROR: NaN passed into Player.gainIntelligenceExp()"); return;
}
if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_19__[/* hasAISF */ "b"] || this.intelligence > 0) {
this.intelligence_exp += exp;
}
}
//Given a string expression like "str" or "strength", returns the given stat
PlayerObject.prototype.queryStatFromString = function(str) {
const tempStr = str.toLowerCase();
if (tempStr.includes("hack")) {return Player.hacking_skill;}
if (tempStr.includes("str")) {return Player.strength;}
if (tempStr.includes("def")) {return Player.defense;}
if (tempStr.includes("dex")) {return Player.dexterity;}
if (tempStr.includes("agi")) {return Player.agility;}
if (tempStr.includes("cha")) {return Player.charisma;}
if (tempStr.includes("int")) {return Player.intelligence;}
}
/******* Working functions *******/
PlayerObject.prototype.resetWorkStatus = function() {
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workMoneyLossRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.timeWorkedCreateProgram = 0;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
document.getElementById("work-in-progress-text").innerHTML = "";
}
PlayerObject.prototype.processWorkEarnings = function(numCycles=1) {
const hackExpGain = this.workHackExpGainRate * numCycles;
const strExpGain = this.workStrExpGainRate * numCycles;
const defExpGain = this.workDefExpGainRate * numCycles;
const dexExpGain = this.workDexExpGainRate * numCycles;
const agiExpGain = this.workAgiExpGainRate * numCycles;
const chaExpGain = this.workChaExpGainRate * numCycles;
const moneyGain = (this.workMoneyGainRate - this.workMoneyLossRate) * numCycles;
this.gainHackingExp(hackExpGain);
this.gainStrengthExp(strExpGain);
this.gainDefenseExp(defExpGain);
this.gainDexterityExp(dexExpGain);
this.gainAgilityExp(agiExpGain);
this.gainCharismaExp(chaExpGain);
this.gainMoney(moneyGain);
this.workHackExpGained += hackExpGain;
this.workStrExpGained += strExpGain;
this.workDefExpGained += defExpGain;
this.workDexExpGained += dexExpGain;
this.workAgiExpGained += agiExpGain;
this.workChaExpGained += chaExpGain;
this.workRepGained += this.workRepGainRate * numCycles;
this.workMoneyGained += this.workMoneyGainRate * numCycles;
this.workMoneyGained -= this.workMoneyLossRate * numCycles;
}
/* Working for Company */
PlayerObject.prototype.startWork = function() {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCompany;
this.workHackExpGainRate = this.getWorkHackExpGain();
this.workStrExpGainRate = this.getWorkStrExpGain();
this.workDefExpGainRate = this.getWorkDefExpGain();
this.workDexExpGainRate = this.getWorkDexExpGain();
this.workAgiExpGainRate = this.getWorkAgiExpGain();
this.workChaExpGainRate = this.getWorkChaExpGain();
this.workRepGainRate = this.getWorkRepGain();
this.workMoneyGainRate = this.getWorkMoneyGain();
this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Cancel Work";
newCancelButton.addEventListener("click", function() {
Player.finishWork(true);
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.work = function(numCycles) {
//Cap the number of cycles being processed to whatever would put you at
//the work time limit (8 hours)
var overMax = false;
if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles;
this.workRepGainRate = this.getWorkRepGain();
this.processWorkEarnings(numCycles);
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours) {
return this.finishWork(false);
}
var comp = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName], companyRep = "0";
if (comp == null || !(comp instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_3__["Company"])) {
console.error(`Could not find Company: ${this.companyName}`);
} else {
companyRep = comp.playerReputation;
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working as a " + this.companyPosition +
" at " + this.companyName + " (Current Company Reputation: " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(companyRep, '0,0') + ")<br><br>" +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec) <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this company <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp <br><br> " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp <br><br>" +
"You will automatically finish after working for 8 hours. You can cancel earlier if you wish, " +
"but you will only gain half of the reputation you've earned so far."
}
PlayerObject.prototype.finishWork = function(cancelled, sing=false) {
//Since the work was cancelled early, player only gains half of what they've earned so far
if (cancelled) {
this.workRepGained /= 2;
}
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
company.playerReputation += (this.workRepGained);
this.updateSkillLevels();
var txt = "You earned a total of: <br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the company <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp<br>";
if (cancelled) {
txt = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " <br><br> " +
"Since you cancelled your work early, you only gained half of the reputation you earned. <br><br>" + txt;
} else {
txt = "You worked a full shift of 8 hours! <br><br> " + txt;
}
if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
if (sing) {
var res = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " +
"earned $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + ", " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
PlayerObject.prototype.startWorkPartTime = function() {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCompanyPartTime;
this.workHackExpGainRate = this.getWorkHackExpGain();
this.workStrExpGainRate = this.getWorkStrExpGain();
this.workDefExpGainRate = this.getWorkDefExpGain();
this.workDexExpGainRate = this.getWorkDexExpGain();
this.workAgiExpGainRate = this.getWorkAgiExpGain();
this.workChaExpGainRate = this.getWorkChaExpGain();
this.workRepGainRate = this.getWorkRepGain();
this.workMoneyGainRate = this.getWorkMoneyGain();
this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours;
var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Stop Working";
newCancelButton.addEventListener("click", function() {
Player.finishWorkPartTime();
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.workPartTime = function(numCycles) {
//Cap the number of cycles being processed to whatever would put you at the
//work time limit (8 hours)
var overMax = false;
if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles;
this.workRepGainRate = this.getWorkRepGain();
this.processWorkEarnings(numCycles);
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer8Hours) {
return this.finishWorkPartTime();
}
var comp = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName], companyRep = "0";
if (comp == null || !(comp instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_3__["Company"])) {
console.log("ERROR: Could not find Company: " + this.companyName);
} else {
companyRep = comp.playerReputation;
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working as a " + this.companyPosition +
" at " + Player.companyName + " (Current Company Reputation: " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(companyRep, '0,0') + ")<br><br>" +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec) <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this company <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp <br><br> " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp <br><br>" +
"You will automatically finish after working for 8 hours. You can cancel earlier if you wish, <br>" +
"and there will be no penalty because this is a part-time job.";
}
PlayerObject.prototype.finishWorkPartTime = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
company.playerReputation += (this.workRepGained);
this.updateSkillLevels();
var txt = "You earned a total of: <br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the company <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp<br>";
txt = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br> " + txt;
if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
if (sing) {
var res = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " +
"earned a total of " +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + ", " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
/* Working for Faction */
PlayerObject.prototype.startFactionWork = function(faction) {
//Update reputation gain rate to account for faction favor
var favorMult = 1 + (faction.favor / 100);
if (isNaN(favorMult)) {favorMult = 1;}
this.workRepGainRate *= favorMult;
this.workRepGainRate *= _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain;
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeFaction;
this.currentWorkFactionName = faction.name;
this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer20Hours;
var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Stop Faction Work";
cancelButton.addEventListener("click", function() {
Player.finishFactionWork(true);
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.startFactionHackWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = .15 * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult;
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkHacking;
this.currentWorkFactionDescription = "carrying out hacking contracts";
this.startFactionWork(faction);
}
PlayerObject.prototype.startFactionFieldWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = .1 * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = .1 * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = .1 * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = .1 * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = .1 * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = .1 * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.getFactionFieldWorkRepGain();
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkField;
this.currentWorkFactionDescription = "carrying out field missions"
this.startFactionWork(faction);
}
PlayerObject.prototype.startFactionSecurityWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = 0.15 * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = 0.15 * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.getFactionSecurityWorkRepGain();
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkSecurity;
this.currentWorkFactionDescription = "performing security detail"
this.startFactionWork(faction);
}
PlayerObject.prototype.workForFaction = function(numCycles) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][this.currentWorkFactionName];
//Constantly update the rep gain rate
switch (this.factionWorkType) {
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkHacking:
this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkField:
this.workRepGainRate = this.getFactionFieldWorkRepGain();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].FactionWorkSecurity:
this.workRepGainRate = this.getFactionSecurityWorkRepGain();
break;
default:
break;
}
//Update reputation gain rate to account for faction favor
var favorMult = 1 + (faction.favor / 100);
if (isNaN(favorMult)) {favorMult = 1;}
this.workRepGainRate *= favorMult;
this.workRepGainRate *= _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain;
//Cap the number of cycles being processed to whatever would put you at limit (20 hours)
var overMax = false;
if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer20Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer20Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles;
this.processWorkEarnings(numCycles);
//If timeWorked == 20 hours, then finish. You can only work for the faction for 20 hours
if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MillisecondsPer20Hours) {
return this.finishFactionWork(false);
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently " + this.currentWorkFactionDescription + " for your faction " + faction.name +
" (Current Faction Reputation: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(faction.playerReputation, '0,0') + "). <br>" +
"You have been doing this for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec) <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this faction <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp <br><br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp <br><br> " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp <br><br>" +
"You will automatically finish after working for 20 hours. You can cancel earlier if you wish.<br>" +
"There is no penalty for cancelling earlier.";
}
PlayerObject.prototype.finishFactionWork = function(cancelled, sing=false) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][this.currentWorkFactionName];
faction.playerReputation += (this.workRepGained);
this.updateSkillLevels();
var txt = "You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " <br><br> " +
"You earned a total of: <br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the faction <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp<br>";
if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_16__[/* displayFactionContent */ "a"])(faction.name);
if (sing) {
var res="You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ". " +
"You earned " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " rep, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, and " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
//Money gained per game cycle
PlayerObject.prototype.getWorkMoneyGain = function() {
// If player has SF-11, calculate salary multiplier from favor
let bn11Mult = 1;
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_19__[/* hasBn11SF */ "d"]) { bn11Mult = 1 + (company.favor / 100); }
// Get base salary
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (companyPosition == null) {
console.error(`Could not find CompanyPosition object for ${this.companyPosition}. Work salary will be 0`);
return 0;
}
return companyPosition.baseSalary * company.salaryMultiplier * this.work_money_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkMoney * bn11Mult;
}
//Hack exp gained per game cycle
PlayerObject.prototype.getWorkHackExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work hack exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.hackingExpGain * company.expMultiplier * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Str exp gained per game cycle
PlayerObject.prototype.getWorkStrExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work str exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.strengthExpGain * company.expMultiplier * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Def exp gained per game cycle
PlayerObject.prototype.getWorkDefExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work def exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.defenseExpGain * company.expMultiplier * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Dex exp gained per game cycle
PlayerObject.prototype.getWorkDexExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work dex exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.dexterityExpGain * company.expMultiplier * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Agi exp gained per game cycle
PlayerObject.prototype.getWorkAgiExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work agi exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.agilityExpGain * company.expMultiplier * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Charisma exp gained per game cycle
PlayerObject.prototype.getWorkChaExpGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work cha exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.charismaExpGain * company.expMultiplier * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Reputation gained per game cycle
PlayerObject.prototype.getWorkRepGain = function() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`,
`or CompanyPosition object for ${this.companyPosition}.`,
`Work rep gain will be 0`].join(" "));
return 0;
}
var jobPerformance = companyPosition.calculateJobPerformance(this.hacking_skill, this.strength,
this.defense, this.dexterity,
this.agility, this.charisma);
//Intelligence provides a flat bonus to job performance
jobPerformance += (this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel);
//Update reputation gain rate to account for company favor
var favorMult = 1 + (company.favor / 100);
if (isNaN(favorMult)) { favorMult = 1; }
return jobPerformance * this.company_rep_mult * favorMult;
}
PlayerObject.prototype.getFactionSecurityWorkRepGain = function() {
var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.strength / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.defense / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.agility / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel) / 4.5;
return t * this.faction_rep_mult;
}
PlayerObject.prototype.getFactionFieldWorkRepGain = function() {
var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.strength / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.defense / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.agility / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.charisma / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel +
this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MaxSkillLevel) / 5.5;
return t * this.faction_rep_mult;
}
/* Creating a Program */
PlayerObject.prototype.startCreateProgramWork = function(programName, time, reqLevel) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCreateProgram;
//Time needed to complete work affected by hacking skill (linearly based on
//ratio of (your skill - required level) to MAX skill)
//var timeMultiplier = (CONSTANTS.MaxSkillLevel - (this.hacking_skill - reqLevel)) / CONSTANTS.MaxSkillLevel;
//if (timeMultiplier > 1) {timeMultiplier = 1;}
//if (timeMultiplier < 0.01) {timeMultiplier = 0.01;}
this.createProgramReqLvl = reqLevel;
this.timeNeededToCompleteWork = time;
//Check for incomplete program
for (var i = 0; i < this.getHomeComputer().programs.length; ++i) {
var programFile = this.getHomeComputer().programs[i];
if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) {
var res = programFile.split("-");
if (res.length != 3) {break;}
var percComplete = Number(res[1].slice(0, -1));
if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) {break;}
this.timeWorkedCreateProgram = percComplete / 100 * this.timeNeededToCompleteWork;
this.getHomeComputer().programs.splice(i, 1);
}
}
this.createProgramName = programName;
var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Cancel work on creating program";
cancelButton.addEventListener("click", function() {
Player.finishCreateProgramWork(true);
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.createProgramWork = function(numCycles) {
//Higher hacking skill will allow you to create programs faster
var reqLvl = this.createProgramReqLvl;
var skillMult = (this.hacking_skill / reqLvl); //This should always be greater than 1;
skillMult = 1 + ((skillMult - 1) / 5); //The divider constant can be adjusted as necessary
//Skill multiplier directly applied to "time worked"
this.timeWorked += (_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles);
this.timeWorkedCreateProgram += (_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles * skillMult);
var programName = this.createProgramName;
if (this.timeWorkedCreateProgram >= this.timeNeededToCompleteWork) {
this.finishCreateProgramWork(false);
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working on coding " + programName + ".<br><br> " +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br>" +
"The program is " + (this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 100).toFixed(2) + "% complete. <br>" +
"If you cancel, your work will be saved and you can come back to complete the program later.";
}
PlayerObject.prototype.finishCreateProgramWork = function(cancelled, sing=false) {
var programName = this.createProgramName;
if (cancelled === false) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("You've finished creating " + programName + "!<br>" +
"The new program can be found on your home computer.");
this.getHomeComputer().programs.push(programName);
} else {
var perc = (Math.floor(this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 10000)/100).toString();
var incompleteName = programName + "-" + perc + "%-INC";
this.getHomeComputer().programs.push(incompleteName);
}
if (!cancelled) {
this.gainIntelligenceExp(this.createProgramReqLvl / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceProgramBaseExpGain);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadTerminalContent();
this.resetWorkStatus();
}
/* Studying/Taking Classes */
PlayerObject.prototype.startClass = function(costMult, expMult, className) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeStudyClass;
this.className = className;
var gameCPS = 1000 / _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed;
//Base exp gains per second
var baseStudyComputerScienceExp = 0.5;
var baseDataStructuresExp = 1;
var baseNetworksExp = 2;
var baseAlgorithmsExp = 4;
var baseManagementExp = 2;
var baseLeadershipExp = 4;
var baseGymExp = 1;
//Find cost and exp gain per game cycle
var cost = 0;
var hackExp = 0, strExp = 0, defExp = 0, dexExp = 0, agiExp = 0, chaExp = 0;
switch (className) {
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassStudyComputerScience:
hackExp = baseStudyComputerScienceExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassDataStructures:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassDataStructuresBaseCost * costMult / gameCPS;
hackExp = baseDataStructuresExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassNetworks:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassNetworksBaseCost * costMult / gameCPS;
hackExp = baseNetworksExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassAlgorithms:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassAlgorithmsBaseCost * costMult / gameCPS;
hackExp = baseAlgorithmsExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassManagement:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassManagementBaseCost * costMult / gameCPS;
chaExp = baseManagementExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassLeadership:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassLeadershipBaseCost * costMult / gameCPS;
chaExp = baseLeadershipExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymStrength:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
strExp = baseGymExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDefense:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
defExp = baseGymExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDexterity:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
dexExp = baseGymExp * expMult / gameCPS;
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymAgility:
cost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
agiExp = baseGymExp * expMult / gameCPS;
break;
default:
throw new Error("ERR: Invalid/unrecognized class name");
return;
}
this.workMoneyLossRate = cost;
this.workHackExpGainRate = hackExp * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;
this.workStrExpGainRate = strExp * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workDefExpGainRate = defExp * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workDexExpGainRate = dexExp * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workAgiExpGainRate = agiExp * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workChaExpGainRate = chaExp * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button");
if (className == _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymStrength ||
className == _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDefense ||
className == _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDexterity ||
className == _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymAgility) {
cancelButton.innerHTML = "Stop training at gym";
} else {
cancelButton.innerHTML = "Stop taking course";
}
cancelButton.addEventListener("click", function() {
Player.finishClass();
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.takeClass = function(numCycles) {
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles;
var className = this.className;
this.processWorkEarnings(numCycles);
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You have been " + className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "<br><br>" +
"This has cost you: <br>" +
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyLossRate * CYCLES_PER_SEC, '0,0.00') + " / sec) <br><br>" +
"You have gained: <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp <br>" +
"You may cancel at any time";
}
//The 'sing' argument defines whether or not this function was called
//through a Singularity Netscript function
PlayerObject.prototype.finishClass = function(sing=false) {
this.gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceClassBaseExpGain * Math.round(this.timeWorked / 1000));
if (this.workMoneyGained > 0) {
throw new Error("ERR: Somehow gained money while taking class");
}
this.updateSkillLevels();
var txt = "After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ", <br>" +
"you spent a total of $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained * -1, '0,0.00') + ". <br><br>" +
"You earned a total of: <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp<br>";
if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
if (sing) {
var res="After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ", " +
"you spent a total of $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained * -1, '0,0.00') + ". " +
"You earned a total of: " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
//The EXP and $ gains are hardcoded. Time is in ms
PlayerObject.prototype.startCrime = function(hackExp, strExp, defExp, dexExp, agiExp, chaExp, money, time, singParams=null) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCrime;
if (singParams && singParams.workerscript) {
this.committingCrimeThruSingFn = true;
this.singFnCrimeWorkerScript = singParams.workerscript;
}
this.workHackExpGained = hackExp * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workStrExpGained = strExp * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workDefExpGained = defExp * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workDexExpGained = dexExp * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workAgiExpGained = agiExp * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workChaExpGained = chaExp * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workMoneyGained = money * this.crime_money_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeMoney;
this.timeNeededToCompleteWork = time;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_27__["clearEventListeners"])("work-in-progress-cancel-button")
newCancelButton.innerHTML = "Cancel crime"
newCancelButton.addEventListener("click", function() {
Player.finishCrime(true);
return false;
});
//Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.commitCrime = function (numCycles) {
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_13__["Engine"]._idleSpeed * numCycles;
if (this.timeWorked >= this.timeNeededToCompleteWork) {this.finishCrime(false); return;}
var percent = Math.round(this.timeWorked / this.timeNeededToCompleteWork * 100);
var numBars = Math.round(percent / 5);
if (numBars < 0) {numBars = 0;}
if (numBars > 20) {numBars = 20;}
var progressBar = "[" + Array(numBars+1).join("|") + Array(20 - numBars + 1).join(" ") + "]";
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are attempting to " + this.crimeType + ".<br>" +
"Time remaining: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_30__["convertTimeMsToTimeElapsedString"])(this.timeNeededToCompleteWork - this.timeWorked) + "<br>" +
progressBar.replace( / /g, "&nbsp;" );
}
PlayerObject.prototype.finishCrime = function(cancelled) {
//Determine crime success/failure
if (!cancelled) {
var statusText = ""; //TODO, unique message for each crime when you succeed
if (Object(_Crimes__WEBPACK_IMPORTED_MODULE_12__[/* determineCrimeSuccess */ "b"])(this.crimeType, this.workMoneyGained)) {
//Handle Karma and crime statistics
let crime = null;
for(const i in _Crimes__WEBPACK_IMPORTED_MODULE_12__[/* Crimes */ "a"]) {
if(_Crimes__WEBPACK_IMPORTED_MODULE_12__[/* Crimes */ "a"][i].type == this.crimeType) {
crime = _Crimes__WEBPACK_IMPORTED_MODULE_12__[/* Crimes */ "a"][i];
break;
}
}
if(crime == null) {
console.log(this.crimeType);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer");
}
this.karma -= crime.karma;
this.numPeopleKilled += crime.kills;
if(crime.intelligence_exp > 0) {
this.gainIntelligenceExp(crime.intelligence_exp);
}
//On a crime success, gain 2x exp
this.workHackExpGained *= 2;
this.workStrExpGained *= 2;
this.workDefExpGained *= 2;
this.workDexExpGained *= 2;
this.workAgiExpGained *= 2;
this.workChaExpGained *= 2;
if (this.committingCrimeThruSingFn) {
if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) {
this.singFnCrimeWorkerScript.scriptRef.log("Crime successful! Gained " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, "$0.000a") + ", " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hack exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp.");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Crime successful! <br><br>" +
"You gained:<br>"+
"$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking experience <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma experience");
}
} else {
//Exp halved on failure
this.workHackExpGained /= 2;
this.workStrExpGained /= 2;
this.workDefExpGained /= 2;
this.workDexExpGained /= 2;
this.workAgiExpGained /= 2;
this.workChaExpGained /= 2;
if (this.committingCrimeThruSingFn) {
if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) {
this.singFnCrimeWorkerScript.scriptRef.log("Crime failed! Gained " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hack exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp.");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Crime failed! <br><br>" +
"You gained:<br>"+
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking experience <br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility experience<br>" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma experience");
}
}
this.gainHackingExp(this.workHackExpGained);
this.gainStrengthExp(this.workStrExpGained);
this.gainDefenseExp(this.workDefExpGained);
this.gainDexterityExp(this.workDexExpGained);
this.gainAgilityExp(this.workAgiExpGained);
this.gainCharismaExp(this.workChaExpGained);
}
this.committingCrimeThruSingFn = false;
this.singFnCrimeWorkerScript = null;
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
this.resetWorkStatus();
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
}
//Cancels the player's current "work" assignment and gives the proper rewards
//Used only for Singularity functions, so no popups are created
PlayerObject.prototype.singularityStopWork = function() {
if (!this.isWorking) {return "";}
var res; //Earnings text for work
switch (this.workType) {
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeStudyClass:
res = this.finishClass(true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCompany:
res = this.finishWork(true, true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCompanyPartTime:
res = this.finishWorkPartTime(true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeFaction:
res = this.finishFactionWork(true, true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCreateProgram:
res = this.finishCreateProgramWork(true, true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].WorkTypeCrime:
res = this.finishCrime(true);
break;
default:
console.log("ERROR: Unrecognized work type");
return "";
}
return res;
}
//Returns true if hospitalized, false otherwise
PlayerObject.prototype.takeDamage = function(amt) {
this.hp -= amt;
if (this.hp <= 0) {
this.hospitalize();
return true;
} else {
return false;
}
}
PlayerObject.prototype.hospitalize = function() {
if (_Settings__WEBPACK_IMPORTED_MODULE_21__["Settings"].SuppressHospitalizationPopup === false) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])(
"You were in critical condition! You were taken to the hospital where " +
"luckily they were able to save your life. You were charged " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].HospitalCostPerHp, '$0.000a')
);
}
this.loseMoney(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].HospitalCostPerHp);
this.hp = this.max_hp;
}
/********* Company job application **********/
//Determines the job that the Player should get (if any) at the current company
//The 'sing' argument designates whether or not this is being called from
//the applyToCompany() Netscript Singularity function
PlayerObject.prototype.applyForJob = function(entryPosType, sing=false) {
// Get current company and job
let currCompany = null;
if (this.companyName !== "") {
currCompany = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
}
const currPositionName = this.companyPosition;
// Get company that's being applied to
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (!(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_3__["Company"])) {
if (sing) {
return "ERROR: Invalid company name: " + this.location + ". applyToCompany() failed";
} else {
console.error(`Could not find company that matches the location: ${this.location}. Player.applyToCompany() failed`);
return;
}
}
let pos = entryPosType;
if (!this.isQualified(company, pos)) {
var reqText = Object(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_6__["getJobRequirementText"])(company, pos);
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position<br>" + reqText);
return;
}
while (true) {
let newPos = Object(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5__["getNextCompanyPosition"])(pos);
if (newPos == null) {break;}
//Check if this company has this position
if (company.hasPosition(newPos)) {
if (!this.isQualified(company, newPos)) {
//If player not qualified for next job, break loop so player will be given current job
break;
}
pos = newPos;
} else {
break;
}
}
//Check if the determined job is the same as the player's current job
if (currCompany != null) {
if (currCompany.name == company.name && pos.name == currPositionName) {
var nextPos = Object(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5__["getNextCompanyPosition"])(pos);
if (nextPos == null) {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available");
} else if (company.hasPosition(nextPos)) {
if (sing) {return false;}
var reqText = Object(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_6__["getJobRequirementText"])(company, nextPos);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unfortunately, you do not qualify for a promotion<br>" + reqText);
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available");
}
return; //Same job, do nothing
}
}
//Lose reputation from a Company if you are leaving it for another job
let leaveCompany = false;
let oldCompanyName = "";
if (currCompany != null) {
if (currCompany.name != company.name) {
leaveCompany = true;
oldCompanyName = currCompany.name;
currCompany.playerReputation -= 1000;
if (currCompany.playerReputation < 0) { currCompany.playerReputation = 0; }
}
}
this.companyName = company.name;
this.companyPosition = pos.name;
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (leaveCompany) {
if (sing) { return true; }
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])([`Congratulations! You were offered a new job at ${this.companyName} as a ${pos.name}!`,
`You lost 1000 reputation at your old company ${oldCompanyName} because you left.`].join("<br>"));
} else {
if (sing) { return true; }
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.name + "!");
}
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
}
//Returns your next position at a company given the field (software, business, etc.)
PlayerObject.prototype.getNextCompanyPosition = function(company, entryPosType) {
var currCompany = null;
if (this.companyName !== "") {
currCompany = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
}
//Not employed at this company, so return the entry position
if (currCompany == null || (currCompany.name != company.name)) {
return entryPosType;
}
//If the entry pos type and the player's current position have the same type,
//return the player's "nextCompanyPosition". Otherwise return the entryposType
//Employed at this company, so just return the next position if it exists.
const currentPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if ((currentPosition.isSoftwareJob() && entryPosType.isSoftwareJob()) ||
(currentPosition.isITJob() && entryPosType.isITJob()) ||
(currentPosition.isBusinessJob() && entryPosType.isBusinessJob()) ||
(currentPosition.isSecurityEngineerJob() && entryPosType.isSecurityEngineerJob()) ||
(currentPosition.isNetworkEngineerJob() && entryPosType.isNetworkEngineerJob()) ||
(currentPosition.isSecurityJob() && entryPosType.isSecurityJob()) ||
(currentPosition.isAgentJob() && entryPosType.isAgentJob()) ||
(currentPosition.isSoftwareConsultantJob() && entryPosType.isSoftwareConsultantJob()) ||
(currentPosition.isBusinessConsultantJob() && entryPosType.isBusinessConsultantJob()) ||
(currentPosition.isPartTimeJob() && entryPosType.isPartTimeJob())) {
return Object(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_5__["getNextCompanyPosition"])(currentPosition);
}
return entryPosType;
}
PlayerObject.prototype.applyForSoftwareJob = function(sing=false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["SoftwareCompanyPositions"][0]], sing);
}
PlayerObject.prototype.applyForSoftwareConsultantJob = function(sing=false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["SoftwareConsultantCompanyPositions"][0]], sing);
}
PlayerObject.prototype.applyForItJob = function(sing=false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["ITCompanyPositions"][0]], sing);
}
PlayerObject.prototype.applyForSecurityEngineerJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["SecurityEngineerCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["SecurityEngineerCompanyPositions"][0]], sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForNetworkEngineerJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["NetworkEngineerCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["NetworkEngineerCompanyPositions"][0]], sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForBusinessJob = function(sing=false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["BusinessCompanyPositions"][0]], sing);
}
PlayerObject.prototype.applyForBusinessConsultantJob = function(sing=false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["BusinessConsultantCompanyPositions"][0]], sing);
}
PlayerObject.prototype.applyForSecurityJob = function(sing=false) {
// TODO Police Jobs
// Indexing starts at 2 because 0 is for police officer
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["SecurityCompanyPositions"][2]], sing);
}
PlayerObject.prototype.applyForAgentJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["AgentCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["AgentCompanyPositions"][0]], sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForEmployeeJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["MiscCompanyPositions"][1]])) {
this.companyName = company.name;
this.companyPosition = _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["MiscCompanyPositions"][1];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {return true;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Congratulations, you are now employed at " + this.companyName);
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeEmployeeJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["PartTimeCompanyPositions"][1]])) {
this.companyName = company.name;
this.companyPosition = _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["PartTimeCompanyPositions"][1];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {return true;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Congratulations, you are now employed part-time at " + this.companyName);
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForWaiterJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["MiscCompanyPositions"][0]])) {
this.companyName = company.name;
this.companyPosition = _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["MiscCompanyPositions"][0];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {return true;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Congratulations, you are now employed as a waiter at " + this.companyName);
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeWaiterJob = function(sing=false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["PartTimeCompanyPositions"][0]])) {
this.companyName = company.name;
this.companyPosition = _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_8__["PartTimeCompanyPositions"][0];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {return true;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Congratulations, you are now employed as a part-time waiter at " + this.companyName);
_engine__WEBPACK_IMPORTED_MODULE_13__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
//Checks if the Player is qualified for a certain position
PlayerObject.prototype.isQualified = function(company, position) {
var offset = company.jobStatReqOffset;
var reqHacking = position.requiredHacking > 0 ? position.requiredHacking+offset : 0;
var reqStrength = position.requiredStrength > 0 ? position.requiredStrength+offset : 0;
var reqDefense = position.requiredDefense > 0 ? position.requiredDefense+offset : 0;
var reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0;
var reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0;
var reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma+offset : 0;
if (this.hacking_skill >= reqHacking &&
this.strength >= reqStrength &&
this.defense >= reqDefense &&
this.dexterity >= reqDexterity &&
this.agility >= reqAgility &&
this.charisma >= reqCharisma &&
company.playerReputation >= position.requiredReputation) {
return true;
}
return false;
}
/********** Reapplying Augmentations and Source File ***********/
PlayerObject.prototype.reapplyAllAugmentations = function(resetMultipliers=true) {
console.log("Re-applying augmentations");
if (resetMultipliers) {
this.resetMultipliers();
}
for (let i = 0; i < this.augmentations.length; ++i) {
//Compatibility with new version
if (this.augmentations[i].name === "HacknetNode NIC Architecture Neural-Upload") {
this.augmentations[i].name = "Hacknet Node NIC Architecture Neural-Upload";
}
const augName = this.augmentations[i].name;
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName];
if (aug == null) {
console.log(`WARNING: Invalid augmentation name in Player.reapplyAllAugmentations(). Aug ${augName} will be skipped`);
continue;
}
aug.owned = true;
if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
for (let j = 0; j < aug.level; ++j) {
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* applyAugmentation */ "e"])(this.augmentations[i], true);
}
continue;
}
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* applyAugmentation */ "e"])(this.augmentations[i], true);
}
}
PlayerObject.prototype.reapplyAllSourceFiles = function() {
console.log("Re-applying source files");
//Will always be called after reapplyAllAugmentations() so multipliers do not have to be reset
//this.resetMultipliers();
for (let i = 0; i < this.sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + this.sourceFiles[i].n;
var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_23__[/* SourceFiles */ "b"][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + this.sourceFiles[i].n);
continue;
}
Object(_SourceFile__WEBPACK_IMPORTED_MODULE_23__[/* applySourceFile */ "c"])(this.sourceFiles[i]);
}
}
/*************** Check for Faction Invitations *************/
//This function sets the requirements to join a Faction. It checks whether the Player meets
//those requirements and will return an array of all factions that the Player should
//receive an invitation to
PlayerObject.prototype.checkForFactionInvitations = function() {
let invitedFactions = []; //Array which will hold all Factions the player should be invited to
var numAugmentations = this.augmentations.length;
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][this.companyName];
var companyRep = 0;
if (company != null) {
companyRep = company.playerReputation;
}
//Illuminati
var illuminatiFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Illuminati"];
if (!illuminatiFac.isBanned && !illuminatiFac.isMember && !illuminatiFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(150000000000) &&
this.hacking_skill >= 1500 &&
this.strength >= 1200 && this.defense >= 1200 &&
this.dexterity >= 1200 && this.agility >= 1200) {
invitedFactions.push(illuminatiFac);
}
//Daedalus
var daedalusFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Daedalus"];
if (!daedalusFac.isBanned && !daedalusFac.isMember && !daedalusFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(100000000000) &&
(this.hacking_skill >= 2500 ||
(this.strength >= 1500 && this.defense >= 1500 &&
this.dexterity >= 1500 && this.agility >= 1500))) {
invitedFactions.push(daedalusFac);
}
//The Covenant
var covenantFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["The Covenant"];
if (!covenantFac.isBanned && !covenantFac.isMember && !covenantFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(75000000000) &&
this.hacking_skill >= 850 &&
this.strength >= 850 &&
this.defense >= 850 &&
this.dexterity >= 850 &&
this.agility >= 850) {
invitedFactions.push(covenantFac);
}
//ECorp
var ecorpFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["ECorp"];
if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumECorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(ecorpFac);
}
//MegaCorp
var megacorpFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["MegaCorp"];
if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12MegaCorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(megacorpFac);
}
//Bachman & Associates
var bachmanandassociatesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Bachman & Associates"];
if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember &&
!bachmanandassociatesFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumBachmanAndAssociates && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(bachmanandassociatesFac);
}
//Blade Industries
var bladeindustriesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Blade Industries"];
if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12BladeIndustries && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(bladeindustriesFac);
}
//NWO
var nwoFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["NWO"];
if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenNWO && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(nwoFac);
}
//Clarke Incorporated
var clarkeincorporatedFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Clarke Incorporated"];
if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumClarkeIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(clarkeincorporatedFac);
}
//OmniTek Incorporated
var omnitekincorporatedFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["OmniTek Incorporated"];
if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenOmniTekIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(omnitekincorporatedFac);
}
//Four Sigma
var foursigmaFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Four Sigma"];
if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12FourSigma && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(foursigmaFac);
}
//KuaiGong International
var kuaigonginternationalFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["KuaiGong International"];
if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember &&
!kuaigonginternationalFac.alreadyInvited &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].ChongqingKuaiGongInternational && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(kuaigonginternationalFac);
}
//Fulcrum Secret Technologies - If u've unlocked fulcrum secret technolgoies server and have a high rep with the company
var fulcrumsecrettechonologiesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Fulcrum Secret Technologies"];
var fulcrumSecretServer = _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerNames */ "b"].FulcrumSecretTechnologies]];
if (fulcrumSecretServer == null) {
console.log("ERROR: Could not find Fulcrum Secret Technologies Server");
} else {
if (!fulcrumsecrettechonologiesFac.isBanned && !fulcrumsecrettechonologiesFac.isMember &&
!fulcrumsecrettechonologiesFac.alreadyInvited &&
fulcrumSecretServer.manuallyHacked &&
this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumFulcrumTechnologies && companyRep >= 250000) {
invitedFactions.push(fulcrumsecrettechonologiesFac);
}
}
//BitRunners
var bitrunnersFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["BitRunners"];
var homeComp = this.getHomeComputer();
var bitrunnersServer = _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerNames */ "b"].BitRunnersServer]];
if (bitrunnersServer == null) {
console.log("ERROR: Could not find BitRunners Server");
} else if (!bitrunnersFac.isBanned && !bitrunnersFac.isMember && bitrunnersServer.manuallyHacked &&
!bitrunnersFac.alreadyInvited && this.hacking_skill >= 500 && homeComp.maxRam >= 128) {
invitedFactions.push(bitrunnersFac);
}
//The Black Hand
var theblackhandFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["The Black Hand"];
var blackhandServer = _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerNames */ "b"].TheBlackHandServer]];
if (blackhandServer == null) {
console.log("ERROR: Could not find The Black Hand Server");
} else if (!theblackhandFac.isBanned && !theblackhandFac.isMember && blackhandServer.manuallyHacked &&
!theblackhandFac.alreadyInvited && this.hacking_skill >= 350 && homeComp.maxRam >= 64) {
invitedFactions.push(theblackhandFac);
}
//NiteSec
var nitesecFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["NiteSec"];
var nitesecServer = _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerNames */ "b"].NiteSecServer]];
if (nitesecServer == null) {
console.log("ERROR: Could not find NiteSec Server");
} else if (!nitesecFac.isBanned && !nitesecFac.isMember && nitesecServer.manuallyHacked &&
!nitesecFac.alreadyInvited && this.hacking_skill >= 200 && homeComp.maxRam >= 32) {
invitedFactions.push(nitesecFac);
}
//Chongqing
var chongqingFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Chongqing"];
if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited &&
this.money.gte(20000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing) {
invitedFactions.push(chongqingFac);
}
//Sector-12
var sector12Fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Sector-12"];
if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited &&
this.money.gte(15000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12) {
invitedFactions.push(sector12Fac);
}
//New Tokyo
var newtokyoFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["New Tokyo"];
if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited &&
this.money.gte(20000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyo) {
invitedFactions.push(newtokyoFac);
}
//Aevum
var aevumFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Aevum"];
if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited &&
this.money.gte(40000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum) {
invitedFactions.push(aevumFac);
}
//Ishima
var ishimaFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Ishima"];
if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited &&
this.money.gte(30000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Ishima) {
invitedFactions.push(ishimaFac);
}
//Volhaven
var volhavenFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Volhaven"];
if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited &&
this.money.gte(50000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Volhaven) {
invitedFactions.push(volhavenFac);
}
//Speakers for the Dead
var speakersforthedeadFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Speakers for the Dead"];
if (!speakersforthedeadFac.isBanned && !speakersforthedeadFac.isMember && !speakersforthedeadFac.alreadyInvited &&
this.hacking_skill >= 100 && this.strength >= 300 && this.defense >= 300 &&
this.dexterity >= 300 && this.agility >= 300 && this.numPeopleKilled >= 30 &&
this.karma <= -45 && this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12CIA &&
this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12NSA) {
invitedFactions.push(speakersforthedeadFac);
}
//The Dark Army
var thedarkarmyFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["The Dark Army"];
if (!thedarkarmyFac.isBanned && !thedarkarmyFac.isMember && !thedarkarmyFac.alreadyInvited &&
this.hacking_skill >= 300 && this.strength >= 300 && this.defense >= 300 &&
this.dexterity >= 300 && this.agility >= 300 && this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing &&
this.numPeopleKilled >= 5 && this.karma <= -45 && this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12CIA &&
this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12NSA) {
invitedFactions.push(thedarkarmyFac);
}
//The Syndicate
var thesyndicateFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["The Syndicate"];
if (!thesyndicateFac.isBanned && !thesyndicateFac.isMember && !thesyndicateFac.alreadyInvited &&
this.hacking_skill >= 200 && this.strength >= 200 && this.defense >= 200 &&
this.dexterity >= 200 && this.agility >= 200 &&
(this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum || this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12) &&
this.money.gte(10000000) && this.karma <= -90 &&
this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12CIA && this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12NSA) {
invitedFactions.push(thesyndicateFac);
}
//Silhouette
var silhouetteFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Silhouette"];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_7__["CompanyPositions"][this.companyPosition];
if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited &&
companyPosition != null &&
(companyPosition.name == "Chief Technology Officer" ||
companyPosition.name == "Chief Financial Officer" ||
companyPosition.name == "Chief Executive Officer") &&
this.money.gte(15000000) && this.karma <= -22) {
invitedFactions.push(silhouetteFac);
}
//Tetrads
var tetradsFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Tetrads"];
if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited &&
(this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing || this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyo ||
this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Ishima) && this.strength >= 75 && this.defense >= 75 &&
this.dexterity >= 75 && this.agility >= 75 && this.karma <= -18) {
invitedFactions.push(tetradsFac);
}
//SlumSnakes
var slumsnakesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Slum Snakes"];
if (!slumsnakesFac.isBanned && !slumsnakesFac.isMember && !slumsnakesFac.alreadyInvited &&
this.strength >= 30 && this.defense >= 30 && this.dexterity >= 30 &&
this.agility >= 30 && this.karma <= -9 && this.money.gte(1000000)) {
invitedFactions.push(slumsnakesFac);
}
//Netburners
var netburnersFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Netburners"];
var totalHacknetRam = 0;
var totalHacknetCores = 0;
var totalHacknetLevels = 0;
for (var i = 0; i < this.hacknetNodes.length; ++i) {
totalHacknetLevels += this.hacknetNodes[i].level;
totalHacknetRam += this.hacknetNodes[i].ram;
totalHacknetCores += this.hacknetNodes[i].cores;
}
if (!netburnersFac.isBanned && !netburnersFac.isMember && !netburnersFac.alreadyInvited &&
this.hacking_skill >= 80 && totalHacknetRam >= 8 &&
totalHacknetCores >= 4 && totalHacknetLevels >= 100) {
invitedFactions.push(netburnersFac);
}
//Tian Di Hui
var tiandihuiFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["Tian Di Hui"];
if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited &&
this.money.gte(1000000) && this.hacking_skill >= 50 &&
(this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing || this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyo ||
this.city == _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Ishima)) {
invitedFactions.push(tiandihuiFac);
}
//CyberSec
var cybersecFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"]["CyberSec"];
var cybersecServer = _Server__WEBPACK_IMPORTED_MODULE_20__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__[/* SpecialServerNames */ "b"].CyberSecServer]];
if (cybersecServer == null) {
console.log("ERROR: Could not find CyberSec Server");
} else if (!cybersecFac.isBanned && !cybersecFac.isMember && cybersecServer.manuallyHacked &&
!cybersecFac.alreadyInvited && this.hacking_skill >= 50) {
invitedFactions.push(cybersecFac);
}
return invitedFactions;
}
/*************** Gang ****************/
//Returns true if Player is in a gang and false otherwise
PlayerObject.prototype.inGang = function() {
if (this.gang == null || this.gang == undefined) {return false;}
return (this.gang instanceof _Gang__WEBPACK_IMPORTED_MODULE_17__[/* Gang */ "b"]);
}
PlayerObject.prototype.startGang = function(factionName, hacking) {
this.gang = new _Gang__WEBPACK_IMPORTED_MODULE_17__[/* Gang */ "b"](factionName, hacking);
}
/************* BitNodes **************/
PlayerObject.prototype.setBitNodeNumber = function(n) {
this.bitNodeN = n;
}
PlayerObject.prototype.queueAugmentation = function(name) {
for(const i in this.queuedAugmentations) {
if(this.queuedAugmentations[i].name == name) {
console.log('tried to queue '+name+' twice, this may be a bug');
return;
}
}
for(const i in this.augmentations) {
if(this.augmentations[i].name == name) {
console.log('tried to queue '+name+' but we already have that aug');
return;
}
}
this.firstAugPurchased = true;
this.queuedAugmentations.push(new _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* PlayerOwnedAugmentation */ "d"](name));
}
/************* Coding Contracts **************/
PlayerObject.prototype.gainCodingContractReward = function(reward, difficulty=1) {
if (reward == null || reward.type == null || reward == null) {
return `No reward for this contract`;
}
/* eslint-disable no-case-declarations */
switch (reward.type) {
case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputation:
if (reward.name == null || !(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][reward.name] instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_14__["Faction"])) {
// If no/invalid faction was designated, just give rewards to all factions
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll;
return this.gainCodingContractReward(reward);
}
var repGain = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CodingContractBaseFactionRepGain * difficulty;
_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][reward.name].playerReputation += repGain;
return `Gained ${repGain} faction reputation for ${reward.name}`;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll:
const totalGain = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CodingContractBaseFactionRepGain * difficulty;
// Ignore Bladeburners and other special factions for this calculation
const specialFactions = ["Bladeburners"];
var factions = this.factions.slice();
factions = factions.filter((f) => {
return !specialFactions.includes(f);
});
// If the player was only part of the special factions, we'll just give money
if (factions.length == 0) {
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].Money;
return this.gainCodingContractReward(reward, difficulty);
}
const gainPerFaction = Math.floor(totalGain / factions.length);
for (const facName of factions) {
if (!(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][facName] instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_14__["Faction"])) { continue; }
_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][facName].playerReputation += gainPerFaction;
}
return `Gained ${gainPerFaction} reputation for each of the following factions: ${factions.toString()}`;
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].CompanyReputation:
if (reward.name == null || !(_Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][reward.name] instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_3__["Company"])) {
//If no/invalid company was designated, just give rewards to all factions
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll;
return this.gainCodingContractReward(reward);
}
var repGain = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CodingContractBaseCompanyRepGain * difficulty;
_Company_Companies__WEBPACK_IMPORTED_MODULE_4__["Companies"][reward.name].playerReputation += repGain;
return `Gained ${repGain} company reputation for ${reward.name}`;
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].Money:
default:
var moneyGain = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].CodingContractBaseMoneyGain * difficulty * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CodingContractMoney;
this.gainMoney(moneyGain);
return `Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_25__[/* numeralWrapper */ "a"].format(moneyGain, '$0.000a')}`;
break;
}
/* eslint-enable no-case-declarations */
}
/* Functions for saving and loading the Player data */
function loadPlayer(saveString) {
Player = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_29__["Reviver"]);
//Parse Decimal.js objects
Player.money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](Player.money);
Player.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](Player.total_money);
Player.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](Player.lifetime_money);
if (Player.corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_10__[/* Corporation */ "a"]) {
Player.corporation.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](Player.corporation.funds);
Player.corporation.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](Player.corporation.revenue);
Player.corporation.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* 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_24__[/* default */ "a"](ind.lastCycleRevenue);
ind.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](ind.lastCycleExpenses);
ind.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](ind.thisCycleRevenue);
ind.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"](ind.thisCycleExpenses);
}
}
}
PlayerObject.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_29__["Generic_toJSON"])("PlayerObject", this);
}
PlayerObject.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_29__["Generic_fromJSON"])(PlayerObject, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_29__["Reviver"].constructors.PlayerObject = PlayerObject;
let Player = new PlayerObject();
/***/ }),
/* 1 */
/*!**************************!*\
!*** ./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.41.2",
//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 costs */
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000,
BaseCostFor1GBOfRamHacknetNode: 30000,
TravelCost: 200000,
BaseCostForHacknetNode: 1000,
BaseCostForHacknetNodeCore: 500000,
/* Hacknet Node constants */
HacknetNodeMoneyGainPerLevel: 1.6,
HacknetNodePurchaseNextMult: 1.85,
HacknetNodeUpgradeLevelMult: 1.04,
HacknetNodeUpgradeRamMult: 1.28,
HacknetNodeUpgradeCoreMult: 1.48,
HacknetNodeMaxLevel: 200,
HacknetNodeMaxRam: 64,
HacknetNodeMaxCores: 16,
/* Faction and Company favor */
BaseFavorToDonate: 150,
DonateMoneyToRepDivisor: 1e6,
FactionReputationToFavorBase: 500,
FactionReputationToFavorMult: 1.02,
CompanyReputationToFavorBase: 500,
CompanyReputationToFavorMult: 1.02,
/* Augmentation */
//NeuroFlux Governor cost multiplier as you level up
NeuroFluxGovernorLevelMult: 1.14,
/* Netscript Constants */
//RAM Costs for different commands
ScriptBaseRamCost: 1.6,
ScriptDomRamCost: 25,
ScriptWhileRamCost: 0,
ScriptForRamCost: 0,
ScriptIfRamCost: 0,
ScriptHackRamCost: 0.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,
ScriptSingularityFn1RamCost: 1,
ScriptSingularityFn2RamCost: 2,
ScriptSingularityFn3RamCost: 3,
ScriptSingularityFnRamMult: 2,
ScriptGangApiBaseRamCost: 4,
ScriptBladeburnerApiBaseRamCost: 4,
NumNetscriptPorts: 20,
//Server constants
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,
//How much a TOR router costs
TorRouterCost: 200000,
//Infiltration constants
InfiltrationBribeBaseAmount: 100e3,
InfiltrationMoneyValue: 5e3,
InfiltrationRepValue: 1.4,
//Stock market constants
WSEAccountCost: 200e6,
TIXAPICost: 5e9,
MarketData4SCost: 1e9,
MarketDataTixApi4SCost: 20e9,
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
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.<br><br>" +
"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.<br><br>" +
"Each Node has three stats: Attack, Defense, and HP. There are five different actions that " +
"a Node can take:<br><br> " +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"Fortify - Raises the Node's Defense. The effectiveness is determined by your hacking level.<br><br>" +
"Overflow - Raises the Node's Attack but lowers its Defense. The effectiveness is determined by your hacking level.<br><br>" +
"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.<br><br>" +
"To capture a Node, you must lower its HP down to 0.<br><br>" +
"There are six different types of Nodes:<br><br>" +
"CPU Core - These are your main Nodes that are used to perform actions. Capable of performing every action<br><br>" +
"Firewall - Nodes with high defense. These Nodes can 'Fortify'<br><br>" +
"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<br><br>" +
"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<br><br>" +
"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<br><br>" +
"Shield - Nodes with high defense. These Nodes can 'Fortify'<br><br>" +
"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.<br><br>" +
"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'.<br><br>" +
"Other Notes:<br><br>" +
"-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.<br><br>" +
"-Whenever a Node is conquered, its stats are significantly reduced<br><br>" +
"-Miscellaneous Nodes slowly raise their defense over time<br><br>" +
"-Nodes slowly regenerate health over time.",
/* Time 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 related Constants */
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 Constants */
CodingContractBaseFactionRepGain: 2500,
CodingContractBaseCompanyRepGain: 4000,
CodingContractBaseMoneyGain: 50e6,
/* Tutorial related things */
TutorialNetworkingText: "Servers are a central part of the game. You start with a single personal server (your home computer) " +
"and you can purchase additional servers as you progress through the game. Connecting to other servers " +
"and hacking them can be a major source of income and experience. Servers can also be used to run " +
"scripts which can automatically hack servers for you. <br><br>" +
"In order to navigate between machines, use the 'scan' or 'scan-analyze' Terminal command to see all servers " +
"that are reachable from your current server. Then, you can use the 'connect [hostname/ip]' " +
"command to connect to one of the available machines. <br><br>" +
"The 'hostname' and 'ifconfig' commands can be used to display the hostname/IP of the " +
"server you are currently connected to.",
TutorialHackingText: "In the year 2077, currency has become digital and decentralized. People and corporations " +
"store their money on servers. By hacking these servers, you can steal their money and gain " +
"experience. <br><br>" +
"<h1>Gaining root access</h1> <br>" +
"The key to hacking a server is to gain root access to that server. This can be done using " +
"the NUKE virus (NUKE.exe). You start the game with a copy of the NUKE virus on your home " +
"computer. The NUKE virus attacks the target server's open ports using buffer overflow " +
"exploits. When successful, you are granted root administrative access to the machine. <br><br>" +
"Typically, in order for the NUKE virus to succeed, the target server needs to have at least " +
"one of its ports opened. Some servers have no security and will not need any ports opened. Some " +
"will have very high security and will need many ports opened. In order to open ports on another " +
"server, you will need to run programs that attack the server to open specific ports. These programs " +
"can be coded once your hacking skill gets high enough, or they can be purchased if you can find " +
"a seller. <br><br>" +
"In order to determine how many ports need to be opened to successfully NUKE a server, connect to " +
"that server and run the 'analyze' command. This will also show you which ports have already been " +
"opened. <br><br>" +
"Once you have enough ports opened and have ran the NUKE virus to gain root access, the server " +
"can then be hacked by simply calling the 'hack' command through terminal, or by using a script.<br><br>" +
"<h1>Hacking mechanics</h1><br>" +
"When you execute the hack command, either manually through the terminal or automatically through " +
"a script, you attempt to hack the server. This action takes time. The more advanced a server's " +
"security is, the more time it will take. Your hacking skill level also affects the hacking time, " +
"with a higher hacking skill leading to shorter hacking times. Also, running the hack command " +
"manually through terminal is faster than hacking from a script. <br><br>" +
"Your attempt to hack a server will not always succeed. The chance you have to successfully hack a " +
"server is also determined by the server's security and your hacking skill level. Even if your " +
"hacking attempt is unsuccessful, you will still gain experience points. <br><br>" +
"When you successfully hack a server. You steal a certain percentage of that server's total money. This " +
"percentage is determined by the server's security and your hacking skill 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 (since you are only hacking a certain percentage). You can " +
"increase the amount of money on a server using a script and the grow() function in Netscript.<br><br>" +
"<h1>Server Security</h1><br>" +
"Each server has a security level, typically between 1 and 100. A higher number means the server has stronger security. " +
"It is possible for a server to have a security level of 100 or higher, in which case hacking that server " +
"will become impossible (0% chance to hack).<br><br>" +
"As mentioned above, a server's security level is an important factor " +
"to consider when hacking. You can check a server's security level using the 'analyze' command, although this " +
"only gives an estimate (with 5% uncertainty). You can also check a server's security in a script, using the " +
"<i>getServerSecurityLevel(server)</i> function in Netscript. See the Netscript documentation for more details. " +
"This function will give you an exact value for a server's security. <br><br>" +
"Whenever a server is hacked manually or through a script, its security level increases by a small amount. Calling " +
"the grow() command in a script will also increase security level of the target server. These actions will " +
"make it harder for you to hack the server, and decrease the amount of money you can steal. You can lower a " +
"server's security level in a script using the <i>weaken(server)</i> function in Netscript. See the Netscript " +
"documentation for more details.<br><br>" +
"A server has a minimum security level that is equal to one third of its starting security, rounded to the " +
"nearest integer. To be more precise:<br><br>" +
"server.minSecurityLevel = Math.max(1, Math.round(server.startingSecurityLevel / 3))<br><br>" +
"This means that a server's security will not fall below this value if you are trying to weaken it.",
TutorialScriptsText: "Scripts can be used to automate the hacking process. Scripts must be written in the Netscript language. " +
"Documentation about the Netscript language can be found in the 'Netscript Programming Language' " +
"section of this 'Tutorial' page. <br><br> " +
"<strong>It is highly recommended that you have a basic background in programming to start writing scripts. " +
"You by no means need to be an expert. All you need is some familiarity with basic programming " +
"constructs like for/while loops, if statements, " +
"functions, variables, etc. The Netscript programming language most resembles the Javascript language. " +
"Therefore, a good beginner's programming tutorial to read might be <a href='https://www.w3schools.com/js/default.asp' target='_blank'>" +
"this one</a>. Note that while the Netscript language is similar to Javascript, it is not the exact same, so the " +
"syntax will vary a little bit. </strong> <br><br>" +
"Running a script requires RAM. The more complex a script is, the more RAM " +
"it requires to run. Scripts can be run on any server you have root access to. <br><br>" +
"Here are some Terminal commands that are useful when working with scripts: <br><br>" +
"<i>check [script] [args...]</i><br>Prints the logs of the script specified by the name and arguments to Terminal. Arguments should be separated " +
"by a space. Note that scripts are uniquely " +
"identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the argument 'foodnstuff' then in order to 'check' it you must " +
"also add the 'foodnstuff' argument to the check command as so: <br>check foo.script foodnstuff<br><br>" +
"<i>free</i><br>Shows the current server's RAM usage and availability <br><br>" +
"<i>kill [script] [args...]</i><br>Stops a script that is running with the specified script name and arguments. " +
"Arguments should be separated by a space. Note that " +
"scripts are uniquely identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the " +
"argument 1 and 2, then just typing 'kill foo.script' will not work. You have to use 'kill foo.script 1 2'. <br><br>" +
"<i>mem [script] [-t] [n]</i><br>Check how much RAM a script requires to run with n threads<br><br>" +
"<i>nano [script]</i><br>Create/Edit a script. The name of the script must end with the '.script' extension <br><br>" +
"<i>ps</i><br>Displays all scripts that are actively running on the current server<br><br>" +
"<i>rm [script]</i><br>Delete a script<br><br>" +
"<i>run [script] [-t] [n] [args...]</i><br>Run a script with n threads and the specified arguments. Each argument should be separated by a space. " +
"Both the arguments and thread specification are optional. If neither are specified, then the script will be run single-threaded with no arguments.<br>" +
"Examples:<br>run foo.script<br>The command above will run 'foo.script' single-threaded with no arguments." +
"<br>run foo.script -t 10<br>The command above will run 'foo.script' with 10 threads and no arguments." +
"<br>run foo.script foodnstuff sigma-cosmetics 10<br>The command above will run 'foo.script' single-threaded with three arguments: [foodnstuff, sigma-cosmetics, 10]" +
"<br>run foo.script -t 50 foodnstuff<br>The command above will run 'foo.script' with 50 threads and a single argument: [foodnstuff]<br><br>" +
"<i>tail [script] [args...]</i><br>Displays the logs of the script specified by the name and arguments. Note that scripts are uniquely " +
"identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the argument 'foodnstuff' then in order to 'tail' it you must " +
"also add the 'foodnstuff' argument to the tail command as so: <br>tail foo.script foodnstuff<br><br>" +
"<i>top</i><br>Displays all active scripts and their RAM usage <br><br>" +
"<u><h1> Multithreading scripts </h1></u><br>" +
"Scripts can be multithreaded. A multithreaded script runs the script's code once in each thread. The result is that " +
"every call to the hack(), grow(), and weaken() Netscript functions will have its effect multiplied by the number of threads. " +
"For example, if a normal single-threaded script is able to hack $10,000, then running the same script with 5 threads would " +
"yield $50,000. <br><br> " +
"When multithreading a script, the total RAM cost can be calculated by simply multiplying the base RAM cost of the script " +
"with the number of threads, where the base cost refers to the amount of RAM required to run the script single-threaded. " +
"In the terminal, you can run the " +
"'mem [scriptname] -t n' command to see how much RAM a script requires with n threads. <br><br>" +
"Every method for running a script has an option for making it multihreaded. To run a script with " +
"n threads from a Terminal: <br>" +
"run [scriptname] -t n<br><br>" +
"Using Netscript commands: <br>" +
"run('scriptname.script', n);<br> " +
"exec('scriptname.script, 'targetServer', n);<br><br>" +
"<u><h1> Notes about how scripts work offline </h1> </u><br>" +
"<strong> The scripts that you write and execute are interpreted in Javascript. For this " +
"reason, it is not possible for these scripts to run while offline (when the game is closed). " +
"It is important to note that for this reason, conditionals such as if/else statements and certain " +
"commands such as purchaseHacknetNode() or nuke() will not work while the game is offline.<br><br>" +
"However, Scripts WILL continue to generate money and hacking exp for you while the game is offline. This " +
"offline production is based off of the scripts' production while the game is online. <br><br>" +
"grow() and weaken() are two Netscript commands that will also be applied when the game is offline, although at a slower rate " +
"compared to if the game was open. This is done by having each script keep track of the " +
"rate at which the grow() and weaken() commands are called when the game is online. These calculated rates are used to determine how many times " +
"these function calls would be made while the game is offline. <br><br> " +
"Also, note that because of the way the Netscript interpreter is implemented, " +
"whenever you reload or re-open the game all of the scripts that you are running will " +
"start running from the BEGINNING of the code. The game does not keep track of where exactly " +
"the execution of a script is when it saves/loads. </strong><br><br>",
TutorialNetscriptText: "Netscript is a programming language implemented for this game. There are two versions of Netscript: " +
"Netscript 1.0 and Netscript 2.0 (NetscriptJS).<br><br>" +
"<a href='https://bitburner.readthedocs.io/en/latest/index.html' target='_blank'>Click here for Bitburner's official Netscript documentation</a>",
TutorialTravelingText: "There are six major cities in the world that you are able to travel to: <br><br> " +
" Aevum<br>" +
" Chongqing<br>" +
" Sector-12<br>" +
" New Tokyo<br>" +
" Ishima<br>" +
" Volhaven<br><br>" +
"To travel between cities, visit your current city's travel agency through the 'World' page. " +
"From the travel agency you can travel to any other city. Doing so costs money. <br><br>" +
"Each city has its own set of companies and unique locations. Also, certain content is only available to you " +
"if you are in certain cities, so get exploring!",
TutorialCompaniesText: "Hacking is not the only way to gain money and experience! Located around the world are many " +
"different companies which you can work for. By working for a company you can earn money, " +
"train your various labor skills, and unlock powerful passive perks. <br><br> " +
"To apply for a job, visit the company you want to work for through the 'World' menu. The company " +
"page will have options that let you apply to positions in the company. There might be several different " +
"positions you can apply for, ranging from software engineer to business analyst to security officer. <br><br> " +
"When you apply for a job, you will get the offer if your stats are high enough. Your first position at " +
"a company will be an entry-level position such as 'intern'. Once you get the job, an button will appear on " +
"the company page that allows you to work for the company. Click this button to start working. <br><br>" +
"Working occurs in 8 hour shifts. Once you start working, you will begin earning money, experience, " +
"and reputation. The rate at which you money and experience depends on the company and your position. " +
"The amount of reputation you gain for your company is based on your job performance, which is affected by " +
"your stats. Different positions value different stats. When you are working, you are unable to perform any " +
"other actions such as using your terminal or visiting other locations (However, note that any scripts you have " +
"running on servers will continue to run as you work!). It is possible to cancel your work shift before the " +
"8 hours is up. However, if you have a full-time job, then cancelling a shift early will result in you gaining " +
"only half of the reputation " +
"that you had earned up to that point. There are also part-time/consultant jobs available where you will not " +
" be penalized if you cancel a work shift early. However, these positions pay less than full-time positions.<br><br>" +
"As you continue to work at a company, you will gain more and more reputation at that company. When your stats " +
"and reputation are high enough, you can get a promotion. You can apply for a promotion on the company page, just like " +
"you applied for the job originally. Higher positions at a company provide better salaries and stat gains.<br><br>" +
"<h1>Infiltrating Companies</h1><br>" +
"Many companies have facilities that you can attempt to infiltrate. By infiltrating, you can steal classified company secrets " +
"and then sell these for money or for faction reputation. To try and infiltrate a company, visit a company through the " +
"'World' menu. There will be an option that says 'Infiltrate Company'. <br><br>" +
"When infiltrating a company, you must progress through clearance levels in the facility. Every clearance level " +
"has some form of security that you must get past. There are several forms of security, ranging from high-tech security systems to " +
"armed guards. For each form of security, there are a variety of options that you can choose to try and bypass the security. Examples " +
"include hacking the security, engaging in combat, assassination, or sneaking past the security. The chance to succeed for each option " +
"is determined in part by your stats. So, for example, trying to hack the security system relies on your hacking skill, whereas trying to " +
"sneak past the security relies on your agility level.<br><br>" +
"The facility has a 'security level' that affects your chance of success when trying to get past a clearance level. " +
"Every time you advance to the next clearance level, the facility's security level will increase by a fixed amount. Furthermore " +
"the options you choose and whether you succeed or fail will affect the security level as well. For example, " +
"if you try to kill a security guard and fail, the security level will increase by a lot. If you choose to sneak past " +
"security and succeed, the security level will not increase at all. <br><br>" +
"Every 5 clearance levels, you will steal classified company secrets that can be sold for money or faction reputation. However, " +
"in order to sell these secrets you must successfully escape the facility using the 'Escape' option. Furthermore, companies have " +
"a max clearance level. If you reach the max clearance level you will automatically escape the facility with all of your " +
"stolen secrets.<br><br>",
TutorialFactionsText: "Throughout the game you may receive invitations from factions. There are many different factions, and each faction " +
"has different criteria for determining its potential members. Joining a faction and furthering its cause is crucial " +
"to progressing in the game and unlocking endgame content. <br><br> " +
"It is possible to join multiple factions if you receive invitations from them. However, note that joining a faction " +
"may prevent you from joining other rival factions. <br><br> " +
"The 'Factions' link on the menu brings up a list of all factions that you have joined. " +
"You can select a Faction on this list to go to that Faction page. This page displays general " +
"information about the Faction and also lets you perform work for the faction. " +
"Working for a Faction is similar to working for a company except that you don't get paid a salary. " +
"You will only earn reputation in your Faction and train your stats. Also, cancelling work early " +
"when working for a Faction does NOT result in reduced experience/reputation earnings. <br><br>" +
"Earning reputation for a Faction unlocks powerful Augmentations. Purchasing and installing these Augmentations will " +
"upgrade your abilities. The Augmentations that are available to unlock vary from faction to faction.",
TutorialAugmentationsText: "Advances in science and medicine have lead to powerful new technologies that allow people to augment themselves " +
"beyond normal human capabilities. There are many different types of Augmentations, ranging from cybernetic to " +
"genetic to biological. Acquiring these Augmentations enhances the user's physical and mental faculties. <br><br>" +
"Because of how powerful these Augmentations are, the technology behind them is kept private and secret by the " +
"corporations and organizations that create them. Therefore, the only way for the player to obtain Augmentations is " +
"through Factions. After joining a Faction and earning enough reputation in it, you will be able to purchase " +
"its Augmentations. Different Factions offer different Augmentations. Augmentations must be purchased in order to be installed, " +
"and they are fairly expensive. <br><br>" +
"When you purchase an Augmentation, the price of purchasing another Augmentation increases by 90%. This multiplier stacks for " +
"each Augmentation you purchase. You will not gain the benefits of your purchased Augmentations until you install them. You can " +
"choose to install Augmentations through the 'Augmentations' menu tab. Once you install your purchased Augmentations, " +
"their costs are reset back to the original price.<br><br>" +
"Unfortunately, installing Augmentations has side effects. You will lose most of the progress you've made, including your " +
"skills, stats, and money. You will have to start over, but you will have all of the Augmentations you have installed to " +
"help you progress. <br><br> " +
"To summarize, here is a list of everything you will LOSE when you install an Augmentation: <br><br>" +
"Stats/Skills<br>" +
"Money<br>" +
"Scripts on all servers EXCEPT your home computer<br>" +
"Purchased servers<br>" +
"Hacknet Nodes<br>" +
"Company/faction reputation<br>" +
"Jobs and Faction memberships<br>" +
"Programs<br>" +
"Stocks<br>" +
"TOR router<br><br>" +
"Here is everything you will KEEP when you install an Augmentation: <br><br>" +
"Every Augmentation you have installed<br>" +
"Scripts on your home computer<br>" +
"RAM and CPU Core Upgrades on your home computer<br>" +
"World Stock Exchange account and TIX API Access<br>",
LatestUpdate: `
v0.41.2
* IMPORTANT - Netscript Changes:
** rm() now takes an optional parameter that lets you specify on which server to delete the file
** Added growthAnalyze() Netscript function
* Gang Changes:
** UI now displays your chance to win a clash with other gangs
** Added getChanceToWinClash() function to the Gang API
** Added getEquipmentType() function to the Gang API
** Added several new hacking-based equipment and Augmentations
** Rebalanced several equipment/upgrades to give less defense
** Wanted level gain rate is now be slightly higher for all tasks
** Rebalanced parameters for "hacking" tasks
* Added new Main Menu configuration in .fconf: "compact"
* Added the terminal command 'expr', which can be used to evaluate simple mathematical expressions
* Bug Fix: Can no longer purchase duplicate equipment/Augmentations through gang.purchaseEquipment()
* Bug Fix: scp() should no longer throw errors when used with 2-arguments and an array of files
* Bug Fix: Coding Contracts no longer give money in BitNode-8
* Bug Fix: In Bladeburner, you can no longer start a BlackOp through the Netscript API if it has already been completed
* Bug Fix: In Bladeburner, fixed a bug which caused the configured 'automate' actions to occasionally be switched to other actions
* Bug Fix: 'Return to World' button at locations no longer accumulates event listeners
* Bug Fix: Working & taking classes now continuously add/subtract money during the action, instead of doing it at completion
* Bug Fix: Top-right overview panel now displays negative money using '-' instead of '()'
* Bug Fix: Stock Market UI should no longer show 'NaN' profit immediately after buying a stock
`
};
/***/ }),
/* 2 */
/*!******************************************!*\
!*** ./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;
}
}
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;
}
}
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,
}));
}
}
/**
* 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;
/***/ }),
/* 3 */
/*!****************************************!*\
!*** ./utils/StringHelperFunctions.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: containsAllStrings, convertTimeMsToTimeElapsedString, formatNumber, generateRandomString, isString, longestCommonStart, replaceAt */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __webpack_require__(/*! ./helpers/isString */ 37);
// 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 -> "0 hours 0 minutes and 10 seconds"
120000 -> "0 0 hours 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;
/***/ }),
/* 4 */
/*!*********************************!*\
!*** ./src/ui/numeralFormat.js ***!
\*********************************/
/*! exports provided: numeralWrapper */
/*! exports used: numeralWrapper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return numeralWrapper; });
/* harmony import */ var numeral__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! numeral */ 70);
/* harmony import */ var numeral__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(numeral__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! numeral/locales/bg */ 258);
/* harmony import */ var numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! numeral/locales/cs */ 257);
/* harmony import */ var numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! numeral/locales/da-dk */ 256);
/* harmony import */ var numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var numeral_locales_de__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! numeral/locales/de */ 255);
/* harmony import */ var numeral_locales_de__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_de__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! numeral/locales/en-au */ 254);
/* harmony import */ var numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! numeral/locales/en-gb */ 253);
/* harmony import */ var numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var numeral_locales_es__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/locales/es */ 252);
/* harmony import */ var numeral_locales_es__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_es__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! numeral/locales/fr */ 251);
/* harmony import */ var numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! numeral/locales/hu */ 250);
/* harmony import */ var numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var numeral_locales_it__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/locales/it */ 249);
/* harmony import */ var numeral_locales_it__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_it__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! numeral/locales/lv */ 248);
/* harmony import */ var numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var numeral_locales_no__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! numeral/locales/no */ 247);
/* harmony import */ var numeral_locales_no__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_no__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! numeral/locales/pl */ 246);
/* harmony import */ var numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! numeral/locales/ru */ 245);
/* harmony import */ var numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14__);
/* eslint-disable class-methods-use-this */
class NumeralFormatter {
constructor() {
this.defaultLocale = 'en';
}
updateLocale(l) {
if (numeral__WEBPACK_IMPORTED_MODULE_0___default.a.locale(l) == null) {
console.warn(`Invalid locale for numeral: ${l}`);
numeral__WEBPACK_IMPORTED_MODULE_0___default.a.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__WEBPACK_IMPORTED_MODULE_0___default()(n).format(format);
}
}
const numeralWrapper = new NumeralFormatter();
/***/ }),
/* 5 */
/*!**************************!*\
!*** ./src/Locations.ts ***!
\**************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Display Location Content when visiting somewhere in the World
*/
// tslint:disable-next-line:variable-name
exports.Locations = {
// Cities
Aevum: "Aevum",
Chongqing: "Chongqing",
Ishima: "Ishima",
NewTokyo: "New Tokyo",
Sector12: "Sector-12",
Volhaven: "Volhaven",
// Aevum Locations
AevumAeroCorp: "AeroCorp",
AevumBachmanAndAssociates: "Bachman & Associates",
AevumClarkeIncorporated: "Clarke Incorporated",
AevumCrushFitnessGym: "Crush Fitness Gym",
AevumECorp: "ECorp",
AevumFulcrumTechnologies: "Fulcrum Technologies",
AevumGalacticCybersystems: "Galactic Cybersystems",
AevumNetLinkTechnologies: "NetLink Technologies",
AevumPolice: "Aevum Police Headquarters",
AevumRhoConstruction: "Rho Construction",
AevumSlums: "Aevum Slums",
AevumSnapFitnessGym: "Snap Fitness Gym",
AevumSummitUniversity: "Summit University",
AevumTravelAgency: "Aevum Travel Agency",
AevumWatchdogSecurity: "Watchdog Security",
// Chongqing locations
ChongqingKuaiGongInternational: "KuaiGong International",
ChongqingSlums: "Chongqing Slums",
ChongqingSolarisSpaceSystems: "Solaris Space Systems",
ChongqingTravelAgency: "Chongqing Travel Agency",
// Sector 12
Sector12AlphaEnterprises: "Alpha Enterprises",
Sector12BladeIndustries: "Blade Industries",
Sector12CIA: "Central Intelligence Agency",
Sector12CarmichaelSecurity: "Carmichael Security",
Sector12CityHall: "Sector-12 City Hall",
Sector12DeltaOne: "DeltaOne",
Sector12FoodNStuff: "FoodNStuff",
Sector12FourSigma: "Four Sigma",
Sector12IcarusMicrosystems: "Icarus Microsystems",
Sector12IronGym: "Iron Gym",
Sector12JoesGuns: "Joe's Guns",
Sector12MegaCorp: "MegaCorp",
Sector12NSA: "National Security Agency",
Sector12PowerhouseGym: "Powerhouse Gym",
Sector12RothmanUniversity: "Rothman University",
Sector12Slums: "Sector-12 Slums",
Sector12TravelAgency: "Sector-12 Travel Agency",
Sector12UniversalEnergy: "Universal Energy",
// New Tokyo
NewTokyoDefComm: "DefComm",
NewTokyoGlobalPharmaceuticals: "Global Pharmaceuticals",
NewTokyoNoodleBar: "Noodle Bar",
NewTokyoSlums: "New Tokyo Slums",
NewTokyoTravelAgency: "New Tokyo Travel Agency",
NewTokyoVitaLife: "VitaLife",
// Ishima
IshimaNovaMedical: "Nova Medical",
IshimaOmegaSoftware: "Omega Software",
IshimaSlums: "Ishima Slums",
IshimaStormTechnologies: "Storm Technologies",
IshimaTravelAgency: "Ishima Travel Agency",
// Volhaven
VolhavenCompuTek: "CompuTek",
VolhavenHeliosLabs: "Helios Labs",
VolhavenLexoCorp: "LexoCorp",
VolhavenMilleniumFitnessGym: "Millenium Fitness Gym",
VolhavenNWO: "NWO",
VolhavenOmniTekIncorporated: "OmniTek Incorporated",
VolhavenOmniaCybersystems: "Omnia Cybersystems",
VolhavenSlums: "Volhaven Slums",
VolhavenSysCoreSecurities: "SysCore Securities",
VolhavenTravelAgency: "Volhaven Travel Agency",
VolhavenZBInstituteOfTechnology: "ZB Institute of Technology",
// Generic locations
Hospital: "Hospital",
WorldStockExchange: "World Stock Exchange",
};
/***/ }),
/* 6 */
/*!***********************************!*\
!*** ./src/NetscriptEvaluator.js ***!
\***********************************/
/*! exports provided: makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript, evaluate, isScriptErrorMessage, killNetscriptDelay, evaluateImport */
/*! exports used: evaluateImport, isScriptErrorMessage, killNetscriptDelay, makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return makeRuntimeRejectMsg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return netscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptFromScript; });
/* unused harmony export evaluate */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isScriptErrorMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return killNetscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return evaluateImport; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment */ 105);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/acorn */ 46);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 52);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 84);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__);
var Promise = __webpack_require__(/*! bluebird */ 230);
Promise.config({
warnings: false,
longStackTraces: false,
cancellation: true,
monitoring: false
});
/* Evaluator
* Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser
*
* Returns a promise
*/
function evaluate(exp, workerScript) {
return Promise.delay(_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
if (exp == null) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression", exp));
}
if (env.stopFlag) {return Promise.reject(workerScript);}
switch (exp.type) {
case "BlockStatement":
case "Program":
var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment
return evaluateProgPromise.then(function(w) {
return Promise.resolve(workerScript);
}).catch(function(e) {
if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") {
return Promise.reject(e);
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) {
workerScript.errorMessage = e;
return Promise.reject(workerScript);
} else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) {
return Promise.reject(e);
} else {
return Promise.reject(workerScript);
}
});
break;
case "Literal":
return Promise.resolve(exp.value);
break;
case "Identifier":
//Javascript constructor() method can be used as an exploit to run arbitrary code
if (exp.name == "constructor") {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp));
}
if (!(exp.name in env.vars)){
return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp));
}
return Promise.resolve(env.get(exp.name))
break;
case "ExpressionStatement":
return evaluate(exp.expression, workerScript);
break;
case "ArrayExpression":
var argPromises = exp.elements.map(function(arg) {
return evaluate(arg, workerScript);
});
return Promise.all(argPromises).then(function(array) {
return Promise.resolve(array)
});
break;
case "CallExpression":
return evaluate(exp.callee, workerScript).then(function(func) {
return Promise.map(exp.arguments, function(arg) {
return evaluate(arg, workerScript);
}).then(function(args) {
if (func instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) { //Player-defined function
//Create new Environment for the function
//Should be automatically garbage collected...
var funcEnv = env.extend();
//Define function arguments in this new environment
for (var i = 0; i < func.params.length; ++i) {
var arg;
if (i >= args.length) {
arg = null;
} else {
arg = args[i];
}
funcEnv.def(func.params[i].name, arg);
}
//Create a new WorkerScript for this function evaluation
var funcWorkerScript = new _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"](workerScript.scriptRef);
funcWorkerScript.serverIp = workerScript.serverIp;
funcWorkerScript.env = funcEnv;
workerScript.fnWorker = funcWorkerScript;
return evaluate(func.body, funcWorkerScript).then(function(res) {
//If the function finished successfuly, that means there
//was no return statement since a return statement rejects. So resolve to null
workerScript.fnWorker = null;
return Promise.resolve(null);
}).catch(function(e) {
if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") {
//Return statement from function
return Promise.resolve(e[1]);
workerScript.fnWorker = null;
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, e));
} else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) {
//Parse out the err message from the WorkerScript and re-reject
var errorMsg = e.errorMessage;
var errorTextArray = errorMsg.split("|");
if (errorTextArray.length === 4) {
errorMsg = errorTextArray[3];
return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg));
} else {
if (env.stopFlag) {
return Promise.reject(workerScript);
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function"));
}
}
} else if (e instanceof Error) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString()));
}
});
} else if (exp.callee.type === "MemberExpression"){
return evaluate(exp.callee.object, workerScript).then(function(object) {
try {
if (func === "NETSCRIPTFOREACH") {
return evaluateForeach(object, args, workerScript).then(function(res) {
return Promise.resolve(res);
}).catch(function(e) {
return Promise.reject(e);
});
}
var res = func.apply(object,args);
return Promise.resolve(res);
} catch (e) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp));
}
});
} else {
try {
var out = func.apply(null,args);
if (out instanceof Promise){
return out.then(function(res) {
return Promise.resolve(res)
}).catch(function(e) {
if (isScriptErrorMessage(e)) {
//Functions don't have line number appended in error message, so add it
var num = getErrorLineNumber(exp, workerScript);
e += " (Line " + num + ")";
}
return Promise.reject(e);
});
} else {
return Promise.resolve(out);
}
} catch (e) {
if (isScriptErrorMessage(e)) {
if (isScriptErrorMessage(e)) {
//Functions don't have line number appended in error message, so add it
var num = getErrorLineNumber(exp, workerScript);
e += " (Line " + num + ")";
}
return Promise.reject(e);
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp));
}
}
}
});
});
break;
case "MemberExpression":
return evaluate(exp.object, workerScript).then(function(object) {
if (exp.computed){
return evaluate(exp.property, workerScript).then(function(index) {
if (index >= object.length) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp));
}
return Promise.resolve(object[index]);
}).catch(function(e) {
if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] || isScriptErrorMessage(e)) {
return Promise.reject(e);
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp));
}
});
} else {
if (exp.property.name === "constructor") {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp));
}
if (object != null && object instanceof Array && exp.property.name === "forEach") {
return "NETSCRIPTFOREACH";
}
try {
return Promise.resolve(object[exp.property.name])
} catch (e) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp));
}
}
});
break;
case "LogicalExpression":
case "BinaryExpression":
return evalBinary(exp, workerScript);
break;
case "UnaryExpression":
return evalUnary(exp, workerScript);
break;
case "AssignmentExpression":
return evalAssignment(exp, workerScript);
break;
case "VariableDeclaration":
return evalVariableDeclaration(exp, workerScript);
break;
case "UpdateExpression":
if (exp.argument.type==="Identifier"){
if (exp.argument.name in env.vars){
if (exp.operator === "++" || exp.operator === "--") {
switch (exp.operator) {
case "++":
env.set(exp.argument.name,env.get(exp.argument.name)+1);
break;
case "--":
env.set(exp.argument.name,env.get(exp.argument.name)-1);
break;
default: break;
}
return Promise.resolve(env.get(exp.argument.name));
}
//Not sure what prefix UpdateExpressions there would be besides ++/--
if (exp.prefix){
return Promise.resolve(env.get(exp.argument.name))
}
switch (exp.operator){
default:
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp));
}
return Promise.resolve(env.get(exp.argument.name))
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp));
}
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp));
}
break;
case "EmptyStatement":
return Promise.resolve(false);
break;
case "ReturnStatement":
return evaluate(exp.argument, workerScript).then(function(res) {
return Promise.reject(["RETURNSTATEMENT", res]);
});
break;
case "BreakStatement":
return Promise.reject("BREAKSTATEMENT");
break;
case "ContinueStatement":
return Promise.reject("CONTINUESTATEMENT");
break;
case "IfStatement":
return evaluateIf(exp, workerScript);
break;
case "SwitchStatement":
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp));
break;
case "WhileStatement":
return evaluateWhile(exp, workerScript).then(function(res) {
return Promise.resolve(res);
}).catch(function(e) {
if (e == "BREAKSTATEMENT" ||
(e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "BREAKSTATEMENT")) {
return Promise.resolve("whileLoopBroken");
} else {
return Promise.reject(e);
}
});
break;
case "ForStatement":
return evaluate(exp.init, workerScript).then(function(expInit) {
return evaluateFor(exp, workerScript);
}).then(function(forLoopRes) {
return Promise.resolve("forLoopDone");
}).catch(function(e) {
if (e == "BREAKSTATEMENT" ||
(e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "BREAKSTATEMENT")) {
return Promise.resolve("forLoopBroken");
} else {
return Promise.reject(e);
}
});
break;
case "FunctionDeclaration":
if (exp.id && exp.id.name) {
env.set(exp.id.name, exp);
return Promise.resolve(true);
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp));
}
break;
case "ImportDeclaration":
return evaluateImport(exp, workerScript).then(function(res) {
return Promise.resolve(res);
}).catch(function(e) {
return Promise.reject(e);
});
break;
case "ThrowStatement":
return evaluate(exp.argument, workerScript).then(function(res) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, res));
});
break;
default:
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp));
break;
} //End switch
}).catch(function(e) {
return Promise.reject(e);
}); // End Promise
}
function evalBinary(exp, workerScript){
return evaluate(exp.left, workerScript).then(function(expLeft) {
//Short circuiting
if (expLeft && exp.operator === "||") {
return Promise.resolve(expLeft);
}
if (!expLeft && exp.operator === "&&") {
return Promise.resolve(expLeft);
}
return evaluate(exp.right, workerScript).then(function(expRight) {
switch (exp.operator){
case "===":
case "==":
return Promise.resolve(expLeft===expRight);
break;
case "!==":
case "!=":
return Promise.resolve(expLeft!==expRight);
break;
case "<":
return Promise.resolve(expLeft<expRight);
break;
case "<=":
return Promise.resolve(expLeft<=expRight);
break;
case ">":
return Promise.resolve(expLeft>expRight);
break;
case ">=":
return Promise.resolve(expLeft>=expRight);
break;
case "+":
return Promise.resolve(expLeft+expRight);
break;
case "-":
return Promise.resolve(expLeft-expRight);
break;
case "*":
return Promise.resolve(expLeft*expRight);
break;
case "/":
if (expRight === 0) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero"));
} else {
return Promise.resolve(expLeft/expRight);
}
break;
case "%":
return Promise.resolve(expLeft%expRight);
break;
case "in":
return Promise.resolve(expLeft in expRight);
break;
case "instanceof":
return Promise.resolve(expLeft instanceof expRight);
break;
case "||":
return Promise.resolve(expLeft || expRight);
break;
case "&&":
return Promise.resolve(expLeft && expRight);
break;
default:
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator));
}
});
});
}
function evalUnary(exp, workerScript){
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
return evaluate(exp.argument, workerScript).then(function(res) {
if (exp.operator == "!") {
return Promise.resolve(!res);
} else if (exp.operator == "-") {
if (isNaN(res)) {
return Promise.resolve(res);
} else {
return Promise.resolve(-1 * res);
}
} else {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator));
}
});
}
//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional)
//The return value is an array of the form:
// [0th index (leftmost), array name, 1st index, 2nd index, ...]
function getArrayElement(exp, workerScript) {
var indices = [];
return evaluate(exp.property, workerScript).then(function(idx) {
if (isNaN(idx)) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx));
} else {
if (exp.object.name === undefined && exp.object.object) {
return getArrayElement(exp.object, workerScript).then(function(res) {
res.push(idx);
indices = res;
return Promise.resolve(indices);
}).catch(function(e) {
return Promise.reject(e);
});
} else {
indices.push(idx);
indices.push(exp.object.name);
return Promise.resolve(indices);
}
}
});
}
function evalAssignment(exp, workerScript) {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left)));
}
if (exp.operator !== "=" && !(exp.left.name in env.vars)){
return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined"));
}
return evaluate(exp.right, workerScript).then(function(expRight) {
if (exp.left.type == "MemberExpression") {
if (!exp.left.computed) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to an object's property. This is currently unsupported in Netscript", exp));
}
//Assign to array element
//Array object designed by exp.left.object.name
//Index designated by exp.left.property
return getArrayElement(exp.left, workerScript).then(function(res) {
if (!(res instanceof Array) || res.length < 2) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev"));
}
//The array name is the second value
var arrName = res.splice(1, 1);
arrName = arrName[0];
var res;
try {
res = env.setArrayElement(arrName, res, expRight);
} catch (e) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, e));
}
return Promise.resolve(res);
}).catch(function(e) {
return Promise.reject(e);
});
} else {
//Other assignments
try {
var assign;
switch (exp.operator) {
case "=":
assign = expRight; break;
case "+=":
assign = env.get(exp.left.name) + expRight; break;
case "-=":
assign = env.get(exp.left.name) - expRight; break;
case "*=":
assign = env.get(exp.left.name) * expRight; break;
case "/=":
assign = env.get(exp.left.name) / expRight; break;
case "%=":
assign = env.get(exp.left.name) % expRight; break;
default:
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented"));
}
env.set(exp.left.name, assign);
return Promise.resolve(assign);
} catch (e) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString()));
}
}
});
}
function evalVariableDeclaration(exp, workerScript) {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
if (!(exp.declarations instanceof Array)) {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Variable declarations parsed incorrectly. This may be a syntax error"));
}
if (exp.kind !== "var") {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Only 'var' declarations are currently allowed (let, const, etc. are not allowed)"));
}
return Promise.all(exp.declarations.map((decl)=>{
evalVariableDeclarator(decl, workerScript);
})).then(function(res) {
return Promise.resolve(res);
});
}
//A Variable Declaration contains an array of Variable Declarators
function evalVariableDeclarator(exp, workerScript) {
var env = workerScript.env;
if (exp.type !== "VariableDeclarator") {
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid AST Node passed into evalVariableDeclarator: " + exp.type));
}
if (exp.init == null) {
env.set(exp.id.name, null);
return Promise.resolve(null);
} else {
return evaluate(exp.init, workerScript).then(function(initValue) {
env.set(exp.id.name, initValue);
});
}
}
function evaluateIf(exp, workerScript, i) {
var env = workerScript.env;
return evaluate(exp.test, workerScript).then(function(condRes) {
if (condRes) {
return evaluate(exp.consequent, workerScript).then(function(res) {
return Promise.resolve(true);
}, function(e) {
return Promise.reject(e);
});
} else if (exp.alternate) {
return evaluate(exp.alternate, workerScript).then(function(res) {
return Promise.resolve(true);
}, function(e) {
return Promise.reject(e);
});
} else {
return Promise.resolve("endIf");
}
});
}
//Evaluate the looping part of a for loop (Initialization block is NOT done in here)
function evaluateFor(exp, workerScript) {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
return new Promise(function(resolve, reject) {
function recurse() {
//Don't return a promise so the promise chain is broken on each recursion (saving memory)
evaluate(exp.test, workerScript).then(function(resCond) {
if (resCond) {
return evaluate(exp.body, workerScript).then(function(res) {
return evaluate(exp.update, workerScript);
}).catch(function(e) {
if (e == "CONTINUESTATEMENT" ||
(e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "CONTINUESTATEMENT")) {
//Continue statement, recurse to next iteration
return evaluate(exp.update, workerScript).then(function(resPostloop) {
return evaluateFor(exp, workerScript);
}).then(function(foo) {
return Promise.resolve("endForLoop");
}).catch(function(e) {
return Promise.reject(e);
});
} else {
return Promise.reject(e);
}
}).then(recurse, reject).catch(function(e) {
return Promise.reject(e);
});
} else {
resolve();
}
}).catch(function(e) {
reject(e);
});
}
recurse();
});
}
function evaluateForeach(arr, args, workerScript) {
console.log("evaluateForeach called");
if (!(arr instanceof Array)) {
return Promise.reject("Invalid array passed into forEach");
}
if (!(args instanceof Array) && args.length != 1) {
return Promise.reject("Invalid argument passed into forEach");
}
var func = args[0];
if (typeof func !== "function") {
return Promise.reject("Invalid function passed into forEach");
}
console.log(func);
return new Promise(function(resolve, reject) {
//Don't return a promise so the promise chain is broken on each recursion
function recurse(i) {
console.log("recurse() called with i: " + i);
if (i >= arr.length) {
resolve();
} else {
return Promise.delay(_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() {
console.log("About to apply function");
var res = func.apply(null, [arr[i]]);
console.log("Applied function");
++i;
Promise.resolve(res).then(function(val) {
recurse(i);
}, reject).catch(function(e) {
return Promise.reject(e);
});
});
}
}
recurse(0);
});
}
function evaluateWhile(exp, workerScript) {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
return new Promise(function (resolve, reject) {
function recurse() {
//Don't return a promise so the promise chain is broken on each recursion (saving memory)
evaluate(exp.test, workerScript).then(function(resCond) {
if (resCond) {
return evaluate(exp.body, workerScript).catch(function(e) {
if (e == "CONTINUESTATEMENT" ||
(e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "CONTINUESTATEMENT")) {
//Continue statement, recurse
return evaluateWhile(exp, workerScript).then(function(foo) {
return Promise.resolve("endWhileLoop");
}, function(e) {
return Promise.reject(e);
});
} else {
return Promise.reject(e);
}
}).then(recurse, reject).catch(function(e) {
return Promise.reject(e);
});
} else {
resolve();
}
}).catch(function(e) {
reject(e);
});
}
recurse();
});
}
function evaluateProg(exp, workerScript, index) {
var env = workerScript.env;
if (env.stopFlag) {return Promise.reject(workerScript);}
if (index >= exp.body.length) {
return Promise.resolve("progFinished");
} else {
//Evaluate this line of code in the prog
//After the code finishes evaluating, evaluate the next line recursively
return evaluate(exp.body[index], workerScript).then(function(res) {
return evaluateProg(exp, workerScript, index + 1);
}).then(function(res) {
return Promise.resolve(workerScript);
}).catch(function(e) {
return Promise.reject(e);
});
}
}
function evaluateImport(exp, workerScript, checkingRam=false) {
//When its checking RAM, it exports an array of nodes for each imported function
var ramCheckRes = [];
var env = workerScript.env;
if (env.stopFlag) {
if (checkingRam) {return ramCheckRes;}
return Promise.reject(workerScript);
}
//Get source script and name of all functions to import
var scriptName = exp.source.value;
var namespace, namespaceObj, allFns = false, fnNames = [];
if (exp.specifiers.length === 1 && exp.specifiers[0].type === "ImportNamespaceSpecifier") {
allFns = true;
namespace = exp.specifiers[0].local.name;
} else {
for (var i = 0; i < exp.specifiers.length; ++i) {
fnNames.push(exp.specifiers[i].local.name);
}
}
//Get the code
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_5__[/* getServer */ "e"])(workerScript.serverIp), code = "";
if (server == null) {
if (checkingRam) {return ramCheckRes;}
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to identify server. This is a bug please report to dev", exp));
}
for (var i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === scriptName) {
code = server.scripts[i].code;
break;
}
}
if (code === "") {
if (checkingRam) {return ramCheckRes;}
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Could not find script " + scriptName + " to import", exp));
}
//Create the AST
try {
var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_8__["parse"])(code, {sourceType:"module"});
} catch(e) {
console.log("Failed to parse import script");
if (checkingRam) {return ramCheckRes;}
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to import functions from " + scriptName +
" This is most likely due to a syntax error in the imported script", exp));
}
if (allFns) {
//A namespace is implemented as a JS obj
env.set(namespace, {});
namespaceObj = env.get(namespace);
}
//Search through the AST for all imported functions
var queue = [ast];
while (queue.length != 0) {
var node = queue.shift();
switch (node.type) {
case "BlockStatement":
case "Program":
for (var i = 0; i < node.body.length; ++i) {
if (node.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) {
queue.push(node.body[i]);
}
}
break;
case "FunctionDeclaration":
if (node.id && node.id.name) {
if (allFns) {
//Import all functions under this namespace
if (checkingRam) {
ramCheckRes.push(node);
} else {
namespaceObj[node.id.name] = node;
}
} else {
//Only import specified functions
if (fnNames.includes(node.id.name)) {
if (checkingRam) {
ramCheckRes.push(node);
} else {
env.set(node.id.name, node);
}
}
}
} else {
if (checkingRam) {return ramCheckRes;}
return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration in imported script " + scriptName, exp));
}
break;
default:
break;
}
for (var prop in node) {
if (node.hasOwnProperty(prop)) {
if (node[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) {
queue.push(node[prop]);
}
}
}
}
if (!checkingRam) {workerScript.scriptRef.log("Imported functions from " + scriptName);}
if (checkingRam) {return ramCheckRes;}
return Promise.resolve(true);
}
function killNetscriptDelay(workerScript) {
if (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) {
if (workerScript.delay) {
clearTimeout(workerScript.delay);
workerScript.delayResolve();
}
}
}
function netscriptDelay(time, workerScript) {
return new Promise(function(resolve, reject) {
workerScript.delay = setTimeout(()=>{
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;
}
//Run a script from inside a script using run() command
function runScriptFromScript(server, scriptname, args, workerScript, threads=1) {
//Check if the script is already running
var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_7__[/* findRunningScript */ "d"])(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 (var 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 (var i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) {
//Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage;
threads = Math.round(Number(threads)); //Convert to number and round
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_9__["arrayToString"])(args) + ". May take a few seconds to start up...");
}
var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_7__[/* RunningScript */ "b"](script, args);
runningScriptObj.threads = threads;
server.runningScripts.push(runningScriptObj); //Push onto runningScripts
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* addWorkerScript */ "c"])(runningScriptObj, server);
return Promise.resolve(true);
}
}
}
workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname);
return Promise.resolve(false);
}
function getErrorLineNumber(exp, workerScript) {
var code = workerScript.scriptRef.scriptRef.code;
//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_11__["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_10__["isValidIPAddress"])(ip)) {
return false;
}
return true;
}
/***/ }),
/* 7 */
/*!**********************************!*\
!*** ./src/ui/postToTerminal.ts ***!
\**********************************/
/*! no static exports found */
/*! exports used: hackProgressBarPost, hackProgressPost, post */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 51);
/**
* Adds some output to the terminal.
* @param input Text or HTML to output to the terminal
*/
function post(input) {
postContent(input);
}
exports.post = post;
/**
* 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, "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, "hack-progress");
}
exports.hackProgressPost = hackProgressPost;
function postContent(input, id) {
// tslint:disable-next-line:max-line-length
const style = `color: var(--my-font-color); background-color:var(--my-background-color);${id === undefined ? " white-space:pre-wrap;" : ""}`;
// tslint:disable-next-line:max-line-length
const content = `<tr class="posted"><td ${id === undefined ? 'class="terminal-line"' : `id="${id}"`} style="${style}">${input}</td></tr>`;
const inputElement = getElementById_1.getElementById("terminal-input");
inputElement.insertAdjacentHTML("beforebegin", content);
scrollTerminalToBottom();
}
function scrollTerminalToBottom() {
const container = getElementById_1.getElementById("terminal-container");
container.scrollTop = container.scrollHeight;
}
/***/ }),
/* 8 */
/*!***********************!*\
!*** ./src/engine.js ***!
\***********************/
/*! 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_DialogBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/GameOptions */ 80);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/removeLoadingScreen */ 109);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/LogBox */ 75);
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./ActiveScriptsUI */ 64);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./BitNode */ 56);
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Bladeburner */ 29);
/* harmony import */ var _CharacterOverview__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./CharacterOverview */ 118);
/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./CinematicText */ 93);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./CodingContractGenerator */ 92);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Company/CompanyPositions */ 26);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./CompanyManagement */ 58);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _DevMenu__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./DevMenu */ 107);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Fconf */ 45);
/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Location */ 86);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./HacknetNode */ 63);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./InteractiveTutorial */ 33);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Literature */ 78);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Message */ 38);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Missions */ 53);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./Prestige */ 82);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./RedPill */ 55);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./SaveObject */ 72);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./ui/setSettingsLabels */ 117);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./SourceFile */ 66);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./StockMarket */ 22);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./Terminal */ 49);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__);
/* harmony import */ var normalize_css__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! normalize.css */ 193);
/* harmony import */ var normalize_css__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(normalize_css__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var _css_styles_scss__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ../css/styles.scss */ 169);
/* harmony import */ var _css_styles_scss__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_css_styles_scss__WEBPACK_IMPORTED_MODULE_51__);
/* harmony import */ var _css_buttons_scss__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ../css/buttons.scss */ 167);
/* harmony import */ var _css_buttons_scss__WEBPACK_IMPORTED_MODULE_52___default = /*#__PURE__*/__webpack_require__.n(_css_buttons_scss__WEBPACK_IMPORTED_MODULE_52__);
/* harmony import */ var _css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ../css/mainmenu.scss */ 165);
/* harmony import */ var _css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_53___default = /*#__PURE__*/__webpack_require__.n(_css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_53__);
/* harmony import */ var _css_characteroverview_scss__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ../css/characteroverview.scss */ 163);
/* harmony import */ var _css_characteroverview_scss__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_css_characteroverview_scss__WEBPACK_IMPORTED_MODULE_54__);
/* harmony import */ var _css_terminal_scss__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ../css/terminal.scss */ 161);
/* harmony import */ var _css_terminal_scss__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_css_terminal_scss__WEBPACK_IMPORTED_MODULE_55__);
/* harmony import */ var _css_menupages_scss__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ../css/menupages.scss */ 159);
/* harmony import */ var _css_menupages_scss__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_css_menupages_scss__WEBPACK_IMPORTED_MODULE_56__);
/* harmony import */ var _css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ../css/workinprogress.scss */ 157);
/* harmony import */ var _css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_57__);
/* harmony import */ var _css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ../css/popupboxes.scss */ 155);
/* harmony import */ var _css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_58__);
/* harmony import */ var _css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ../css/interactivetutorial.scss */ 153);
/* harmony import */ var _css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_59___default = /*#__PURE__*/__webpack_require__.n(_css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_59__);
/* harmony import */ var _css_loader_scss__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ../css/loader.scss */ 151);
/* harmony import */ var _css_loader_scss__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_css_loader_scss__WEBPACK_IMPORTED_MODULE_60__);
/* harmony import */ var _css_missions_scss__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ../css/missions.scss */ 149);
/* harmony import */ var _css_missions_scss__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(_css_missions_scss__WEBPACK_IMPORTED_MODULE_61__);
/* harmony import */ var _css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ../css/companymanagement.scss */ 147);
/* harmony import */ var _css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_62___default = /*#__PURE__*/__webpack_require__.n(_css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_62__);
/* harmony import */ var _css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ../css/bladeburner.scss */ 145);
/* harmony import */ var _css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_63___default = /*#__PURE__*/__webpack_require__.n(_css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_63__);
/* harmony import */ var _css_gang_scss__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ../css/gang.scss */ 143);
/* harmony import */ var _css_gang_scss__WEBPACK_IMPORTED_MODULE_64___default = /*#__PURE__*/__webpack_require__.n(_css_gang_scss__WEBPACK_IMPORTED_MODULE_64__);
// These should really be imported with the module that is presenting that UI, but because they very much depend on the
// cascade order, we'll pull them all in here.
/* 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__WEBPACK_IMPORTED_MODULE_42__["Settings"].DisableHotkeys === true) {return;}
if (!_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].isWorking && !_RedPill__WEBPACK_IMPORTED_MODULE_38__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_33__[/* inMission */ "c"] && !_CinematicText__WEBPACK_IMPORTED_MODULE_16__[/* cinematicTextFlag */ "a"]) {
if (e.keyCode == 84 && e.altKey) {
e.preventDefault();
Engine.loadTerminalContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].C && e.altKey) {
e.preventDefault();
Engine.loadCharacterContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].E && e.altKey) {
e.preventDefault();
Engine.loadScriptEditorContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].S && e.altKey) {
e.preventDefault();
Engine.loadActiveScriptsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].H && e.altKey) {
e.preventDefault();
Engine.loadHacknetNodesContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].W && e.altKey) {
e.preventDefault();
Engine.loadWorldContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].J && e.altKey) {
e.preventDefault();
Engine.loadJobContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].R && e.altKey) {
e.preventDefault();
Engine.loadTravelContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].P && e.altKey) {
e.preventDefault();
Engine.loadCreateProgramContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].F && e.altKey) {
//Overriden by Fconf
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Terminal) && _Fconf__WEBPACK_IMPORTED_MODULE_26__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS) {
return;
}
e.preventDefault();
Engine.loadFactionsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].A && e.altKey) {
e.preventDefault();
Engine.loadAugmentationsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].U && e.altKey) {
e.preventDefault();
Engine.loadTutorialContent();
}
}
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_48__["KEY"].O && e.altKey) {
e.preventDefault();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxOpen */ "b"])();
}
});
const Engine = {
version: "",
Debug: true,
overview: new _CharacterOverview__WEBPACK_IMPORTED_MODULE_15__[/* CharacterOverview */ "a"](),
//Clickable objects
Clickables: {
//Main menu buttons
terminalMainMenuButton: null,
characterMainMenuButton: null,
scriptEditorMainMenuButton: null,
activeScriptsMainMenuButton: null,
hacknetNodesMainMenuButton: null,
worldMainMenuButton: null,
travelMainMenuButton: null,
jobMainMenuButton: null,
stockmarketMainMenuButton: null,
createProgramMainMenuButton: null,
factionsMainMenuButton: null,
augmentationsMainMenuButton: null,
tutorialMainMenuButton: null,
bladeburnerMenuButton: null,
corporationMenuButton: null,
gangMenuButton: null,
devMainMenuButton: null,
saveMainMenuButton: null,
deleteMainMenuButton: null,
//Tutorial buttons
tutorialNetworkingButton: null,
tutorialHackingButton: null,
tutorialScriptsButton: null,
tutorialNetscriptButton: null,
tutorialTravelingButton: null,
tutorialCompaniesButton: null,
tutorialFactionsButton: null,
tutorialAugmentationsButton: null,
tutorialBackButton: null,
},
//Display objects
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,
worldContent: null,
createProgramContent: null,
factionsContent: null,
factionContent: null,
factionAugmentationsContent: 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
/* Load content when a main menu button is clicked */
loadTerminalContent: function() {
Engine.hideAllContent();
Engine.Display.terminalContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Terminal);
document.getElementById("terminal-menu-link").classList.add("active");
},
loadCharacterContent: function() {
Engine.hideAllContent();
Engine.Display.characterContent.style.display = "block";
Engine.displayCharacterInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].CharacterInfo);
document.getElementById("stats-menu-link").classList.add("active");
},
loadScriptEditorContent: function(filename = "", code = "") {
Engine.hideAllContent();
Engine.Display.scriptEditorContent.style.display = "block";
var editor = ace.edit('javascript-editor');
if (filename != "") {
document.getElementById("script-editor-filename").value = filename;
editor.setValue(code);
}
editor.focus();
Object(_Script__WEBPACK_IMPORTED_MODULE_40__[/* updateScriptEditorContent */ "h"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].ScriptEditor);
document.getElementById("create-script-menu-link").classList.add("active");
},
loadActiveScriptsContent: function() {
Engine.hideAllContent();
Engine.Display.activeScriptsContent.style.display = "block";
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_11__[/* updateActiveScriptsItems */ "c"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].ActiveScripts);
document.getElementById("active-scripts-menu-link").classList.add("active");
},
loadHacknetNodesContent: function() {
Engine.hideAllContent();
Engine.Display.hacknetNodesContent.style.display = "block";
Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_29__[/* displayHacknetNodesContent */ "b"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].HacknetNodes);
document.getElementById("hacknet-nodes-menu-link").classList.add("active");
},
loadWorldContent: function() {
Engine.hideAllContent();
Engine.Display.worldContent.style.display = "block";
Engine.displayWorldInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].World);
document.getElementById("city-menu-link").classList.add("active");
},
loadCreateProgramContent: function() {
Engine.hideAllContent();
Engine.Display.createProgramContent.style.display = "block";
Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_22__[/* displayCreateProgramContent */ "b"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].CreateProgram);
document.getElementById("create-program-menu-link").classList.add("active");
},
loadFactionsContent: function() {
Engine.hideAllContent();
Engine.Display.factionsContent.style.display = "block";
Engine.displayFactionsInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Factions);
document.getElementById("factions-menu-link").classList.add("active");
},
loadFactionContent: function() {
Engine.hideAllContent();
Engine.Display.factionContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Faction);
},
loadAugmentationsContent: function() {
Engine.hideAllContent();
Engine.Display.augmentationsContent.style.display = "block";
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* displayAugmentationsContent */ "g"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Augmentations);
document.getElementById("augmentations-menu-link").classList.add("active");
},
loadTutorialContent: function() {
Engine.hideAllContent();
Engine.Display.tutorialContent.style.display = "block";
Engine.displayTutorialContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Tutorial);
document.getElementById("tutorial-menu-link").classList.add("active");
},
loadDevMenuContent: function() {
Engine.hideAllContent();
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_23__[/* createDevMenu */ "b"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].DevMenu);
document.getElementById("dev-menu-link").classList.add("active");
},
loadLocationContent: function() {
Engine.hideAllContent();
Engine.Display.locationContent.style.display = "block";
try {
Object(_Location__WEBPACK_IMPORTED_MODULE_27__[/* displayLocationContent */ "a"])();
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__[/* exceptionAlert */ "a"])(e);
console.error(e);
}
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Location);
},
loadTravelContent: function() {
switch(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].city) {
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Aevum:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].AevumTravelAgency;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Chongqing:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].ChongqingTravelAgency;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Sector12:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Sector12TravelAgency;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].NewTokyo:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].NewTokyoTravelAgency;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Ishima:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].IshimaTravelAgency;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Volhaven:
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].VolhavenTravelAgency;
break;
default:
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("ERROR: Invalid city. This is a bug please contact game dev");
break;
}
Engine.loadLocationContent();
},
loadJobContent: function() {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyName == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("You do not currently have a job! You can visit various companies " +
"in the city and try to find a job.");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyName;
Engine.loadLocationContent();
},
loadWorkInProgressContent: function() {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
//mainMenu.style.visibility = "hidden";
mainMenu.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["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_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["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_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].CinematicText);
},
loadInfiltrationContent: function() {
Engine.hideAllContent();
Engine.Display.infiltrationContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Infiltration);
},
loadStockMarketContent: function() {
Engine.hideAllContent();
Engine.Display.stockMarketContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].StockMarket);
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* displayStockMarketContent */ "g"])();
},
loadGangContent: function() {
Engine.hideAllContent();
if (document.getElementById("gang-container") || _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].gang.displayGangContent(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"]);
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Gang);
} else {
Engine.loadTerminalContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["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_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Mission);
},
loadCorporationContent: function() {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"]) {
Engine.hideAllContent();
document.getElementById("character-overview-wrapper").style.visibility = "hidden";
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.createUI();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Corporation);
}
},
loadBladeburnerContent: function() {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Bladeburner);
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner.createContent();
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__[/* exceptionAlert */ "a"])(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";
Engine.Display.hacknetNodesContent.style.display = "none";
Engine.Display.worldContent.style.display = "none";
Engine.Display.createProgramContent.style.display = "none";
Engine.Display.factionsContent.style.display = "none";
Engine.Display.factionContent.style.display = "none";
Engine.Display.factionAugmentationsContent.style.display = "none";
Engine.Display.augmentationsContent.style.display = "none";
Engine.Display.tutorialContent.style.display = "none";
Engine.Display.locationContent.style.display = "none";
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_36__[/* Player */ "a"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].gang.clearUI();
}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.clearUI();
}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner.clearContent();
}
//Location lists
Engine.aevumLocationsList.style.display = "none";
Engine.chongqingLocationsList.style.display = "none";
Engine.sector12LocationsList.style.display = "none";
Engine.newTokyoLocationsList.style.display = "none";
Engine.ishimaLocationsList.style.display = "none";
Engine.volhavenLocationsList.style.display = "none";
//Make nav menu tabs inactive
document.getElementById("terminal-menu-link").classList.remove("active");
document.getElementById("create-script-menu-link").classList.remove("active");
document.getElementById("active-scripts-menu-link").classList.remove("active");
document.getElementById("create-program-menu-link").classList.remove("active");
document.getElementById("stats-menu-link").classList.remove("active");
document.getElementById("factions-menu-link").classList.remove("active");
document.getElementById("augmentations-menu-link").classList.remove("active");
document.getElementById("hacknet-nodes-menu-link").classList.remove("active");
document.getElementById("city-menu-link").classList.remove("active");
document.getElementById("tutorial-menu-link").classList.remove("active");
document.getElementById("options-menu-link").classList.remove("active");
document.getElementById("dev-menu-link").classList.remove("active");
document.getElementById("bladeburner-menu-link").classList.remove("active");
document.getElementById("corporation-menu-link").classList.remove("active");
document.getElementById("gang-menu-link").classList.remove("active");
// Close dev menu
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_23__[/* closeDevMenu */ "a"])();
},
displayCharacterOverviewInfo: function() {
Engine.overview.update();
const save = document.getElementById("character-overview-save-button");
const flashClass = "flashing-button";
if(!_Settings__WEBPACK_IMPORTED_MODULE_42__["Settings"].AutosaveInterval) {
save.classList.add(flashClass);
} else {
save.classList.remove(flashClass);
}
},
/* Display character info */
displayCharacterInfo: function() {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(Engine.Display.characterInfo);
var companyPosition = "";
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyPosition !== "") {
companyPosition = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyPosition;
}
var intText = "";
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].intelligence > 0) {
intText = 'Intelligence: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].intelligence).toLocaleString() + '<br>';
}
let bitNodeTimeText = "";
if(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].sourceFiles.length > 0) {
bitNodeTimeText = 'Time played since last Bitnode destroyed: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode) + '<br>';
}
Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("pre", {
innerHTML:
'<b>General</b><br><br>' +
'Current City: ' + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].city + '<br><br>' +
'Employer: ' + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyName + '<br>' +
'Job Title: ' + companyPosition + '<br><br>' +
'Money: $' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].money.toNumber(), 2) + '<br><br><br>' +
'<b>Stats</b><br><br>' +
'Hacking Level: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_skill).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_exp, '(0.000a)') + ' experience)<br>' +
'Strength: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].strength).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].strength_exp, '(0.000a)') + ' experience)<br>' +
'Defense: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].defense).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].defense_exp, '(0.000a)') + ' experience)<br>' +
'Dexterity: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].dexterity).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].dexterity_exp, '(0.000a)') + ' experience)<br>' +
'Agility: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].agility).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].agility_exp, '(0.000a)') + ' experience)<br>' +
'Charisma: ' + (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].charisma).toLocaleString() +
' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].charisma_exp, '(0.000a)') + ' experience)<br>' +
intText + '<br><br>' +
'<b>Multipliers</b><br><br>' +
'Hacking Chance multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_chance_mult * 100, 2) + '%<br>' +
'Hacking Speed multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_speed_mult * 100, 2) + '%<br>' +
'Hacking Money multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_money_mult * 100, 2) + '%<br>' +
'Hacking Growth multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_grow_mult * 100, 2) + '%<br><br>' +
'Hacking Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_mult * 100, 2) + '%<br>' +
'Hacking Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacking_exp_mult * 100, 2) + '%<br><br>' +
'Strength Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].strength_mult * 100, 2) + '%<br>' +
'Strength Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].strength_exp_mult * 100, 2) + '%<br><br>' +
'Defense Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].defense_mult * 100, 2) + '%<br>' +
'Defense Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].defense_exp_mult * 100, 2) + '%<br><br>' +
'Dexterity Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].dexterity_mult * 100, 2) + '%<br>' +
'Dexterity Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].dexterity_exp_mult * 100, 2) + '%<br><br>' +
'Agility Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].agility_mult * 100, 2) + '%<br>' +
'Agility Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].agility_exp_mult * 100, 2) + '%<br><br>' +
'Charisma Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].charisma_mult * 100, 2) + '%<br>' +
'Charisma Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].charisma_exp_mult * 100, 2) + '%<br><br>' +
'Hacknet Node production multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknet_node_money_mult * 100, 2) + '%<br>' +
'Hacknet Node purchase cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknet_node_purchase_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node RAM upgrade cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknet_node_ram_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node Core purchase cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknet_node_core_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node level upgrade cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknet_node_level_cost_mult * 100, 2) + '%<br><br>' +
'Company reputation gain multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].company_rep_mult * 100, 2) + '%<br>' +
'Faction reputation gain multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].faction_rep_mult * 100, 2) + '%<br>' +
'Salary multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].work_money_mult * 100, 2) + '%<br>' +
'Crime success multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].crime_success_mult * 100, 2) + '%<br>' +
'Crime money multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].crime_money_mult * 100, 2) + '%<br><br><br>' +
'<b>Misc</b><br><br>' +
'Servers owned: ' + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].purchasedServers.length + '<br>' +
'Hacknet Nodes owned: ' + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hacknetNodes.length + '<br>' +
'Augmentations installed: ' + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].augmentations.length + '<br>' +
'Time played since last Augmentation: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug) + '<br>' +
bitNodeTimeText +
'Time played: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime),
}));
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].sourceFiles.length !== 0) {
var index = "BitNode" + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN;
Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", {
width:"60%",
innerHTML:
"<br>Current BitNode: " + _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN + " (" + _BitNode__WEBPACK_IMPORTED_MODULE_13__[/* BitNodes */ "a"][index].name + ")<br><br>",
}));
Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", {
width:"60%", fontSize: "13px", marginLeft:"4%",
innerHTML:_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* BitNodes */ "a"][index].info,
}))
}
},
/* Display locations in the world*/
aevumLocationsList: null,
chongqingLocationsList: null,
sector12LocationsList: null,
newTokyoLocationsList: null,
ishimaLocationsList: null,
volhavenLocationsList: null,
displayWorldInfo: function() {
Engine.aevumLocationsList.style.display = "none";
Engine.chongqingLocationsList.style.display = "none";
Engine.sector12LocationsList.style.display = "none";
Engine.newTokyoLocationsList.style.display = "none";
Engine.ishimaLocationsList.style.display = "none";
Engine.volhavenLocationsList.style.display = "none";
document.getElementById("world-city-name").innerHTML = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].city;
var cityDesc = document.getElementById("world-city-desc"); //TODO
switch(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].city) {
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Aevum:
Engine.aevumLocationsList.style.display = "inline";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Chongqing:
Engine.chongqingLocationsList.style.display = "inline";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Sector12:
Engine.sector12LocationsList.style.display = "inline";
//City hall only in BitNode-3/with Source-File 3
if ((_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN === 3 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_34__[/* hasCorporationSF */ "e"]) && _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN !== 8) {
document.getElementById("sector12-cityhall-li").style.display = "block";
} else {
document.getElementById("sector12-cityhall-li").style.display = "none";
}
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].NewTokyo:
Engine.newTokyoLocationsList.style.display = "inline";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Ishima:
Engine.ishimaLocationsList.style.display = "inline";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].Volhaven:
Engine.volhavenLocationsList.style.display = "inline";
break;
default:
console.log("Invalid city value in Player object!");
break;
}
//Generic Locations (common to every city):
// World Stock Exchange
// Corporation (if applicable)
// Bladeburner HQ (if applicable);
var genericLocationsList = document.getElementById("generic-locations-list");
genericLocationsList.style.display = "inline";
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(genericLocationsList);
var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li");
li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", {
innerText:"World Stock Exchange", class:"a-link-button",
clickListener:()=>{
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_28__["Locations"].WorldStockExchange;
Engine.loadStockMarketContent();
return false;
}
}));
genericLocationsList.appendChild(li);
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"] && document.getElementById("location-corporation-button") == null) {
var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li");
li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", {
innerText:_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.name, id:"location-corporation-button",
class:"a-link-button",
clickListener:()=>{
Engine.loadCorporationContent();
return false;
}
}));
genericLocationsList.appendChild(li);
}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li");
li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", {
innerText:"Bladeburner Headquarters", class:"a-link-button",
clickListener:()=>{
Engine.loadBladeburnerContent();
return false;
}
}));
genericLocationsList.appendChild(li);
}
},
displayFactionsInfo: function() {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(Engine.Display.factionsContent);
//Factions
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("h1", {
innerText:"Factions"
}));
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", {
innerText:"Lists all factions you have joined"
}));
var factionsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("ul");
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br"));
//Add a button for each faction you are a member of
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factions.length; ++i) {
(function () {
var factionName = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factions[i];
factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", {
class:"a-link-button", innerText:factionName, padding:"4px", margin:"4px",
display:"inline-block",
clickListener:()=>{
Engine.loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_25__[/* displayFactionContent */ "a"])(factionName);
return false;
}
}));
factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br"));
}()); //Immediate invocation
}
Engine.Display.factionsContent.appendChild(factionsList);
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br"));
//Invited Factions
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("h1", {
innerText:"Outstanding Faction Invitations"
}));
Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["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_5__["createElement"])("ul");
//Add a button to accept for each faction you have invitiations for
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations.length; ++i) {
(function () {
var factionName = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations[i];
var item = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li", {padding:"6px", margin:"6px"});
item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", {
innerText:factionName, display:"inline", margin:"4px", padding:"4px"
}));
item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", {
innerText:"Accept Faction Invitation",
class:"a-link-button", display:"inline", margin:"4px", padding:"4px",
clickListener:()=>{
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_25__[/* joinFaction */ "c"])(_Faction_Factions__WEBPACK_IMPORTED_MODULE_24__["Factions"][factionName]);
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations[i] == factionName || _Faction_Factions__WEBPACK_IMPORTED_MODULE_24__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations[i]].isBanned) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].factionInvitations.splice(i, 1);
i--;
}
}
Engine.displayFactionsInfo();
return false;
}
}));
invitationsList.appendChild(item);
}());
}
Engine.Display.factionsContent.appendChild(invitationsList);
},
displayTutorialContent: function() {
document.getElementById("tutorial-getting-started-link").style.display = "block";
Engine.Clickables.tutorialNetworkingButton.style.display = "block";
Engine.Clickables.tutorialHackingButton.style.display = "block";
Engine.Clickables.tutorialScriptsButton.style.display = "block";
Engine.Clickables.tutorialNetscriptButton.style.display = "block";
Engine.Clickables.tutorialTravelingButton.style.display = "block";
Engine.Clickables.tutorialCompaniesButton.style.display = "block";
Engine.Clickables.tutorialFactionsButton.style.display = "block";
Engine.Clickables.tutorialAugmentationsButton.style.display = "block";
document.getElementById("tutorial-shortcuts-link").style.display = "block";
Engine.Clickables.tutorialBackButton.style.display = "none";
document.getElementById("tutorial-text").style.display = "none";
},
//Displays the text when a section of the Tutorial is opened
displayTutorialPage: function(text) {
document.getElementById("tutorial-getting-started-link").style.display = "none";
Engine.Clickables.tutorialNetworkingButton.style.display = "none";
Engine.Clickables.tutorialHackingButton.style.display = "none";
Engine.Clickables.tutorialScriptsButton.style.display = "none";
Engine.Clickables.tutorialNetscriptButton.style.display = "none";
Engine.Clickables.tutorialTravelingButton.style.display = "none";
Engine.Clickables.tutorialCompaniesButton.style.display = "none";
Engine.Clickables.tutorialFactionsButton.style.display = "none";
Engine.Clickables.tutorialAugmentationsButton.style.display = "none";
document.getElementById("tutorial-shortcuts-link").style.display = "none";
Engine.Clickables.tutorialBackButton.style.display = "inline-block";
document.getElementById("tutorial-text").style.display = "block";
document.getElementById("tutorial-text").innerHTML = text;
},
/* Main Event 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_36__[/* Player */ "a"].lastUpdate = _thisUpdate - offset;
Engine.updateGame(diff);
}
window.requestAnimationFrame(Engine.idleTimer);
},
updateGame: function(numCycles = 1) {
var time = numCycles * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode = 0;}
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode += time;
//Start Manual hack
if (_Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].actionStarted === true) {
Engine._totalActionTime = _Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].actionTime;
Engine._actionTimeLeft = _Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].actionTime;
Engine._actionInProgress = true;
Engine._actionProgressBarCount = 1;
Engine._actionProgressStr = "[ ]";
Engine._actionTimeStr = "Time left: ";
_Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].actionStarted = false;
}
//Working
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].isWorking) {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workForFaction(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].createProgramWork(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].takeClass(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].commitCrime(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workPartTime(numCycles);
} else {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].work(numCycles);
}
}
// Update stock prices
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* processStockPrices */ "m"])(numCycles);
}
//Gang, if applicable
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].gang.process(numCycles, _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"]);
}
//Mission
if (_Missions__WEBPACK_IMPORTED_MODULE_33__[/* inMission */ "c"] && _Missions__WEBPACK_IMPORTED_MODULE_33__[/* currMission */ "b"]) {
_Missions__WEBPACK_IMPORTED_MODULE_33__[/* currMission */ "b"].process(numCycles);
}
//Corporation
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"]) {
//Stores cycles in a "buffer". Processed separately using Engine Counters
//This is to avoid constant DOM redraws when Corporation is catching up
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.storeCycles(numCycles);
}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner.storeCycles(numCycles);
}
//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_35__[/* updateOnlineScriptTimes */ "g"])(numCycles);
//Hacknet Nodes
Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_29__[/* processAllHacknetNodeEarnings */ "d"])(numCycles);
},
//Counters for the main event loop. Represent the number of game cycles are required
//for something to happen.
Counters: {
autoSaveCounter: 300, //Autosave every minute
updateSkillLevelsCounter: 10, //Only update skill levels every 2 seconds. Might improve performance
updateDisplays: 3,
updateDisplaysMed: 9,
updateDisplaysLong: 15,
updateActiveScriptsDisplay: 5,
createProgramNotifications: 10, //Checks whether any programs can be created and notifies
checkFactionInvitations: 100, //Check whether you qualify for any faction invitations
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 and if they are, executes whatever
//is necessary and then resets the counter
checkCounters: function() {
if (Engine.Counters.autoSaveCounter <= 0) {
_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* saveObject */ "b"].saveGame(indexedDb);
if (_Settings__WEBPACK_IMPORTED_MODULE_42__["Settings"].AutosaveInterval == null) {
_Settings__WEBPACK_IMPORTED_MODULE_42__["Settings"].AutosaveInterval = 60;
}
if (_Settings__WEBPACK_IMPORTED_MODULE_42__["Settings"].AutosaveInterval === 0) {
Engine.Counters.autoSaveCounter = Infinity;
} else {
Engine.Counters.autoSaveCounter = _Settings__WEBPACK_IMPORTED_MODULE_42__["Settings"].AutosaveInterval * 5;
}
}
if (Engine.Counters.updateSkillLevelsCounter <= 0) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].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_11__[/* updateActiveScriptsItems */ "c"])();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].ActiveScripts)) {
Engine.Counters.updateActiveScriptsDisplay = 5;
} else {
Engine.Counters.updateActiveScriptsDisplay = 10;
}
}
if (Engine.Counters.updateDisplays <= 0) {
Engine.displayCharacterOverviewInfo();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].CharacterInfo)) {
Engine.displayCharacterInfo();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].HacknetNodes)) {
Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_29__[/* updateHacknetNodesContent */ "f"])();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].CreateProgram)) {
Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_22__[/* displayCreateProgramContent */ "b"])();
}
if (_utils_LogBox__WEBPACK_IMPORTED_MODULE_10__[/* logBoxOpened */ "b"]) {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_10__[/* logBoxUpdateText */ "c"])();
}
Engine.Counters.updateDisplays = 3;
}
if (Engine.Counters.updateDisplaysMed <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Corporation)) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.updateUIContent();
}
Engine.Counters.updateDisplaysMed = 9;
}
if (Engine.Counters.updateDisplaysLong <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].Gang) && _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].gang.updateGangContent();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["Page"].ScriptEditor)) {
Object(_Script__WEBPACK_IMPORTED_MODULE_40__[/* updateScriptEditorContent */ "h"])();
}
Engine.Counters.updateDisplaysLong = 15;
}
if (Engine.Counters.createProgramNotifications <= 0) {
var num = Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_22__[/* getNumAvailableCreateProgram */ "c"])();
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_36__[/* Player */ "a"].checkForFactionInvitations();
if (invitedFactions.length > 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].firstFacInvRecvd === false) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].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_25__[/* inviteToFaction */ "b"])(randFaction);
}
Engine.Counters.checkFactionInvitations = 100;
}
if (Engine.Counters.passiveFactionGrowth <= 0) {
var adjustedCycles = Math.floor((600 - Engine.Counters.passiveFactionGrowth));
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_25__[/* processPassiveFactionRepGain */ "d"])(adjustedCycles);
Engine.Counters.passiveFactionGrowth = 600;
}
if (Engine.Counters.messages <= 0) {
Object(_Message__WEBPACK_IMPORTED_MODULE_32__[/* checkForMessagesToSend */ "c"])();
if (_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* AugmentationNames */ "b"].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_36__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* stockMarketCycle */ "q"])();
}
Engine.Counters.sCr = 1500;
}
if (Engine.Counters.mechanicProcess <= 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation.process();
}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
try {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner.process();
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__[/* exceptionAlert */ "a"])("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_17__[/* generateRandomContract */ "a"])();
}
Engine.Counters.contractGeneration = 3000;
}
},
/* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */
_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_9__["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, "&nbsp;" );
//Once percent is 100, the hack is completed
if (percent >= 100) {
Engine._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].finishAction();
}
},
//Used when initializing a game
//elems should be an array of all DOM elements under the 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";
}
},
//Used when initializing the game
//elems should be an array of all DOM elements under the 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 FOR INITIALIZATION)
//open is a boolean specifying whether its being opened or closed
//elems is an array of DOM elements for main menu tabs (li)
//links is an array of DOM elements for main menu links (a)
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"
var terminal = document.getElementById("terminal-tab");
var createScript = document.getElementById("create-script-tab");
var activeScripts = document.getElementById("active-scripts-tab");
var createProgram = document.getElementById("create-program-tab");
var stats = document.getElementById("stats-tab");
var factions = document.getElementById("factions-tab");
var augmentations = document.getElementById("augmentations-tab");
var hacknetnodes = document.getElementById("hacknet-nodes-tab");
var city = document.getElementById("city-tab");
var travel = document.getElementById("travel-tab");
var job = document.getElementById("job-tab");
var stockmarket = document.getElementById("stock-market-tab");
var bladeburner = document.getElementById("bladeburner-tab");
var corp = document.getElementById("corporation-tab");
var gang = document.getElementById("gang-tab");
var tutorial = document.getElementById("tutorial-tab");
var options = document.getElementById("options-tab");
var dev = document.getElementById("dev-tab");
//Load game from save or create new game
if (Object(_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* loadGame */ "a"])(saveString)) {
console.log("Loaded game from save");
Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodes */ "c"])();
Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodeMultipliers */ "b"])();
Object(_SourceFile__WEBPACK_IMPORTED_MODULE_44__[/* initSourceFiles */ "d"])();
Engine.setDisplayElements(); //Sets variables for important DOM elements
Engine.init(); //Initialize buttons, work, etc.
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* initAugmentations */ "h"])(); //Also calls Player.reapplyAllAugmentations()
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].reapplyAllSourceFiles();
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* initStockSymbols */ "i"])();
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* initSymbolToStockMap */ "j"])();
}
Object(_Literature__WEBPACK_IMPORTED_MODULE_31__[/* initLiterature */ "a"])();
Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_34__[/* initSingularitySFFlags */ "g"])();
console.log(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].intelligence_exp);
//Calculate the number of cycles have elapsed while offline
Engine._lastUpdate = new Date().getTime();
var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].lastUpdate;
var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed);
/* Process offline progress */
var offlineProductionFromScripts = Object(_Script__WEBPACK_IMPORTED_MODULE_40__[/* loadAllRunningScripts */ "f"])(); //This also takes care of offline production for those scripts
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].isWorking) {
console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds");
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workForFaction(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].createProgramWork(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].takeClass(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].commitCrime(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workPartTime(numCyclesOffline);
} else {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].work(numCyclesOffline);
}
}
//Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_29__[/* processAllHacknetNodeEarnings */ "d"])(numCyclesOffline);
//Passive faction rep gain offline
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_25__[/* processPassiveFactionRepGain */ "d"])(numCyclesOffline);
// Stock Market offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* processStockPrices */ "m"])(numCyclesOffline);
}
//Gang progress for BitNode 2
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN != null && _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bitNodeN === 2 && _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].gang.process(numCyclesOffline, _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"]);
}
//Bladeburner offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner.storeCycles(numCyclesOffline);
}
//Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode = 0;}
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].playtimeSinceLastBitnode += time;
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].lastUpdate = Engine._lastUpdate;
Engine.start(); //Run main game loop and Scripts loop
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__["removeLoadingScreen"])();
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("While you were offline, your scripts generated <span class='money-gold'>$" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(offlineProductionFromScripts, 2) + "</span> and your Hacknet Nodes generated <span class='money-gold'>$" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(offlineProductionFromHacknetNodes, 2) + "</span>");
//Close main menu accordions for loaded game
var visibleMenuTabs = [terminal, createScript, activeScripts, stats,
hacknetnodes, city, tutorial, options, dev];
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].firstFacInvRecvd) {visibleMenuTabs.push(factions);}
else {factions.style.display = "none";}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].firstAugPurchased) {visibleMenuTabs.push(augmentations);}
else {augmentations.style.display = "none";}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyPosition !== "") {visibleMenuTabs.push(job);}
else {job.style.display = "none";}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].firstTimeTraveled) {visibleMenuTabs.push(travel);}
else {travel.style.display = "none";}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].firstProgramAvailable) {visibleMenuTabs.push(createProgram);}
else {createProgram.style.display = "none";}
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hasWseAccount) {visibleMenuTabs.push(stockmarket);}
else {stockmarket.style.display = "none";}
if(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {visibleMenuTabs.push(bladeburner);}
else {bladeburner.style.display = "none";}
if(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"]) {visibleMenuTabs.push(corp);}
else {corp.style.display = "none";}
if(_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].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__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodes */ "c"])();
Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodeMultipliers */ "b"])();
Object(_SourceFile__WEBPACK_IMPORTED_MODULE_44__[/* initSourceFiles */ "d"])();
Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_45__[/* initSpecialServerIps */ "c"])();
Engine.setDisplayElements(); //Sets variables for important DOM elements
Engine.start(); //Run main game loop and Scripts loop
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].init();
Object(_Server__WEBPACK_IMPORTED_MODULE_41__[/* initForeignServers */ "f"])();
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_19__["initCompanies"])();
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_24__["initFactions"])();
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* initAugmentations */ "h"])();
Object(_Message__WEBPACK_IMPORTED_MODULE_32__[/* initMessages */ "d"])();
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_46__[/* initStockSymbols */ "i"])();
Object(_Literature__WEBPACK_IMPORTED_MODULE_31__[/* initLiterature */ "a"])();
Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_34__[/* initSingularitySFFlags */ "g"])();
//Open main menu accordions for new game
//Main menu accordions
var hackingHdr = document.getElementById("hacking-menu-header");
hackingHdr.classList.toggle("opened");
var characterHdr = document.getElementById("character-menu-header");
characterHdr.classList.toggle("opened");
var worldHdr = document.getElementById("world-menu-header");
worldHdr.classList.toggle("opened");
var 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_30__[/* iTutorialStart */ "c"])();
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__["removeLoadingScreen"])();
}
//Initialize labels on game settings
Object(_ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_43__[/* setSettingsLabels */ "a"])();
Object(_Script__WEBPACK_IMPORTED_MODULE_40__[/* scriptEditorInit */ "g"])();
_Terminal__WEBPACK_IMPORTED_MODULE_47__[/* Terminal */ "a"].resetTerminalInput();
},
setDisplayElements: function() {
//Content elements
Engine.Display.terminalContent = document.getElementById("terminal-container");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_49__["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.worldContent = document.getElementById("world-container");
Engine.Display.worldContent.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.factionAugmentationsContent = document.getElementById("faction-augmentations-container");
Engine.Display.factionAugmentationsContent.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 lists
Engine.aevumLocationsList = document.getElementById("aevum-locations-list");
Engine.chongqingLocationsList = document.getElementById("chongqing-locations-list");
Engine.sector12LocationsList = document.getElementById("sector12-locations-list");
Engine.newTokyoLocationsList = document.getElementById("newtokyo-locations-list");
Engine.ishimaLocationsList = document.getElementById("ishima-locations-list");
Engine.volhavenLocationsList = document.getElementById("volhaven-locations-list");
//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.visibility = "hidden";
Engine.Display.locationContent.style.display = "none";
//Work In Progress
Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container");
//Engine.Display.workInProgressContent.style.visibility = "hidden";
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";
//Init Location buttons
Object(_Location__WEBPACK_IMPORTED_MODULE_27__[/* initLocationButtons */ "b"])();
//Tutorial buttons
Engine.Clickables.tutorialNetworkingButton = document.getElementById("tutorial-networking-link");
Engine.Clickables.tutorialNetworkingButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialNetworkingText);
});
Engine.Clickables.tutorialHackingButton = document.getElementById("tutorial-hacking-link");
Engine.Clickables.tutorialHackingButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialHackingText);
});
Engine.Clickables.tutorialScriptsButton = document.getElementById("tutorial-scripts-link");
Engine.Clickables.tutorialScriptsButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialScriptsText);
});
Engine.Clickables.tutorialNetscriptButton = document.getElementById("tutorial-netscript-link");
Engine.Clickables.tutorialNetscriptButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialNetscriptText);
});
Engine.Clickables.tutorialTravelingButton = document.getElementById("tutorial-traveling-link");
Engine.Clickables.tutorialTravelingButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialTravelingText);
});
Engine.Clickables.tutorialCompaniesButton = document.getElementById("tutorial-jobs-link");
Engine.Clickables.tutorialCompaniesButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialCompaniesText);
});
Engine.Clickables.tutorialFactionsButton = document.getElementById("tutorial-factions-link");
Engine.Clickables.tutorialFactionsButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialFactionsText);
});
Engine.Clickables.tutorialAugmentationsButton = document.getElementById("tutorial-augmentations-link");
Engine.Clickables.tutorialAugmentationsButton.addEventListener("click", function() {
Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].TutorialAugmentationsText);
});
Engine.Clickables.tutorialBackButton = document.getElementById("tutorial-back-button");
Engine.Clickables.tutorialBackButton.addEventListener("click", function() {
Engine.displayTutorialContent();
});
},
/* Initialization */
init: function() {
//Import game link
document.getElementById("import-game-link").onclick = function() {
_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* saveObject */ "b"].importGame();
};
//Main menu accordions
var hackingHdr = document.getElementById("hacking-menu-header");
var characterHdr = document.getElementById("character-menu-header");
var worldHdr = document.getElementById("world-menu-header");
var helpHdr = document.getElementById("help-menu-header");
hackingHdr.onclick = function() {
var terminal = document.getElementById("terminal-tab");
var terminalLink = document.getElementById("terminal-menu-link");
var createScript = document.getElementById("create-script-tab");
var createScriptLink = document.getElementById("create-script-menu-link");
var activeScripts = document.getElementById("active-scripts-tab");
var activeScriptsLink = document.getElementById("active-scripts-menu-link");
var createProgram = document.getElementById("create-program-tab");
var createProgramLink = document.getElementById("create-program-menu-link");
var createProgramNot = document.getElementById("create-program-notification");
this.classList.toggle("opened");
if (terminal.style.maxHeight) {
Engine.toggleMainMenuHeader(false,
[terminal, createScript, activeScripts, createProgram],
[terminalLink, createScriptLink, activeScriptsLink, createProgramLink]
);
createProgramNot.style.display = "none";
} else {
Engine.toggleMainMenuHeader(true,
[terminal, createScript, activeScripts, createProgram],
[terminalLink, createScriptLink, activeScriptsLink, createProgramLink]
);
createProgramNot.style.display = "block"
}
}
characterHdr.onclick = function() {
var stats = document.getElementById("stats-tab");
var statsLink = document.getElementById("stats-menu-link");
var factions = document.getElementById("factions-tab");
var factionsLink = document.getElementById("factions-menu-link");
var augmentations = document.getElementById("augmentations-tab");
var augmentationsLink = document.getElementById("augmentations-menu-link");
var hacknetnodes = document.getElementById("hacknet-nodes-tab");
var hacknetnodesLink = document.getElementById("hacknet-nodes-menu-link");
this.classList.toggle("opened");
if (stats.style.maxHeight) {
Engine.toggleMainMenuHeader(false,
[stats, factions, augmentations, hacknetnodes],
[statsLink, factionsLink, augmentationsLink, hacknetnodesLink]
);
} else {
Engine.toggleMainMenuHeader(true,
[stats, factions, augmentations, hacknetnodes],
[statsLink, factionsLink, augmentationsLink, hacknetnodesLink]
);
}
}
worldHdr.onclick = function() {
var city = document.getElementById("city-tab");
var cityLink = document.getElementById("city-menu-link");
var travel = document.getElementById("travel-tab");
var travelLink = document.getElementById("travel-menu-link");
var job = document.getElementById("job-tab");
var jobLink = document.getElementById("job-menu-link");
var stockmarket = document.getElementById("stock-market-tab");
var stockmarketLink = document.getElementById("stock-market-menu-link");
var bladeburner = document.getElementById("bladeburner-tab");
var bladeburnerLink = document.getElementById("bladeburner-menu-link");
var corporation = document.getElementById("corporation-tab");
var corporationLink = document.getElementById("corporation-menu-link");
var gang = document.getElementById("gang-tab");
var gangLink = document.getElementById("gang-menu-link");
// Determine whether certain links should show up
job.style.display = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].companyPosition !== "" ? "list-item" : "none";
stockmarket.style.display = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].hasWseAccount ? "list-item" : "none";
bladeburner.style.display = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"] ? "list-item" : "none";
corporation.style.display = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_20__[/* Corporation */ "a"] ? "list-item" : "none";
gang.style.display = _Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].inGang() ? "list-item" : "none";
this.classList.toggle("opened");
if (city.style.maxHeight) {
Engine.toggleMainMenuHeader(false,
[city, travel, job, stockmarket, bladeburner, corporation, gang],
[cityLink, travelLink, jobLink, stockmarketLink, bladeburnerLink, corporationLink, gangLink]
);
} else {
Engine.toggleMainMenuHeader(true,
[city, travel, job, stockmarket, bladeburner, corporation, gang],
[cityLink, travelLink, jobLink, stockmarketLink, bladeburnerLink, corporationLink, gangLink]
);
}
}
helpHdr.onclick = function() {
var tutorial = document.getElementById("tutorial-tab");
var tutorialLink = document.getElementById("tutorial-menu-link");
var options = document.getElementById("options-tab");
var optionsLink = document.getElementById("options-menu-link");
this.classList.toggle("opened");
const elems = [tutorial, options];
const links = [tutorialLink, optionsLink];
if (true) {
elems.push(document.getElementById("dev-tab"));
links.push(document.getElementById("dev-menu-link"));
}
if (tutorial.style.maxHeight) {
Engine.toggleMainMenuHeader(false, elems, links);
} else {
Engine.toggleMainMenuHeader(true, elems, links);
}
}
//Main menu buttons and content
Engine.Clickables.terminalMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("terminal-menu-link");
Engine.Clickables.terminalMainMenuButton.addEventListener("click", function() {
Engine.loadTerminalContent();
return false;
});
Engine.Clickables.characterMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("stats-menu-link");
Engine.Clickables.characterMainMenuButton.addEventListener("click", function() {
Engine.loadCharacterContent();
return false;
});
Engine.Clickables.scriptEditorMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("create-script-menu-link");
Engine.Clickables.scriptEditorMainMenuButton.addEventListener("click", function() {
Engine.loadScriptEditorContent();
return false;
});
Engine.Clickables.activeScriptsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("active-scripts-menu-link");
Engine.Clickables.activeScriptsMainMenuButton.addEventListener("click", function() {
Engine.loadActiveScriptsContent();
return false;
});
Engine.Clickables.hacknetNodesMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("hacknet-nodes-menu-link");
Engine.Clickables.hacknetNodesMainMenuButton.addEventListener("click", function() {
Engine.loadHacknetNodesContent();
return false;
});
Engine.Clickables.worldMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("city-menu-link");
Engine.Clickables.worldMainMenuButton.addEventListener("click", function() {
Engine.loadWorldContent();
return false;
});
Engine.Clickables.travelMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("travel-menu-link");
Engine.Clickables.travelMainMenuButton.addEventListener("click", function() {
Engine.loadTravelContent();
return false;
});
Engine.Clickables.jobMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("job-menu-link");
Engine.Clickables.jobMainMenuButton.addEventListener("click", function() {
Engine.loadJobContent();
return false;
});
Engine.Clickables.stockmarketMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("stock-market-menu-link");
Engine.Clickables.stockmarketMainMenuButton.addEventListener("click", function() {
Engine.loadStockMarketContent();
return false;
});
Engine.Clickables.createProgramMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("create-program-menu-link");
Engine.Clickables.createProgramMainMenuButton.addEventListener("click", function() {
Engine.loadCreateProgramContent();
return false;
});
Engine.Clickables.factionsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("factions-menu-link");
Engine.Clickables.factionsMainMenuButton.addEventListener("click", function() {
Engine.loadFactionsContent();
return false;
});
Engine.Clickables.augmentationsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("augmentations-menu-link");
Engine.Clickables.augmentationsMainMenuButton.addEventListener("click", function() {
Engine.loadAugmentationsContent();
return false;
});
Engine.Clickables.tutorialMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("tutorial-menu-link");
Engine.Clickables.tutorialMainMenuButton.addEventListener("click", function() {
Engine.loadTutorialContent();
return false;
});
Engine.Clickables.bladeburnerMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("bladeburner-menu-link");
Engine.Clickables.bladeburnerMenuButton.addEventListener("click", function() {
Engine.loadBladeburnerContent();
return false;
});
Engine.Clickables.corporationMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("corporation-menu-link");
Engine.Clickables.corporationMenuButton.addEventListener("click", function() {
Engine.loadCorporationContent();
return false;
});
Engine.Clickables.gangMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("gang-menu-link");
Engine.Clickables.gangMenuButton.addEventListener("click", function() {
Engine.loadGangContent();
return false;
});
Engine.Clickables.devMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("dev-menu-link");
Engine.Clickables.devMainMenuButton.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_39__[/* saveObject */ "b"].saveGame(indexedDb);
return false;
});
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() {
_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* saveObject */ "b"].deleteGame(indexedDb);
return false;
});
document.getElementById("export-game-link").addEventListener("click", function() {
_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* saveObject */ "b"].exportGame();
return false;
});
//Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function() {
_SaveObject__WEBPACK_IMPORTED_MODULE_39__[/* saveObject */ "b"].saveGame(indexedDb);
return false;
});
document.getElementById("character-overview-options-button").addEventListener("click", function() {
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxOpen */ "b"])();
return false;
});
//Create Program buttons
Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_22__[/* initCreateProgramButtons */ "d"])();
//Message at the top of terminal
Object(_Terminal__WEBPACK_IMPORTED_MODULE_47__[/* postNetburnerText */ "b"])();
//Player was working cancel button
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].isWorking) {
var cancelButton = document.getElementById("work-in-progress-cancel-button");
cancelButton.addEventListener("click", function() {
if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeFaction) {
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_24__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].currentWorkFactionName];
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].finishFactionWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].finishCreateProgramWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].finishClass();
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].finishCrime(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_21__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].finishWorkPartTime();
} else {
_Player__WEBPACK_IMPORTED_MODULE_36__[/* Player */ "a"].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");
//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_36__[/* Player */ "a"].getHomeComputer().runningScripts = [];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("Forcefully deleted all running scripts on home computer. Please save and refresh page");
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxClose */ "a"])();
return false;
});
//DEBUG Soft Reset
document.getElementById("debug-soft-reset").addEventListener("click", function() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("Soft Reset!");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_37__[/* prestigeAugmentation */ "a"])();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxClose */ "a"])();
return false;
});
},
start: function() {
//Run main loop
Engine.idleTimer();
//Scripts
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_35__[/* runScriptsLoop */ "f"])();
}
};
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); //Is this right?
}
};
indexedDbRequest.onupgradeneeded = function(e) {
var db = e.target.result;
var objectStore = db.createObjectStore("savestring");
}
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 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; });
/* Pop up Dialog Box */
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";
}
}
});
var dialogBoxOpened = false;
function dialogBoxCreate(txt, preformatted=false) {
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 = "&times;"
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, '<br>');
}
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 */ 62)))
/***/ }),
/* 10 */
/*!***********************************!*\
!*** ./src/BitNodeMultipliers.ts ***!
\***********************************/
/*! no static exports found */
/*! exports used: BitNodeMultipliers */
/***/ (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,
ServerGrowthRate: 1,
ServerMaxMoney: 1,
ServerStartingMoney: 1,
ServerStartingSecurity: 1,
ServerWeakenRate: 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,
CorporationValuation: 1,
BladeburnerRank: 1,
BladeburnerSkillCost: 1,
};
/***/ }),
/* 11 */
/*!***********************!*\
!*** ./src/Server.js ***!
\***********************/
/*! exports provided: initForeignServers, numCycleForGrowth, processSingleServerGrowth, prestigeHomeComputer, prestigeAllServers, loadAllServers, AddToAllServers, GetServerByHostname, getServer, Server, AllServers */
/*! exports used: AddToAllServers, AllServers, GetServerByHostname, Server, getServer, initForeignServers, loadAllServers, numCycleForGrowth, prestigeAllServers, prestigeHomeComputer, processSingleServerGrowth */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return initForeignServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return numCycleForGrowth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return processSingleServerGrowth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return prestigeHomeComputer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return prestigeAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return loadAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AddToAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return GetServerByHostname; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return Server; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AllServers; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CodingContracts */ 40);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./TextFile */ 60);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/IPAddress */ 57);
/* harmony import */ var _data_servers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./data/servers */ 124);
/* harmony import */ var _data_servers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_data_servers__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 84);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__);
function Server(params={ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])(), hostname:""}) {
/* Properties */
//Connection information
this.ip = params.ip ? params.ip : Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])();
var hostname = params.hostname;
var i = 0;
var suffix = "";
while (GetServerByHostname(hostname+suffix) != null) {
//Server already exists
suffix = "-" + i;
++i;
}
this.hostname = hostname + suffix;
this.organizationName = params.organizationName != null ? params.organizationName : "";
this.isConnectedTo = params.isConnectedTo != null ? params.isConnectedTo : false;
//Access information
this.hasAdminRights = params.adminRights != null ? params.adminRights : false;
this.purchasedByPlayer = params.purchasedByPlayer != null ? params.purchasedByPlayer : false;
this.manuallyHacked = false; //Flag that tracks whether or not the server has been hacked at least once
//RAM, CPU speed and Scripts
this.maxRam = params.maxRam != null ? params.maxRam : 0; //GB
this.ramUsed = 0;
this.cpuCores = 1; //Max of 8, affects hacking times and Hacking Mission starting Cores
this.scripts = [];
this.runningScripts = []; //Stores RunningScript objects
this.programs = [];
this.messages = [];
this.textFiles = [];
this.contracts = [];
this.dir = 0; //new Directory(this, null, ""); TODO
/* Hacking information (only valid for "foreign" aka non-purchased servers) */
this.requiredHackingSkill = params.requiredHackingSkill != null ? params.requiredHackingSkill : 1;
this.moneyAvailable = params.moneyAvailable != null ? params.moneyAvailable * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney : 0;
this.moneyMax = 25 * this.moneyAvailable * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney;
//Hack Difficulty is synonymous with server security. Base Difficulty = Starting difficulty
this.hackDifficulty = params.hackDifficulty != null ? params.hackDifficulty * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity : 1;
this.baseDifficulty = this.hackDifficulty;
this.minDifficulty = Math.max(1, Math.round(this.hackDifficulty / 3));
this.serverGrowth = params.serverGrowth != null ? params.serverGrowth : 1; //Integer from 0 to 100. Affects money increase from grow()
//The IP's of all servers reachable from this one (what shows up if you run scan/netstat)
// NOTE: Only contains IP and not the Server objects themselves
this.serversOnNetwork = [];
//Port information, required for porthacking servers to get admin rights
this.numOpenPortsRequired = params.numOpenPortsRequired != null ? params.numOpenPortsRequired : 5;
this.sshPortOpen = false; //Port 22
this.ftpPortOpen = false; //Port 21
this.smtpPortOpen = false; //Port 25
this.httpPortOpen = false; //Port 80
this.sqlPortOpen = false; //Port 1433
this.openPortCount = 0;
};
Server.prototype.setMaxRam = function(ram) {
this.maxRam = ram;
}
//The serverOnNetwork array holds the IP of all the servers. This function
//returns the actual Server objects
Server.prototype.getServerOnNetwork = function(i) {
if (i > this.serversOnNetwork.length) {
console.log("Tried to get server on network that was out of range");
return;
}
return AllServers[this.serversOnNetwork[i]];
}
//Given the name of the script, returns the corresponding
//script object on the server (if it exists)
Server.prototype.getScript = function(scriptName) {
for (var i = 0; i < this.scripts.length; i++) {
if (this.scripts[i].filename == scriptName) {
return this.scripts[i];
}
}
return null;
}
Server.prototype.capDifficulty = function() {
if (this.hackDifficulty < this.minDifficulty) {this.hackDifficulty = this.minDifficulty;}
if (this.hackDifficulty < 1) {this.hackDifficulty = 1;}
//Place some arbitrarily limit that realistically should never happen unless someone is
//screwing around with the game
if (this.hackDifficulty > 1000000) {this.hackDifficulty = 1000000;}
}
//Strengthens a server's security level (difficulty) by the specified amount
Server.prototype.fortify = function(amt) {
this.hackDifficulty += amt;
this.capDifficulty();
}
Server.prototype.weaken = function(amt) {
this.hackDifficulty -= (amt * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerWeakenRate);
this.capDifficulty();
}
// Write to a script file
// Overwrites existing files. Creates new files if the script does not eixst
Server.prototype.writeToScriptFile = function(fn, code) {
var ret = {success: false, overwritten: false};
if (!Object(_Script__WEBPACK_IMPORTED_MODULE_3__[/* isScriptFilename */ "e"])(fn)) { return ret; }
//Check if the script already exists, and overwrite it if it does
for (let i = 0; i < this.scripts.length; ++i) {
if (fn === this.scripts[i].filename) {
let script = this.scripts[i];
script.code = code;
script.updateRamUsage();
script.module = "";
ret.overwritten = true;
ret.success = true;
return ret;
}
}
//Otherwise, create a new script
var newScript = new _Script__WEBPACK_IMPORTED_MODULE_3__[/* Script */ "c"]();
newScript.filename = fn;
newScript.code = code;
newScript.updateRamUsage();
newScript.server = this.ip;
this.scripts.push(newScript);
ret.success = true;
return ret;
}
// Write to a text file
// Overwrites existing files. Creates new files if the text file does not exist
Server.prototype.writeToTextFile = function(fn, txt) {
var ret = {success: false, overwritten: false};
if (!fn.endsWith("txt")) { return ret; }
//Check if the text file already exists, and overwrite if it does
for (let i = 0; i < this.textFiles.length; ++i) {
if (this.textFiles[i].fn === fn) {
ret.overwritten = true;
this.textFiles[i].text = txt;
ret.success = true;
return ret;
}
}
//Otherwise create a new text file
var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_7__["TextFile"](fn, txt);
this.textFiles.push(newFile);
ret.success = true;
return ret;
}
Server.prototype.addContract = function(contract) {
this.contracts.push(contract);
}
Server.prototype.removeContract = function(contract) {
if (contract instanceof _CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContract"]) {
this.contracts = this.contracts.filter((c) => {
return c.fn !== contract.fn;
});
} else {
this.contracts = this.contracts.filter((c) => {
return c.fn !== contract;
});
}
}
Server.prototype.getContract = function(contractName) {
for (const contract of this.contracts) {
if (contract.fn === contractName) {
return contract;
}
}
return null;
}
//Functions for loading and saving a Server
Server.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_toJSON"])("Server", this);
}
Server.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Server, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"].constructors.Server = Server;
function initForeignServers() {
/* 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 Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["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 _data_servers__WEBPACK_IMPORTED_MODULE_10__["serverMetadata"]) {
const serverParams = {
hostname: metadata.hostname,
ip: Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])(),
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(serverParams);
for (const filename of (metadata.literature || [])) {
server.messages.push(filename);
}
if (metadata.specialName !== undefined) {
_SpecialServerIps__WEBPACK_IMPORTED_MODULE_6__[/* SpecialServerIps */ "a"].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], () => _Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].getHomeComputer());
for (let i = 1; i < networkLayers.length; i++) {
linkNetworkLayers(networkLayers[i], () => getRandomArrayItem(networkLayers[i - 1]));
}
}
// 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) {
let ajdGrowthRate = 1 + (_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerBaseGrowthRate - 1) / server.hackDifficulty;
if(ajdGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerMaxGrowthRate) {
ajdGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerMaxGrowthRate;
}
const serverGrowthPercentage = server.serverGrowth / 100;
const cycles = Math.log(growth)/(Math.log(ajdGrowthRate)*_Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].hacking_grow_mult*serverGrowthPercentage);
return cycles;
}
//Applied server growth for a single server. Returns the percentage growth
function processSingleServerGrowth(server, numCycles) {
//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__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerBaseGrowthRate;
var adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty;
if (adjGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerMaxGrowthRate) {adjGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerMaxGrowthRate;}
//Calculate adjusted server growth rate based on parameters
const serverGrowthPercentage = server.serverGrowth / 100;
const numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate;
//Apply serverGrowth for the calculated number of growth cycles
var serverGrowth = Math.pow(adjGrowthRate, numServerGrowthCyclesAdjusted * _Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].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);
usedCycles = Math.max(0, usedCycles);
server.fortify(2 * _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerFortifyAmount * Math.ceil(usedCycles));
}
return server.moneyAvailable / oldMoneyAvailable;
}
function prestigeHomeComputer(homeComp) {
const hasBitflume = homeComp.programs.includes(_CreateProgram__WEBPACK_IMPORTED_MODULE_4__[/* Programs */ "a"].BitFlume.name);
homeComp.programs.length = 0; //Remove programs
homeComp.runningScripts = [];
homeComp.serversOnNetwork = [];
homeComp.isConnectedTo = true;
homeComp.ramUsed = 0;
homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_4__[/* Programs */ "a"].NukeProgram.name);
if (hasBitflume) { homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_4__[/* Programs */ "a"].BitFlume.name); }
//Update RAM usage on all scripts
homeComp.scripts.forEach(function(script) {
script.updateRamUsage();
});
homeComp.messages.length = 0; //Remove .lit and .msg files
homeComp.messages.push("hackers-starting-handbook.lit");
}
//List of all servers that exist in the game, indexed by their ip
let AllServers = {};
function prestigeAllServers() {
for (var member in AllServers) {
delete AllServers[member];
}
AllServers = {};
}
function loadAllServers(saveString) {
AllServers = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"]);
}
function SizeOfAllServers() {
var size = 0, key;
for (key in AllServers) {
if (AllServers.hasOwnProperty(key)) size++;
}
return size;
}
//Add a server onto the map of all servers in the game
function AddToAllServers(server) {
var serverIp = server.ip;
if (Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* ipExists */ "b"])(serverIp)) {
console.log("IP of server that's being added: " + serverIp);
console.log("Hostname of the server thats being added: " + server.hostname);
console.log("The server that already has this IP is: " + AllServers[serverIp].hostname);
throw new Error("Error: Trying to add a server with an existing IP");
return;
}
AllServers[serverIp] = server;
}
//Returns server object with corresponding hostname
// Relatively slow, would rather not use this a lot
function GetServerByHostname(hostname) {
for (var ip in AllServers) {
if (AllServers.hasOwnProperty(ip)) {
if (AllServers[ip].hostname == hostname) {
return AllServers[ip];
}
}
}
return null;
}
//Get server by IP or hostname. Returns null if invalid
function getServer(s) {
if (!Object(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__["isValidIPAddress"])(s)) {
return GetServerByHostname(s);
}
if(AllServers[s] !== undefined) {
return AllServers[s];
}
return null;
}
//Debugging tool
function PrintAllServers() {
for (var ip in AllServers) {
if (AllServers.hasOwnProperty(ip)) {
console.log("Ip: " + ip + ", hostname: " + AllServers[ip].hostname);
}
}
}
// Directory object (folders)
function Directory(server, parent, name) {
this.s = server; //Ref to server
this.p = parent; //Ref to parent directory
this.c = []; //Subdirs
this.n = name;
this.d = parent.d + 1; //We'll only have a maximum depth of 3 or something
this.scrs = []; //Holds references to the scripts in server.scripts
this.pgms = [];
this.msgs = [];
}
Directory.prototype.createSubdir = function(name) {
var subdir = new Directory(this.s, this, name);
}
Directory.prototype.getPath = function(name) {
var res = [];
var i = this;
while (i !== null) {
res.unshift(i.n, "/");
i = i.parent;
}
res.unshift("/");
return res.join("");
}
/***/ }),
/* 12 */
/*!**************************************!*\
!*** ./src/ui/navigationTracking.ts ***!
\**************************************/
/*! no static exports found */
/*! exports used: Page, routing */
/***/ (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";
/**
* View the city the player is currently in.
*/
Page["World"] = "World";
/**
* 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";
/**
* Information about the specific location the player at (job, company, etc.);
*/
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";
})(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 */
/*!******************************!*\
!*** ./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") {
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 (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;
}
/***/ }),
/* 14 */
/*!***************************************!*\
!*** ./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;
/***/ }),
/* 15 */
/*!*********************************!*\
!*** ./src/Faction/Factions.ts ***!
\*********************************/
/*! no static exports found */
/*! exports used: Factions, factionExists, initFactions, loadFactions */
/***/ (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 */ 54);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 104);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 13);
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;
/***/ }),
/* 16 */
/*!************************************************!*\
!*** ./utils/uiHelpers/clearEventListeners.ts ***!
\************************************************/
/*! no static exports found */
/*! exports used: clearEventListeners */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 51);
/**
* 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 {
const elem = getElementById_1.getElementById(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;
/***/ }),
/* 17 */
/*!***************************!*\
!*** ./utils/YesNoBox.js ***!
\***************************/
/*! exports provided: yesNoBoxCreate, yesNoTxtInpBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoTxtInpBoxGetYesButton, yesNoTxtInpBoxGetNoButton, yesNoTxtInpBoxGetInput, yesNoBoxClose, yesNoTxtInpBoxClose, yesNoBoxOpen */
/*! exports used: yesNoBoxClose, yesNoBoxCreate, yesNoBoxGetNoButton, yesNoBoxGetYesButton, yesNoBoxOpen, yesNoTxtInpBoxClose, yesNoTxtInpBoxCreate, yesNoTxtInpBoxGetInput, yesNoTxtInpBoxGetNoButton, yesNoTxtInpBoxGetYesButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return yesNoBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return yesNoTxtInpBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return yesNoBoxGetYesButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return yesNoBoxGetNoButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return yesNoTxtInpBoxGetYesButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return yesNoTxtInpBoxGetNoButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return yesNoTxtInpBoxGetInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return yesNoBoxClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return yesNoTxtInpBoxClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return yesNoBoxOpen; });
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__);
/* Generic Yes-No Pop-up box
* Can be used to create pop-up boxes that require a yes/no response from player
*/
var yesNoBoxOpen = false;
function yesNoBoxClose() {
var container = document.getElementById("yes-no-box-container");
if (container) {
container.style.display = "none";
} else {
console.log("ERROR: Container not found for YesNoBox");
}
yesNoBoxOpen = false;
return false; //So that 'return yesNoBoxClose()' is return false in event listeners
}
function yesNoBoxGetYesButton() {
return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-yes");
}
function yesNoBoxGetNoButton() {
return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-no");
}
function yesNoBoxCreate(txt) {
if (yesNoBoxOpen) {return false;} //Already open
yesNoBoxOpen = true;
var textElement = document.getElementById("yes-no-box-text");
if (textElement) {
textElement.innerHTML = txt;
}
var c = document.getElementById("yes-no-box-container");
if (c) {
c.style.display = "flex";
} else {
console.log("ERROR: Container not found for YesNoBox");
}
return true;
}
/* Generic Yes-No POp-up Box with Text input */
function yesNoTxtInpBoxClose() {
var c = document.getElementById("yes-no-text-input-box-container");
if (c) {
c.style.display = "none";
} else {
console.log("ERROR: Container not found for YesNoTextInputBox");
}
yesNoBoxOpen = false;
document.getElementById("yes-no-text-input-box-input").value = "";
return false;
}
function yesNoTxtInpBoxGetYesButton() {
return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-yes");
}
function yesNoTxtInpBoxGetNoButton() {
return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-no");
}
function yesNoTxtInpBoxGetInput() {
var val = document.getElementById("yes-no-text-input-box-input").value;
val = val.replace(/\s+/g, '');
return val;
}
function yesNoTxtInpBoxCreate(txt) {
yesNoBoxOpen = true;
var txtE = document.getElementById("yes-no-text-input-box-text");
if (txtE) {
txtE.innerHTML = txt;
}
var c = document.getElementById("yes-no-text-input-box-container");
if (c) {
c.style.display = "flex";
} else {
console.log("ERROR: Container not found for YesNoTextInputBox");
}
document.getElementById("yes-no-text-input-box-input").focus();
}
/***/ }),
/* 18 */
/*!**********************************!*\
!*** ./src/Company/Companies.ts ***!
\**********************************/
/*! no static exports found */
/*! exports used: Companies, companyExists, initCompanies, loadCompanies */
/***/ (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 */ 184);
const Company_1 = __webpack_require__(/*! ./Company */ 71);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 13);
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;
/***/ }),
/* 19 */
/*!*************************!*\
!*** ./src/Settings.ts ***!
\*************************/
/*! no static exports found */
/*! exports used: Settings */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const SettingEnums_1 = __webpack_require__(/*! ./SettingEnums */ 69);
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,
EditorKeybinding: "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 */
/*!**********************************************!*\
!*** ./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 */ 51);
const removeElement_1 = __webpack_require__(/*! ./removeElement */ 67);
/**
* 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;
/***/ }),
/* 21 */
/*!******************************!*\
!*** ./src/Augmentations.js ***!
\******************************/
/*! exports provided: AugmentationNames, Augmentations, PlayerOwnedAugmentation, installAugmentations, initAugmentations, applyAugmentation, augmentationExists, Augmentation, displayAugmentationsContent */
/*! exports used: Augmentation, AugmentationNames, Augmentations, PlayerOwnedAugmentation, applyAugmentation, augmentationExists, displayAugmentationsContent, initAugmentations, installAugmentations */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AugmentationNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Augmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return PlayerOwnedAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return installAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return applyAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return augmentationExists; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Augmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return displayAugmentationsContent; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Prestige */ 82);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./SaveObject */ 72);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _SettingEnums__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SettingEnums */ 69);
/* harmony import */ var _SettingEnums__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_SettingEnums__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SourceFile */ 66);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/uiHelpers/createAccordionElement */ 73);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/helpers/clearObject */ 74);
/* 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_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20__);
//Augmentations
function Augmentation(params) {
if (params.name == null || params.info == null || params.moneyCost == null || params.repCost == null) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_14__["dialogBoxCreate"])("ERROR Creating Augmentations. This is a bug please contact game dev");
return;
}
this.name = params.name;
this.info = params.info;
this.owned = false;
this.prereqs = params.prereqs ? params.prereqs : [];
//Price and reputation base requirements (can change based on faction multipliers)
this.baseRepRequirement = params.repCost * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost;
this.baseCost = params.moneyCost * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost;
//Level - Only applicable for some augmentations
// NeuroFlux Governor
this.level = 0;
}
//Takes in an array of faction names and adds this augmentation to all of those factions
Augmentation.prototype.addToFactions = function(factionList) {
for (var i = 0; i < factionList.length; ++i) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][factionList[i]];
if (faction == null) {
throw new Error("In Augmentation.addToFactions(), could not find faction with this name:" + factionList[i]);
continue;
}
faction.augmentations.push(this.name);
}
}
Augmentation.prototype.addToAllFactions = function() {
for (var fac in _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(fac)) {
var facObj = _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][fac];
if (facObj == null) {
console.log("ERROR: Invalid faction object");
continue;
}
facObj.augmentations.push(this.name);
}
}
}
Augmentation.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("Augmentation", this);
}
Augmentation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(Augmentation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.Augmentation = Augmentation;
let Augmentations = {}
function AddToAugmentations(aug) {
var name = aug.name;
Augmentations[name] = aug;
}
let 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",
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",
//Wasteland Augs
//PepBoy: "P.E.P-Boy", Plasma Energy Projection System
//PepBoyForceField Generates plasma force fields
//PepBoyBlasts Generate high density plasma concussive blasts
//PepBoyDataStorage STore more data on pep boy,
}
function initAugmentations() {
for (var name in _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(name)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][name].augmentations = [];
}
}
//Reset Augmentations
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_17__["clearObject"])(Augmentations);
//Combat stat augmentations
var HemoRecirculator = new Augmentation({
name:AugmentationNames.HemoRecirculator, moneyCost: 9e6, repCost:4e3,
info:"A heart implant that greatly increases the body's ability to effectively use and pump " +
"blood.<br><br>" +
"This augmentation increases all of the player's combat stats by 8%."
});
HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]);
if (augmentationExists(AugmentationNames.HemoRecirculator)) {
delete Augmentations[AugmentationNames.HemoRecirculator];
}
AddToAugmentations(HemoRecirculator);
var Targeting1 = new Augmentation({
name:AugmentationNames.Targeting1, moneyCost:3e6, repCost:2e3,
info:"This cranial implant is embedded within the player's inner ear structure and optic nerves. It regulates and enhances the user's " +
"balance and hand-eye coordination. It is also capable of augmenting reality by projecting digital information " +
"directly onto the retina. These enhancements allow the player to better lock-on and keep track of enemies.<br><br>" +
"This augmentation increases the player's dexterity by 10%."
});
Targeting1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.Targeting1)) {
delete Augmentations[AugmentationNames.Targeting1];
}
AddToAugmentations(Targeting1);
var Targeting2 = new Augmentation({
name:AugmentationNames.Targeting2, moneyCost:8.5e6, repCost:3.5e3,
info:"This is an upgrade of the Augmented Targeting I cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.<br><br>" +
"This augmentation increases the player's dexterity by 20%.",
prereqs:[AugmentationNames.Targeting1]
});
Targeting2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.Targeting2)) {
delete Augmentations[AugmentationNames.Targeting2];
}
AddToAugmentations(Targeting2);
var Targeting3 = new Augmentation({
name:AugmentationNames.Targeting3, moneyCost:23e6, repCost:11e3,
info:"This is an upgrade of the Augmented Targeting II cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.<br><br>" +
"This augmentation increases the player's dexterity by 30%.",
prereqs:[AugmentationNames.Targeting2]
});
Targeting3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(AugmentationNames.Targeting3)) {
delete Augmentations[AugmentationNames.Targeting3];
}
AddToAugmentations(Targeting3);
var SyntheticHeart = new Augmentation({
name:AugmentationNames.SyntheticHeart, moneyCost:575e6, repCost:300e3,
info:"This advanced artificial heart, created from plasteel and graphene, is capable of pumping more blood " +
"at much higher efficiencies than a normal human heart.<br><br>" +
"This augmentation increases the player's agility and strength by 50%."
});
SyntheticHeart.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati"]);
if (augmentationExists(AugmentationNames.SyntheticHeart)) {
delete Augmentations[AugmentationNames.SyntheticHeart];
}
AddToAugmentations(SyntheticHeart);
var SynfibrilMuscle = new Augmentation({
name:AugmentationNames.SynfibrilMuscle, repCost:175e3, moneyCost:225e6,
info:"The myofibrils in human muscles are injected with special chemicals that react with the proteins inside " +
"the myofibrils, altering their underlying structure. The end result is muscles that are stronger and more elastic. " +
"Scientists have named these artificially enhanced units 'synfibrils'.<br><br>" +
"This augmentation increases the player's strength and defense by 30%."
});
SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]);
if (augmentationExists(AugmentationNames.SynfibrilMuscle)) {
delete Augmentations[AugmentationNames.SynfibrilMuscle];
}
AddToAugmentations(SynfibrilMuscle)
var CombatRib1 = new Augmentation({
name:AugmentationNames.CombatRib1, repCost:3e3, moneyCost:4750000,
info:"The human body's ribs are replaced with artificial ribs that automatically and continuously release cognitive " +
"and performance-enhancing drugs into the bloodstream, improving the user's abilities in combat.<br><br>" +
"This augmentation increases the player's strength and defense by 10%."
});
CombatRib1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.CombatRib1)) {
delete Augmentations[AugmentationNames.CombatRib1];
}
AddToAugmentations(CombatRib1);
var CombatRib2 = new Augmentation({
name:AugmentationNames.CombatRib2, repCost:7.5e3, moneyCost:13e6,
info:"This is an upgrade to the Combat Rib I augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream.<br><br>" +
"This augmentation increases the player's strength and defense by 14%.",
prereqs:[AugmentationNames.CombatRib1]
});
CombatRib2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.CombatRib2)) {
delete Augmentations[AugmentationNames.CombatRib2];
}
AddToAugmentations(CombatRib2);
var CombatRib3 = new Augmentation({
name:AugmentationNames.CombatRib3, repCost:14e3, moneyCost:24e6,
info:"This is an upgrade to the Combat Rib II augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream<br><br>." +
"This augmentation increases the player's strength and defense by 18%.",
prereqs:[AugmentationNames.CombatRib2]
});
CombatRib3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(AugmentationNames.CombatRib3)) {
delete Augmentations[AugmentationNames.CombatRib3];
}
AddToAugmentations(CombatRib3);
var NanofiberWeave = new Augmentation({
name:AugmentationNames.NanofiberWeave, repCost:15e3, moneyCost:25e6,
info:"Synthetic nanofibers are woven into the skin's extracellular matrix using electrospinning. " +
"This improves the skin's ability to regenerate itself and protect the body from external stresses and forces.<br><br>" +
"This augmentation increases the player's strength and defense by 20%."
});
NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead",
"Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]);
if (augmentationExists(AugmentationNames.NanofiberWeave)) {
delete Augmentations[AugmentationNames.NanofiberWeave];
}
AddToAugmentations(NanofiberWeave);
var SubdermalArmor = new Augmentation({
name:AugmentationNames.SubdermalArmor, repCost:350e3, moneyCost:650e6,
info:"The NEMEAN Subdermal Weave is a thin, light-weight, graphene plating that houses a dilatant fluid. " +
"The material is implanted underneath the skin, and is the most advanced form of defensive enhancement " +
"that has ever been created. The dilatant fluid, despite being thin and light, is extremely effective " +
"at stopping piercing blows and reducing blunt trauma. The properties of graphene allow the plating to " +
"mitigate damage from any fire-related or electrical traumas.<br><br>" +
"This augmentation increases the player's defense by 120%."
});
SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus",
"The Covenant"]);
if (augmentationExists(AugmentationNames.SubdermalArmor)) {
delete Augmentations[AugmentationNames.SubdermalArmor];
}
AddToAugmentations(SubdermalArmor);
var WiredReflexes = new Augmentation({
name:AugmentationNames.WiredReflexes, repCost:500, moneyCost:500e3,
info:"Synthetic nerve-enhancements are injected into all major parts of the somatic nervous system, " +
"supercharging the body's ability to send signals through neurons. This results in increased reflex speed.<br><br>" +
"This augmentation increases the player's agility and dexterity by 5%."
});
WiredReflexes.addToFactions(["Tian Di Hui", "Slum Snakes", "Sector-12", "Volhaven", "Aevum", "Ishima",
"The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(AugmentationNames.WiredReflexes)) {
delete Augmentations[AugmentationNames.WiredReflexes];
}
AddToAugmentations(WiredReflexes);
var GrapheneBoneLacings = new Augmentation({
name:AugmentationNames.GrapheneBoneLacings, repCost:450e3, moneyCost:850e6,
info:"A graphene-based material is grafted and fused into the user's bones, significantly increasing " +
"their density and tensile strength.<br><br>" +
"This augmentation increases the player's strength and defense by 70%."
});
GrapheneBoneLacings.addToFactions(["Fulcrum Secret Technologies", "The Covenant"]);
if (augmentationExists(AugmentationNames.GrapheneBoneLacings)) {
delete Augmentations[AugmentationNames.GrapheneBoneLacings];
}
AddToAugmentations(GrapheneBoneLacings);
var BionicSpine = new Augmentation({
name:AugmentationNames.BionicSpine, repCost:18e3, moneyCost:25e6,
info:"An artificial spine created from plasteel and carbon fibers that completely replaces the organic spine. " +
"Not only is the Bionic Spine physically stronger than a human spine, but it is also capable of digitally " +
"stimulating and regulating the neural signals that are sent and received by the spinal cord. This results in " +
"greatly improved senses and reaction speeds.<br><br>" +
"This augmentation increases all of the player's combat stats by 15%."
});
BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(AugmentationNames.BionicSpine)) {
delete Augmentations[AugmentationNames.BionicSpine];
}
AddToAugmentations(BionicSpine);
var GrapheneBionicSpine = new Augmentation({
name:AugmentationNames.GrapheneBionicSpine, repCost:650e3, moneyCost:1200e6,
info:"An upgrade to the Bionic Spine augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.<br><br>" +
"This augmentation increases all of the player's combat stats by 60%.",
prereqs:[AugmentationNames.BionicSpine]
});
GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]);
if (augmentationExists(AugmentationNames.GrapheneBionicSpine)) {
delete Augmentations[AugmentationNames.GrapheneBionicSpine];
}
AddToAugmentations(GrapheneBionicSpine);
var BionicLegs = new Augmentation({
name:AugmentationNames.BionicLegs, repCost:60e3, moneyCost:75e6,
info:"Cybernetic legs created from plasteel and carbon fibers that completely replace the user's organic legs.<br><br>" +
"This augmentation increases the player's agility by 60%."
});
BionicLegs.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(AugmentationNames.BionicLegs)) {
delete Augmentations[AugmentationNames.BionicLegs];
}
AddToAugmentations(BionicLegs);
var GrapheneBionicLegs = new Augmentation({
name:AugmentationNames.GrapheneBionicLegs, repCost:300e3, moneyCost:900e6,
info:"An upgrade to the Bionic Legs augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.<br><br>" +
"This augmentation increases the player's agility by 150%.",
prereqs:[AugmentationNames.BionicLegs]
});
GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.GrapheneBionicLegs)) {
delete Augmentations[AugmentationNames.GrapheneBionicLegs];
}
AddToAugmentations(GrapheneBionicLegs);
//Labor stat augmentations
var SpeechProcessor = new Augmentation({
name:AugmentationNames.SpeechProcessor, repCost:3e3, moneyCost:10e6,
info:"A cochlear implant with an embedded computer that analyzes incoming speech. " +
"The embedded computer processes characteristics of incoming speech, such as tone " +
"and inflection, to pick up on subtle cues and aid in social interactions.<br><br>" +
"This augmentation increases the player's charisma by 20%."
});
SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Silhouette"]);
if (augmentationExists(AugmentationNames.SpeechProcessor)) {
delete Augmentations[AugmentationNames.SpeechProcessor];
}
AddToAugmentations(SpeechProcessor);
let TITN41Injection = new Augmentation({
name:AugmentationNames.TITN41Injection, repCost:10e3, moneyCost:38e6,
info:"TITN is a series of viruses that targets and alters the sequences of human DNA in genes that " +
"control personality. The TITN-41 strain alters these genes so that the subject becomes more " +
"outgoing and socialable.<br><br>" +
"This augmentation increases the player's charisma and charisma experience gain rate by 15%."
});
TITN41Injection.addToFactions(["Silhouette"]);
if (augmentationExists(AugmentationNames.TITN41Injection)) {
delete Augmentations[AugmentationNames.TITN41Injection];
}
AddToAugmentations(TITN41Injection);
var EnhancedSocialInteractionImplant = new Augmentation({
name:AugmentationNames.EnhancedSocialInteractionImplant, repCost:150e3, moneyCost:275e6,
info:"A cranial implant that greatly assists in the user's ability to analyze social situations " +
"and interactions. The system uses a wide variety of factors such as facial expression, body " +
"language, and the voice's tone/inflection to determine the best course of action during social" +
"situations. The implant also uses deep learning software to continuously learn new behavior" +
"patterns and how to best respond.<br><br>" +
"This augmentation increases the player's charisma and charisma experience gain rate by 60%."
});
EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma"]);
if (augmentationExists(AugmentationNames.EnhancedSocialInteractionImplant)) {
delete Augmentations[AugmentationNames.EnhancedSocialInteractionImplant];
}
AddToAugmentations(EnhancedSocialInteractionImplant);
//Hacking augmentations
var BitWire = new Augmentation({
name:AugmentationNames.BitWire, repCost:1500, moneyCost:2e6,
info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " +
"capabilities.<br><br>" +
"This augmentation increases the player's hacking skill by 5%."
});
BitWire.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(AugmentationNames.BitWire)) {
delete Augmentations[AugmentationNames.BitWire];
}
AddToAugmentations(BitWire);
var ArtificialBioNeuralNetwork = new Augmentation({
name:AugmentationNames.ArtificialBioNeuralNetwork, repCost:110e3, moneyCost:600e6,
info:"A network consisting of millions of nanoprocessors is embedded into the brain. " +
"The network is meant to mimick the way a biological brain solves a problem, which each " +
"nanoprocessor acting similar to the way a neuron would in a neural network. However, these " +
"nanoprocessors are programmed to perform computations much faster than organic neurons, " +
"allowing its user to solve much more complex problems at a much faster rate.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%.<br>" +
"Increases the amount of money the player's gains from hacking by 15%.<br>" +
"Increases the player's hacking skill by 12%."
});
ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.ArtificialBioNeuralNetwork)) {
delete Augmentations[AugmentationNames.ArtificialBioNeuralNetwork];
}
AddToAugmentations(ArtificialBioNeuralNetwork);
var ArtificialSynapticPotentiation = new Augmentation({
name:AugmentationNames.ArtificialSynapticPotentiation, repCost:2500, moneyCost:16e6,
info:"The body is injected with a chemical that artificially induces synaptic potentiation, " +
"otherwise known as the strengthening of synapses. This results in a enhanced cognitive abilities.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2% <br>" +
"Increases the player's hacking chance by 5%.<br>" +
"Increases the player's hacking experience gain rate by 5%."
});
ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]);
if (augmentationExists(AugmentationNames.ArtificialSynapticPotentiation)) {
delete Augmentations[AugmentationNames.ArtificialSynapticPotentiation];
}
AddToAugmentations(ArtificialSynapticPotentiation);
var EnhancedMyelinSheathing = new Augmentation({
name:AugmentationNames.EnhancedMyelinSheathing, repCost:40e3, moneyCost:275e6,
info:"Electrical signals are used to induce a new, artificial form of myelinogensis in the human body. " +
"This process results in the proliferation of new, synthetic myelin sheaths in the nervous " +
"system. These myelin sheaths can propogate neuro-signals much faster than their organic " +
"counterparts, leading to greater processing speeds and better brain function.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%.<br>" +
"Increases the player's hacking skill by 8%.<br>" +
"Increases the player's hacking experience gain rate by 10%."
});
EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]);
if (augmentationExists(AugmentationNames.EnhancedMyelinSheathing)) {
delete Augmentations[AugmentationNames.EnhancedMyelinSheathing];
}
AddToAugmentations(EnhancedMyelinSheathing);
var SynapticEnhancement = new Augmentation({
name:AugmentationNames.SynapticEnhancement, repCost:800, moneyCost:1.5e6,
info:"A small cranial implant that continuously uses weak electric signals to stimulate the brain and " +
"induce stronger synaptic activity. This improves the user's cognitive abilities.<br><br>" +
"This augmentation increases the player's hacking speed by 3%."
});
SynapticEnhancement.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.SynapticEnhancement)) {
delete Augmentations[AugmentationNames.SynapticEnhancement];
}
AddToAugmentations(SynapticEnhancement);
var NeuralRetentionEnhancement = new Augmentation({
name:AugmentationNames.NeuralRetentionEnhancement, repCost:8e3, moneyCost:50e6,
info:"Chemical injections are used to permanently alter and strengthen the brain's neuronal " +
"circuits, strengthening its ability to retain information.<br><br>" +
"This augmentation increases the player's hacking experience gain rate by 25%."
});
NeuralRetentionEnhancement.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.NeuralRetentionEnhancement)) {
delete Augmentations[AugmentationNames.NeuralRetentionEnhancement];
}
AddToAugmentations(NeuralRetentionEnhancement);
var DataJack = new Augmentation({
name:AugmentationNames.DataJack, repCost:45e3, moneyCost:90e6,
info:"A brain implant that provides an interface for direct, wireless communication between a computer's main " +
"memory and the mind. This implant allows the user to not only access a computer's memory, but also alter " +
"and delete it.<br><br>" +
"This augmentation increases the amount of money the player gains from hacking by 25%."
});
DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]);
if (augmentationExists(AugmentationNames.DataJack)) {
delete Augmentations[AugmentationNames.DataJack];
}
AddToAugmentations(DataJack);
var ENM = new Augmentation({
name:AugmentationNames.ENM, repCost:6e3, moneyCost:50e6,
info:"A thin device embedded inside the arm containing a wireless module capable of connecting " +
"to nearby networks. Once connected, the Netburner Module is capable of capturing and " +
"processing all of the traffic on that network. By itself, the Embedded Netburner Module does " +
"not do much, but a variety of very powerful upgrades can be installed that allow you to fully " +
"control the traffic on a network.<br><br>" +
"This augmentation increases the player's hacking skill by 8%."
});
ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(AugmentationNames.ENM)) {
delete Augmentations[AugmentationNames.ENM];
}
AddToAugmentations(ENM);
var ENMCore = new Augmentation({
name:AugmentationNames.ENMCore, repCost:100e3, moneyCost:500e6,
info:"The Core library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgrade allows the Embedded Netburner Module to generate its own data on a network.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%.<br>" +
"Increases the amount of money the player gains from hacking by 10%.<br>" +
"Increases the player's chance of successfully performing a hack by 3%.<br>" +
"Increases the player's hacking experience gain rate by 7%.<br>" +
"Increases the player's hacking skill by 7%.",
prereqs:[AugmentationNames.ENM]
});
ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(AugmentationNames.ENMCore)) {
delete Augmentations[AugmentationNames.ENMCore];
}
AddToAugmentations(ENMCore);
var ENMCoreV2 = new Augmentation({
name:AugmentationNames.ENMCoreV2, repCost:400e3, moneyCost:900e6,
info:"The Core V2 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to control the information on " +
"a network by re-routing traffic, spoofing IP addresses, or altering the data inside network " +
"packets.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 5%.<br>" +
"Increases the amount of money the player gains from hacking by 30%.<br>" +
"Increases the player's chance of successfully performing a hack by 5%.<br>" +
"Increases the player's hacking experience gain rate by 15%.<br>" +
"Increases the player's hacking skill by 8%.",
prereqs:[AugmentationNames.ENMCore]
});
ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Blade Industries", "OmniTek Incorporated", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.ENMCoreV2)) {
delete Augmentations[AugmentationNames.ENMCoreV2];
}
AddToAugmentations(ENMCoreV2);
var ENMCoreV3 = new Augmentation({
name:AugmentationNames.ENMCoreV3, repCost:700e3, moneyCost:1500e6,
info:"The Core V3 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to seamlessly inject code into " +
"any device on a network.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 5%.<br>" +
"Increases the amount of money the player gains from hacking by 40%.<br>" +
"Increases the player's chance of successfully performing a hack by 10%.<br>" +
"Increases the player's hacking experience gain rate by 25%.<br>" +
"Increases the player's hacking skill by 10%.",
prereqs:[AugmentationNames.ENMCoreV2]
});
ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMCoreV3)) {
delete Augmentations[AugmentationNames.ENMCoreV3];
}
AddToAugmentations(ENMCoreV3);
var ENMAnalyzeEngine = new Augmentation({
name:AugmentationNames.ENMAnalyzeEngine, repCost:250e3, moneyCost:1200e6,
info:"Installs the Analyze Engine for the Embedded Netburner Module, which is a CPU cluster " +
"that vastly outperforms the Netburner Module's native single-core processor.<br><br>" +
"This augmentation increases the player's hacking speed by 10%.",
prereqs:[AugmentationNames.ENM]
});
ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMAnalyzeEngine)) {
delete Augmentations[AugmentationNames.ENMAnalyzeEngine];
}
AddToAugmentations(ENMAnalyzeEngine);
var ENMDMA = new Augmentation({
name:AugmentationNames.ENMDMA, repCost:400e3, moneyCost:1400e6,
info:"This implant installs a Direct Memory Access (DMA) controller into the " +
"Embedded Netburner Module. This allows the Module to send and receive data " +
"directly to and from the main memory of devices on a network.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money the player gains from hacking by 40%.<br>" +
"Increases the player's chance of successfully performing a hack by 20%.",
prereqs:[AugmentationNames.ENM]
});
ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMDMA)) {
delete Augmentations[AugmentationNames.ENMDMA];
}
AddToAugmentations(ENMDMA);
var Neuralstimulator = new Augmentation({
name:AugmentationNames.Neuralstimulator, repCost:20e3, moneyCost:600e6,
info:"A cranial implant that intelligently stimulates certain areas of the brain " +
"in order to improve cognitive functions.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%.<br>" +
"Increases the player's chance of successfully performing a hack by 10%.<br>" +
"Increases the player's hacking experience gain rate by 12%."
});
Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated",
"Four Sigma"]);
if (augmentationExists(AugmentationNames.Neuralstimulator)) {
delete Augmentations[AugmentationNames.Neuralstimulator];
}
AddToAugmentations(Neuralstimulator);
var NeuralAccelerator = new Augmentation({
name:AugmentationNames.NeuralAccelerator, repCost:80e3, moneyCost:350e6,
info:"A microprocessor that accelerates the processing " +
"speed of biological neural networks. This is a cranial implant that is embedded inside the brain.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 10%.<br>" +
"Increases the player's hacking experience gain rate by 15%.<br>" +
"Increases the amount of money the player gains from hacking by 20%."
});
NeuralAccelerator.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.NeuralAccelerator)) {
delete Augmentations[AugmentationNames.NeuralAccelerator];
}
AddToAugmentations(NeuralAccelerator);
var CranialSignalProcessorsG1 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG1, repCost:4e3, moneyCost:14e6,
info:"The first generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 1%.<br>" +
"Increases the player's hacking skill by 5%."
});
CranialSignalProcessorsG1.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG1)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG1];
}
AddToAugmentations(CranialSignalProcessorsG1);
var CranialSignalProcessorsG2 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG2, repCost:7500, moneyCost:25e6,
info:"The second generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%.<br>" +
"Increases the player's chance of successfully performing a hack by 5%.<br>" +
"Increases the player's hacking skill by 7%.",
prereqs:[AugmentationNames.CranialSignalProcessorsG1]
});
CranialSignalProcessorsG2.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG2)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG2];
}
AddToAugmentations(CranialSignalProcessorsG2);
var CranialSignalProcessorsG3 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG3, repCost:20e3, moneyCost:110e6,
info:"The third generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%.<br>" +
"Increases the amount of money the player gains from hacking by 15%.<br>" +
"Increases the player's hacking skill by 9%.",
prereqs:[AugmentationNames.CranialSignalProcessorsG2]
});
CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand", "BitRunners"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG3)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG3];
}
AddToAugmentations(CranialSignalProcessorsG3);
var CranialSignalProcessorsG4 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG4, repCost:50e3, moneyCost:220e6,
info:"The fourth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%.<br>" +
"Increases the amount of money the player gains from hacking by 20%.<br>" +
"Increases the amount of money the player can inject into servers using grow() by 25%.",
prereqs:[AugmentationNames.CranialSignalProcessorsG3]
});
CranialSignalProcessorsG4.addToFactions(["The Black Hand", "BitRunners"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG4)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG4];
}
AddToAugmentations(CranialSignalProcessorsG4);
var CranialSignalProcessorsG5 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG5, repCost:100e3, moneyCost:450e6,
info:"The fifth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 30%.<br>" +
"Increases the amount of money the player gains from hacking by 25%.<br>" +
"Increases the amount of money the player can inject into servers using grow() by 75%.",
prereqs:[AugmentationNames.CranialSignalProcessorsG4]
});
CranialSignalProcessorsG5.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG5)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG5];
}
AddToAugmentations(CranialSignalProcessorsG5);
var NeuronalDensification = new Augmentation({
name:AugmentationNames.NeuronalDensification, repCost:75e3, moneyCost:275e6,
info:"The brain is surgically re-engineered to have increased neuronal density " +
"by decreasing the neuron gap junction. Then, the body is genetically modified " +
"to enhance the production and capabilities of its neural stem cells.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 15%.<br>" +
"Increases the player's hacking experience gain rate by 10%.<br>"+
"Increases the player's hacking speed by 3%."
});
NeuronalDensification.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.NeuronalDensification)) {
delete Augmentations[AugmentationNames.NeuronalDensification];
}
AddToAugmentations(NeuronalDensification);
//Work Augmentations
var NuoptimalInjectorImplant = new Augmentation({
name:AugmentationNames.NuoptimalInjectorImplant, repCost:2e3, moneyCost:4e6,
info:"This torso implant automatically injects nootropic supplements into " +
"the bloodstream to improve memory, increase focus, and provide other " +
"cognitive enhancements.<br><br>" +
"This augmentation increases the amount of reputation the player gains " +
"when working for a company by 20%."
});
NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Ishima",
"Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
if (augmentationExists(AugmentationNames.NuoptimalInjectorImplant)) {
delete Augmentations[AugmentationNames.NuoptimalInjectorImplant];
}
AddToAugmentations(NuoptimalInjectorImplant);
var SpeechEnhancement = new Augmentation({
name:AugmentationNames.SpeechEnhancement, repCost:1e3, moneyCost:2.5e6,
info:"An advanced neural implant that improves your speaking abilities, making " +
"you more convincing and likable in conversations and overall improving your " +
"social interactions.<br><br>" +
"This augmentation:<br>" +
"Increases the player's charisma by 10%.<br>" +
"Increases the amount of reputation the player gains when working for a company by 10%."
});
SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International",
"Clarke Incorporated", "Bachman & Associates"]);
if (augmentationExists(AugmentationNames.SpeechEnhancement)) {
delete Augmentations[AugmentationNames.SpeechEnhancement];
}
AddToAugmentations(SpeechEnhancement);
var FocusWire = new Augmentation({
name:AugmentationNames.FocusWire, repCost:30e3, moneyCost:180e6,
info:"A cranial implant that stops procrastination by blocking specific neural pathways " +
"in the brain.<br><br>" +
"This augmentation:<br>" +
"Increases all experience gains by 5%.<br>" +
"Increases the amount of money the player gains from working by 20%.<br>" +
"Increases the amount of reputation the player gains when working for a company by 10%."
});
FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.FocusWire)) {
delete Augmentations[AugmentationNames.FocusWire];
}
AddToAugmentations(FocusWire)
var PCDNI = new Augmentation({
name:AugmentationNames.PCDNI, repCost:150e3, moneyCost:750e6,
info:"Installs a Direct-Neural Interface jack into your arm that is compatible with most " +
"computers. Connecting to a computer through this jack allows you to interface with " +
"it using the brain's electrochemical signals.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 30%.<br>" +
"Increases the player's hacking skill by 8%."
});
PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]);
if (augmentationExists(AugmentationNames.PCDNI)) {
delete Augmentations[AugmentationNames.PCDNI];
}
AddToAugmentations(PCDNI);
var PCDNIOptimizer = new Augmentation({
name:AugmentationNames.PCDNIOptimizer, repCost:200e3, moneyCost:900e6,
info:"This is a submodule upgrade to the PC Direct-Neural Interface augmentation. It " +
"improves the performance of the interface and gives the user more control options " +
"to the connected computer.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 75%.<br>" +
"Increases the player's hacking skill by 10%.",
prereqs:[AugmentationNames.PCDNI]
});
PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
if (augmentationExists(AugmentationNames.PCDNIOptimizer)) {
delete Augmentations[AugmentationNames.PCDNIOptimizer];
}
AddToAugmentations(PCDNIOptimizer);
var PCDNINeuralNetwork = new Augmentation({
name:AugmentationNames.PCDNINeuralNetwork, repCost:600e3, moneyCost:1500e6,
info:"This is an additional installation that upgrades the functionality of the " +
"PC Direct-Neural Interface augmentation. When connected to a computer, " +
"The NeuroNet Injector upgrade allows the user to use his/her own brain's " +
"processing power to aid the computer in computational tasks.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 100%.<br>" +
"Increases the player's hacking skill by 10%.<br>" +
"Increases the player's hacking speed by 5%.",
prereqs:[AugmentationNames.PCDNI]
});
PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.PCDNINeuralNetwork)) {
delete Augmentations[AugmentationNames.PCDNINeuralNetwork];
}
AddToAugmentations(PCDNINeuralNetwork);
var ADRPheromone1 = new Augmentation({
name:AugmentationNames.ADRPheromone1, repCost:1500, moneyCost:3.5e6,
info:"The body is genetically re-engineered so that it produces the ADR-V1 pheromone, " +
"an artificial pheromone discovered by scientists. The ADR-V1 pheromone, when excreted, " +
"triggers feelings of admiration and approval in other people.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 10% <br>" +
"Increases the amount of reputation the player gains for a faction by 10%."
});
ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]);
if (augmentationExists(AugmentationNames.ADRPheromone1)) {
delete Augmentations[AugmentationNames.ADRPheromone1];
}
AddToAugmentations(ADRPheromone1);
var ADRPheromone2 = new Augmentation({
name:AugmentationNames.ADRPheromone2, repCost:25e3, moneyCost:110e6,
info:"The body is genetically re-engineered so that it produces the ADR-V2 pheromone, " +
"which is similar to but more potent than ADR-V1. This pheromone, when excreted, " +
"triggers feelings of admiration, approval, and respect in others.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains for a faction and company by 20%."
});
ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.ADRPheromone2)) {
delete Augmentations[AugmentationNames.ADRPheromone2];
}
AddToAugmentations(ADRPheromone2);
//HacknetNode Augmentations
var HacknetNodeCPUUpload = new Augmentation({
name:AugmentationNames.HacknetNodeCPUUpload, repCost:1500, moneyCost:2.2e6,
info:"Uploads the architecture and design details of a Hacknet Node's CPU into " +
"the brain. This allows the user to engineer custom hardware and software " +
"for the Hacknet Node that provides better performance.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money produced by Hacknet Nodes by 15%.<br>" +
"Decreases the cost of purchasing a Hacknet Node by 15%."
});
HacknetNodeCPUUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCPUUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeCPUUpload];
}
AddToAugmentations(HacknetNodeCPUUpload);
var HacknetNodeCacheUpload = new Augmentation({
name:AugmentationNames.HacknetNodeCacheUpload, repCost:1e3, moneyCost:1.1e6,
info:"Uploads the architecture and design details of a Hacknet Node's main-memory cache " +
"into the brain. This allows the user to engineer custom cache hardware for the " +
"Hacknet Node that offers better performance.<br><br>" +
"This augmentation:<br> " +
"Increases the amount of money produced by Hacknet Nodes by 10%.<br>" +
"Decreases the cost of leveling up a Hacknet Node by 15%."
});
HacknetNodeCacheUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCacheUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeCacheUpload];
}
AddToAugmentations(HacknetNodeCacheUpload);
var HacknetNodeNICUpload = new Augmentation({
name:AugmentationNames.HacknetNodeNICUpload, repCost:750, moneyCost:900e3,
info:"Uploads the architecture and design details of a Hacknet Node's Network Interface Card (NIC) " +
"into the brain. This allows the user to engineer a custom NIC for the Hacknet Node that " +
"offers better performance.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money produced by Hacknet Nodes by 10%.<br>" +
"Decreases the cost of purchasing a Hacknet Node by 10%."
});
HacknetNodeNICUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeNICUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeNICUpload];
}
AddToAugmentations(HacknetNodeNICUpload);
var HacknetNodeKernelDNI = new Augmentation({
name:AugmentationNames.HacknetNodeKernelDNI, repCost:3e3, moneyCost:8e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting to a " +
"Hacknet Node. This lets the user access and manipulate the Node's kernel using the mind's " +
"electrochemical signals.<br><br>" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 25%."
});
HacknetNodeKernelDNI.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeKernelDNI)) {
delete Augmentations[AugmentationNames.HacknetNodeKernelDNI];
}
AddToAugmentations(HacknetNodeKernelDNI);
var HacknetNodeCoreDNI = new Augmentation({
name:AugmentationNames.HacknetNodeCoreDNI, repCost:5e3, moneyCost:12e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting " +
"to a Hacknet Node. This lets the user access and manipulate the Node's processing logic using " +
"the mind's electrochemical signals.<br><br>" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 45%."
});
HacknetNodeCoreDNI.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCoreDNI)) {
delete Augmentations[AugmentationNames.HacknetNodeCoreDNI];
}
AddToAugmentations(HacknetNodeCoreDNI);
//Misc/Hybrid augmentations
var NeuroFluxGovernor = new Augmentation({
name:AugmentationNames.NeuroFluxGovernor, repCost:500, moneyCost: 750e3,
info:"A device that is embedded in the back of the neck. The NeuroFlux Governor " +
"monitors and regulates nervous impulses coming to and from the spinal column, " +
"essentially 'governing' the body. By doing so, it improves the functionality of the " +
"body's nervous system.<br><br>" +
"This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " +
"increases ALL of the player's multipliers by 1%."
});
// Set the Augmentation's level to the currently-installed level
let currLevel = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name === AugmentationNames.NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].level;
}
}
NeuroFluxGovernor.level = currLevel;
// To set the price/rep req of the NeuroFlux, we have to take into account NeuroFlux
// levels that are purchased but not yet installed
let nextLevel = currLevel;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name === AugmentationNames.NeuroFluxGovernor) {
++nextLevel;
}
}
mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost;
NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost;
if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) {
delete Augmentations[AugmentationNames.NeuroFluxGovernor];
}
NeuroFluxGovernor.addToAllFactions();
AddToAugmentations(NeuroFluxGovernor);
var Neurotrainer1 = new Augmentation({
name:AugmentationNames.Neurotrainer1, repCost:400, moneyCost:800e3,
info:"A decentralized cranial implant that improves the brain's ability to learn. It is " +
"installed by releasing millions of nanobots into the human brain, each of which " +
"attaches to a different neural pathway to enhance the brain's ability to retain " +
"and retrieve information.<br><br>" +
"This augmentation increases the player's experience gain rate for all stats by 10%."
});
Neurotrainer1.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.Neurotrainer1)) {
delete Augmentations[AugmentationNames.Neurotrainer1];
}
AddToAugmentations(Neurotrainer1);
var Neurotrainer2 = new Augmentation({
name:AugmentationNames.Neurotrainer2, repCost:4e3, moneyCost:9e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I augmentation, but it does not " +
"require Neurotrainer I to be installed as a prerequisite.<br><br>" +
"This augmentation increases the player's experience gain rate for all stats by 15%."
});
Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]);
if (augmentationExists(AugmentationNames.Neurotrainer2)) {
delete Augmentations[AugmentationNames.Neurotrainer2];
}
AddToAugmentations(Neurotrainer2);
var Neurotrainer3 = new Augmentation({
name:AugmentationNames.Neurotrainer3, repCost:10e3, moneyCost:26e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I and Neurotrainer II augmentation, " +
"but it does not require either of them to be installed as a prerequisite.<br><br>" +
"This augmentation increases the player's experience gain rate for all stats by 20%."
});
Neurotrainer3.addToFactions(["NWO", "Four Sigma"]);
if (augmentationExists(AugmentationNames.Neurotrainer3)) {
delete Augmentations[AugmentationNames.Neurotrainer3];
}
AddToAugmentations(Neurotrainer3);
var Hypersight = new Augmentation({
name:AugmentationNames.Hypersight, repCost:60e3, moneyCost:550e6,
info:"A bionic eye implant that grants sight capabilities far beyond those of a natural human. " +
"Embedded circuitry within the implant provides the ability to detect heat and movement " +
"through solid objects such as wells, thus providing 'x-ray vision'-like capabilities.<br><br>" +
"This augmentation:<br>" +
"Increases the player's dexterity by 40%.<br>" +
"Increases the player's hacking speed by 3%.<br>" +
"Increases the amount of money the player gains from hacking by 10%."
});
Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.Hypersight)) {
delete Augmentations[AugmentationNames.Hypersight];
}
AddToAugmentations(Hypersight);
var LuminCloaking1 = new Augmentation({
name:AugmentationNames.LuminCloaking1, repCost:600, moneyCost:1e6,
info:"A skin implant that reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, have a negative refractive index. As a result, they bend light " +
"around the skin, making the user much harder to see from the naked eye.<br><br>" +
"This augmentation:<br>" +
"Increases the player's agility by 5% <br>" +
"Increases the amount of money the player gains from crimes by 10%."
});
LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking1)) {
delete Augmentations[AugmentationNames.LuminCloaking1];
}
AddToAugmentations(LuminCloaking1);
var LuminCloaking2 = new Augmentation({
name:AugmentationNames.LuminCloaking2, repCost:2e3, moneyCost:6e6,
info:"This is a more advanced version of the LuminCloaking-V2 augmentation. This skin implant " +
"reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, are capable of not only bending light but also of bending heat, " +
"making the user more resilient as well as stealthy.<br><br>" +
"This augmentation:<br>" +
"Increases the player's agility by 10% <br>" +
"Increases the player's defense by 10% <br>" +
"Increases the amount of money the player gains from crimes by 25%.",
prereqs:[AugmentationNames.LuminCloaking1]
});
LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking2)) {
delete Augmentations[AugmentationNames.LuminCloaking2];
}
AddToAugmentations(LuminCloaking2);
var SmartSonar = new Augmentation({
name:AugmentationNames.SmartSonar, repCost:9e3, moneyCost:15e6,
info:"A cochlear implant that helps the player detect and locate enemies " +
"using sound propagation.<br><br>" +
"This augmentation:<br>" +
"Increases the player's dexterity by 10%.<br>" +
"Increases the player's dexterity experience gain rate by 15%.<br>" +
"Increases the amount of money the player gains from crimes by 25%."
});
SmartSonar.addToFactions(["Slum Snakes"]);
if (augmentationExists(AugmentationNames.SmartSonar)) {
delete Augmentations[AugmentationNames.SmartSonar];
}
AddToAugmentations(SmartSonar);
var PowerRecirculator = new Augmentation({
name:AugmentationNames.PowerRecirculator, repCost:10e3, moneyCost:36e6,
info:"The body's nerves are attached with polypyrrole nanocircuits that " +
"are capable of capturing wasted energy (in the form of heat) " +
"and converting it back into usable power.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's stats by 5%.<br>" +
"Increases the player's experience gain rate for all stats by 10%."
});
PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]);
if (augmentationExists(AugmentationNames.PowerRecirculator)) {
delete Augmentations[AugmentationNames.PowerRecirculator];
}
AddToAugmentations(PowerRecirculator);
//Unique AUGS (Each Faction gets one unique augmentation)
//Factions that already have unique augs up to this point:
// Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies,
// Silhouette
//Illuminati
var QLink = new Augmentation({
name:AugmentationNames.QLink, repCost:750e3, moneyCost:1300e6,
info:"A brain implant that wirelessly connects you to the Illuminati's " +
"quantum supercomputer, allowing you to access and use its incredible " +
"computing power.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 10%.<br>" +
"Increases the player's chance of successfully performing a hack by 30%.<br>" +
"Increases the amount of money the player gains from hacking by 100%."
});
QLink.addToFactions(["Illuminati"]);
if (augmentationExists(AugmentationNames.QLink)) {
delete Augmentations[AugmentationNames.QLink];
}
AddToAugmentations(QLink);
//Daedalus
var RedPill = new Augmentation({
name:AugmentationNames.TheRedPill, repCost:1e6, moneyCost:0,
info:"It's time to leave the cave."
});
RedPill.addToFactions(["Daedalus"]);
if (augmentationExists(AugmentationNames.TheRedPill)) {
delete Augmentations[AugmentationNames.TheRedPill];
}
AddToAugmentations(RedPill);
//Covenant
var SPTN97 = new Augmentation({
name:AugmentationNames.SPTN97, repCost:500e3, moneyCost:975e6,
info:"The SPTN-97 gene is injected into the genome. The SPTN-97 gene is an " +
"artificially-synthesized gene that was developed by DARPA to create " +
"super-soldiers through genetic modification. The gene was outlawed in " +
"2056.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's combat stats by 75%.<br>" +
"Increases the player's hacking skill by 15%."
});
SPTN97.addToFactions(["The Covenant"]);
if (augmentationExists(AugmentationNames.SPTN97)) {
delete Augmentations[AugmentationNames.SPTN97];
}
AddToAugmentations(SPTN97);
//ECorp
var HiveMind = new Augmentation({
name:AugmentationNames.HiveMind, repCost:600e3, moneyCost:1100e6,
info:"A brain implant developed by ECorp. They do not reveal what " +
"exactly the implant does, but they promise that it will greatly " +
"enhance your abilities."
});
HiveMind.addToFactions(["ECorp"]);
if (augmentationExists(AugmentationNames.HiveMind)) {
delete Augmentations[AugmentationNames.HiveMind];
}
AddToAugmentations(HiveMind);
//MegaCorp
var CordiARCReactor = new Augmentation({
name:AugmentationNames.CordiARCReactor, repCost:450e3, moneyCost:1000e6,
info:"The thoracic cavity is equipped with a small chamber designed " +
"to hold and sustain hydrogen plasma. The plasma is used to generate " +
"fusion power through nuclear fusion, providing limitless amount of clean " +
"energy for the body.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's combat stats by 35%.<br>" +
"Increases all of the player's combat stat experience gain rate by 35%."
});
CordiARCReactor.addToFactions(["MegaCorp"]);
if (augmentationExists(AugmentationNames.CordiARCReactor)) {
delete Augmentations[AugmentationNames.CordiARCReactor];
}
AddToAugmentations(CordiARCReactor);
//BachmanAndAssociates
var SmartJaw = new Augmentation({
name:AugmentationNames.SmartJaw, repCost:150e3, moneyCost:550e6,
info:"A bionic jaw that contains advanced hardware and software " +
"capable of psychoanalyzing and profiling the personality of " +
"others using optical imaging software.<br><br>" +
"This augmentation:<br>" +
"Increases the player's charisma by 50%. <br>" +
"Increases the player's charisma experience gain rate by 50%.<br>" +
"Increases the amount of reputation the player gains for a company by 25%.<br>" +
"Increases the amount of reputation the player gains for a faction by 25%."
});
SmartJaw.addToFactions(["Bachman & Associates"]);
if (augmentationExists(AugmentationNames.SmartJaw)) {
delete Augmentations[AugmentationNames.SmartJaw];
}
AddToAugmentations(SmartJaw);
//BladeIndustries
var Neotra = new Augmentation({
name:AugmentationNames.Neotra, repCost:225e3, moneyCost:575e6,
info:"A highly-advanced techno-organic drug that is injected into the skeletal " +
"and integumentary system. The drug permanently modifies the DNA of the " +
"body's skin and bone cells, granting them the ability to repair " +
"and restructure themselves.<br><br>" +
"This augmentation increases the player's strength and defense by 55%."
});
Neotra.addToFactions(["Blade Industries"]);
if (augmentationExists(AugmentationNames.Neotra)) {
delete Augmentations[AugmentationNames.Neotra];
}
AddToAugmentations(Neotra);
//NWO
var Xanipher = new Augmentation({
name:AugmentationNames.Xanipher, repCost:350e3, moneyCost:850e6,
info:"A concoction of advanced nanobots that is orally ingested into the " +
"body. These nanobots induce physiological change and significantly " +
"improve the body's functionining in all aspects.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's stats by 20%.<br>" +
"Increases the player's experience gain rate for all stats by 15%."
});
Xanipher.addToFactions(["NWO"]);
if (augmentationExists(AugmentationNames.Xanipher)) {
delete Augmentations[AugmentationNames.Xanipher];
}
AddToAugmentations(Xanipher);
//ClarkeIncorporated
var nextSENS = new Augmentation({
name:AugmentationNames.nextSENS, repCost:175e3, moneyCost:385e6,
info:"The body is genetically re-engineered to maintain a state " +
"of negligible senescence, preventing the body from " +
"deteriorating with age.<br><br>" +
"This augmentation increases all of the player's stats by 20%."
});
nextSENS.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.nextSENS)) {
delete Augmentations[AugmentationNames.nextSENS];
}
AddToAugmentations(nextSENS);
//OmniTekIncorporated
var OmniTekInfoLoad = new Augmentation({
name:AugmentationNames.OmniTekInfoLoad, repCost:250e3, moneyCost:575e6,
info:"OmniTek's data and information repository is uploaded " +
"into your brain, enhancing your programming and " +
"hacking abilities.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 20%.<br>" +
"Increases the player's hacking experience gain rate by 25%."
});
OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]);
if (augmentationExists(AugmentationNames.OmniTekInfoLoad)) {
delete Augmentations[AugmentationNames.OmniTekInfoLoad];
}
AddToAugmentations(OmniTekInfoLoad);
//FourSigma
//TODO Later when Intelligence is added in . Some aug that greatly increases int
//KuaiGongInternational
var PhotosyntheticCells = new Augmentation({
name:AugmentationNames.PhotosyntheticCells, repCost:225e3, moneyCost:550e6,
info:"Chloroplasts are added to epidermal stem cells and are applied " +
"to the body using a skin graft. The result is photosynthetic " +
"skin cells, allowing users to generate their own energy " +
"and nutrition using solar power.<br><br>" +
"This augmentation increases the player's strength, defense, and agility by 40%."
});
PhotosyntheticCells.addToFactions(["KuaiGong International"]);
if (augmentationExists(AugmentationNames.PhotosyntheticCells)) {
delete Augmentations[AugmentationNames.PhotosyntheticCells];
}
AddToAugmentations(PhotosyntheticCells);
//BitRunners
var Neurolink = new Augmentation({
name:AugmentationNames.Neurolink, repCost:350e3, moneyCost:875e6,
info:"A brain implant that provides a high-bandwidth, direct neural link between your " +
"mind and BitRunners' data servers, which reportedly contain " +
"the largest database of hacking tools and information in the world.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 15%.<br>" +
"Increases the player's hacking experience gain rate by 20%.<br>" +
"Increases the player's chance of successfully performing a hack by 10%.<br>" +
"Increases the player's hacking speed by 5%.<br>" +
"Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset."
});
Neurolink.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.Neurolink)) {
delete Augmentations[AugmentationNames.Neurolink];
}
AddToAugmentations(Neurolink);
//BlackHand
var TheBlackHand = new Augmentation({
name:AugmentationNames.TheBlackHand, repCost:40e3, moneyCost:110e6,
info:"A highly advanced bionic hand. This prosthetic not only " +
"enhances strength and dexterity but it is also embedded " +
"with hardware and firmware that lets the user connect to, access and hack " +
"devices and machines just by touching them.<br><br>" +
"This augmentation:<br>" +
"Increases the player's strength and dexterity by 15%.<br>" +
"Increases the player's hacking skill by 10%.<br>" +
"Increases the player's hacking speed by 2%.<br>" +
"Increases the amount of money the player gains from hacking by 10%."
});
TheBlackHand.addToFactions(["The Black Hand"]);
if (augmentationExists(AugmentationNames.TheBlackHand)) {
delete Augmentations[AugmentationNames.TheBlackHand];
}
AddToAugmentations(TheBlackHand);
//NiteSec
var CRTX42AA = new Augmentation({
name:AugmentationNames.CRTX42AA, repCost:18e3, moneyCost:45e6,
info:"The CRTX42-AA gene is injected into the genome. " +
"The CRTX42-AA is an artificially-synthesized gene that targets the visual and prefrontal " +
"cortex and improves cognitive abilities.<br><br>" +
"This augmentation:<br>" +
"Improves the player's hacking skill by 8%.<br>" +
"Improves the player's hacking experience gain rate by 15%."
});
CRTX42AA.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.CRTX42AA)) {
delete Augmentations[AugmentationNames.CRTX42AA];
}
AddToAugmentations(CRTX42AA);
//Chongqing
var Neuregen = new Augmentation({
name:AugmentationNames.Neuregen, repCost:15e3, moneyCost:75e6,
info:"A drug that genetically modifies the neurons in the brain. " +
"The result is that these neurons never die and continuously " +
"regenerate and strengthen themselves.<br><br>" +
"This augmentation increases the player's hacking experience gain rate by 40%."
});
Neuregen.addToFactions(["Chongqing"]);
if (augmentationExists(AugmentationNames.Neuregen)) {
delete Augmentations[AugmentationNames.Neuregen];
}
AddToAugmentations(Neuregen);
//Sector12
var CashRoot = new Augmentation({
name:AugmentationNames.CashRoot, repCost:5e3, moneyCost:25e6,
info:"A collection of digital assets saved on a small chip. The chip is implanted " +
"into your wrist. A small jack in the chip allows you to connect it to a computer " +
"and upload the assets.<br><br>" +
"This augmentation:<br>" +
"Lets the player start with $1,000,000 after a reset.<br>" +
"Lets the player start with the BruteSSH.exe program after a reset."
});
CashRoot.addToFactions(["Sector-12"]);
if (augmentationExists(AugmentationNames.CashRoot)) {
delete Augmentations[AugmentationNames.CashRoot];
}
AddToAugmentations(CashRoot);
//NewTokyo
var NutriGen = new Augmentation({
name:AugmentationNames.NutriGen, repCost:2500, moneyCost:500e3,
info:"A thermo-powered artificial nutrition generator. Endogenously " +
"synthesizes glucose, amino acids, and vitamins and redistributes them " +
"across the body. The device is powered by the body's naturally wasted " +
"energy in the form of heat.<br><br>" +
"This augmentation:<br>" +
"Increases the player's experience gain rate for all combat stats by 20%."
});
NutriGen.addToFactions(["New Tokyo"]);
if (augmentationExists(AugmentationNames.NutriGen)) {
delete Augmentations[AugmentationNames.NutriGen];
}
AddToAugmentations(NutriGen);
//Aevum
//TODO Later Something that lets you learn advanced math...this increases int
//and profits as a trader/from trading
//Ishima
var INFRARet = new Augmentation({
name:AugmentationNames.INFRARet, repCost:3e3, moneyCost:6e6,
info:"A retina implant consisting of a tiny chip that sits behind the " +
"retina. This implant lets people visually detect infrared radiation.<br><br>" +
"This augmentation:<br>" +
"Increases the player's crime success rate by 25%.<br>" +
"Increases the amount of money the player gains from crimes by 10%.<br>" +
"Increases the player's dexterity by 10%."
});
INFRARet.addToFactions(["Ishima"]);
if (augmentationExists(AugmentationNames.INFRARet)) {
delete Augmentations[AugmentationNames.INFRARet];
}
AddToAugmentations(INFRARet);
//Volhaven
var DermaForce = new Augmentation({
name:AugmentationNames.DermaForce, repCost:6e3, moneyCost:10e6,
info:"A synthetic skin is grafted onto the body. The skin consists of " +
"millions of nanobots capable of projecting high-density muon beams, " +
"creating an energy barrier around the user.<br><br>" +
"This augmentation increases the player's defense by 40%."
});
DermaForce.addToFactions(["Volhaven"]);
if (augmentationExists(AugmentationNames.DermaForce)) {
delete Augmentations[AugmentationNames.DermaForce];
}
AddToAugmentations(DermaForce);
//SpeakersForTheDead
var GrapheneBrachiBlades = new Augmentation({
name:AugmentationNames.GrapheneBrachiBlades, repCost:90e3, moneyCost:500e6,
info:"An upgrade to the BrachiBlades augmentation. It infuses " +
"the retractable blades with an advanced graphene material " +
"to make them much stronger and lighter.<br><br>" +
"This augmentation:<br>" +
"Increases the player's strength and defense by 40%.<br>" +
"Increases the player's crime success rate by 10%.<br>" +
"Increases the amount of money the player gains from crimes by 30%.",
prereqs:[AugmentationNames.BrachiBlades]
});
GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(AugmentationNames.GrapheneBrachiBlades)) {
delete Augmentations[AugmentationNames.GrapheneBrachiBlades];
}
AddToAugmentations(GrapheneBrachiBlades);
//DarkArmy
var GrapheneBionicArms = new Augmentation({
name:AugmentationNames.GrapheneBionicArms, repCost:200e3, moneyCost:750e6,
info:"An upgrade to the Bionic Arms augmentation. It infuses the " +
"prosthetic arms with an advanced graphene material " +
"to make them much stronger and lighter.<br><br>" +
"This augmentation increases the player's strength and dexterity by 85%.",
prereqs:[AugmentationNames.BionicArms]
});
GrapheneBionicArms.addToFactions(["The Dark Army"]);
if (augmentationExists(AugmentationNames.GrapheneBionicArms)) {
delete Augmentations[AugmentationNames.GrapheneBionicArms];
}
AddToAugmentations(GrapheneBionicArms);
//TheSyndicate
var BrachiBlades = new Augmentation({
name:AugmentationNames.BrachiBlades, repCost:5e3, moneyCost:18e6,
info:"A set of retractable plasteel blades are implanted in the arm, underneath the skin.<br><br>" +
"This augmentation:<br>" +
"Increases the player's strength and defense by 15%.<br>" +
"Increases the player's crime success rate by 10%.<br>" +
"Increases the amount of money the player gains from crimes by 15%."
});
BrachiBlades.addToFactions(["The Syndicate"]);
if (augmentationExists(AugmentationNames.BrachiBlades)) {
delete Augmentations[AugmentationNames.BrachiBlades];
}
AddToAugmentations(BrachiBlades);
//Tetrads
var BionicArms = new Augmentation({
name:AugmentationNames.BionicArms, repCost:25e3, moneyCost:55e6,
info:"Cybernetic arms created from plasteel and carbon fibers that completely replace " +
"the user's organic arms.<br><br>" +
"This augmentation increases the user's strength and dexterity by 30%."
});
BionicArms.addToFactions(["Tetrads"]);
if (augmentationExists(AugmentationNames.BionicArms)) {
delete Augmentations[AugmentationNames.BionicArms];
}
AddToAugmentations(BionicArms);
//TianDiHui
var SNA = new Augmentation({
name:AugmentationNames.SNA, repCost:2500, moneyCost:6e6,
info:"A cranial implant that affects the user's personality, making them better " +
"at negotiation in social situations.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money the player earns at a company by 10%.<br>" +
"Increases the amount of reputation the player gains when working for a " +
"company or faction by 15%."
});
SNA.addToFactions(["Tian Di Hui"]);
if (augmentationExists(AugmentationNames.SNA)) {
delete Augmentations[AugmentationNames.SNA];
}
AddToAugmentations(SNA);
//For BitNode-2, add all Augmentations to crime/evil factions.
//Do this before adding special Augmentations that become available in later BitNodes
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bitNodeN === 2) {
console.log("Adding all augmentations to crime factions for Bit node 2");
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Slum Snakes"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Tetrads"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Syndicate"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Dark Army"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Speakers for the Dead"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["NiteSec"].addAllAugmentations(Augmentations);
_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Black Hand"].addAllAugmentations(Augmentations);
}
//Special Bladeburner Augmentations
var BladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["factionExists"])(BladeburnersFactionName)) {
var EsperEyewear = new Augmentation({
name:AugmentationNames.EsperEyewear, repCost:500, moneyCost:33e6,
info:"Ballistic-grade protective and retractable eyewear that was designed specially " +
"for Bladeburner units. This " +
"is implanted by installing a mechanical frame in the skull's orbit. " +
"This frame interfaces with the brain and allows the user to " +
"automatically extrude and extract the eyewear. The eyewear protects " +
"against debris, shrapnel, laser, flash, and gas. It is also " +
"embedded with a data processing chip that can be programmed to display an " +
"AR HUD and assist the user in field missions.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 3%.<br>" +
"Increases the player's dexterity by 5%."
});
EsperEyewear.addToFactions([BladeburnersFactionName]);
resetAugmentation(EsperEyewear);
var EMS4Recombination = new Augmentation({
name:AugmentationNames.EMS4Recombination, repCost: 1e3, moneyCost:55e6,
info:"A DNA recombination of the EMS-4 Gene. This genetic engineering " +
"technique was originally used on Bladeburners during the Synthoid uprising " +
"to induce wakefulness and concentration, suppress fear, reduce empathy, and " +
"improve reflexes and memory-recall among other things.<br><br>" +
"This augmentation:<br>" +
"Increases the player's sucess chance in Bladeburner contracts/operations by 3%.<br>" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 5%.<br>" +
"Increases the player's Bladeburner stamina gain rate by 2%."
});
EMS4Recombination.addToFactions([BladeburnersFactionName]);
resetAugmentation(EMS4Recombination);
var OrionShoulder = new Augmentation({
name:AugmentationNames.OrionShoulder, repCost:2.5e3, moneyCost:110e6,
info:"A bionic shoulder augmentation for the right shoulder. Using cybernetics, " +
"the ORION-MKIV shoulder enhances the strength and dexterity " +
"of the user's right arm. It also provides protection due to its " +
"crystallized graphene plating.<br><br>" +
"This augmentation:<br>" +
"Increases the player's defense by 5%.<br>" +
"Increases the player's strength and dexterity by 5%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 4%."
});
OrionShoulder.addToFactions([BladeburnersFactionName]);
resetAugmentation(OrionShoulder);
var HyperionV1 = new Augmentation({
name:AugmentationNames.HyperionV1, repCost: 5e3, moneyCost:550e6,
info:"A pair of mini plasma cannons embedded into the hands. The Hyperion is capable " +
"of rapidly firing bolts of high-density plasma. The weapon is meant to " +
"be used against augmented enemies as the ionized " +
"nature of the plasma disrupts the electrical systems of Augmentations. However, " +
"it can also be effective against non-augmented enemies due to its high temperature " +
"and concussive force.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 6%."
});
HyperionV1.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV1);
var HyperionV2 = new Augmentation({
name:AugmentationNames.HyperionV2, repCost:10e3, moneyCost:1.1e9,
info:"A pair of mini plasma cannons embedded into the hands. This augmentation " +
"is more advanced and powerful than the original V1 model. This V2 model is " +
"more power-efficiency, more accurate, and can fire plasma bolts at a much " +
"higher velocity than the V1 model.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 8%.",
prereqs:[AugmentationNames.HyperionV1]
});
HyperionV2.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV2);
var GolemSerum = new Augmentation({
name:AugmentationNames.GolemSerum, repCost:12.5e3, moneyCost:2.2e9,
info:"A serum that permanently enhances many aspects of a human's capabilities, " +
"including strength, speed, immune system performance, and mitochondrial efficiency. The " +
"serum was originally developed by the Chinese military in an attempt to " +
"create super soldiers.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's combat stats by 7%.<br>" +
"Increases the player's Bladeburner stamina gain rate by 5%.<br>"
});
GolemSerum.addToFactions([BladeburnersFactionName]);
resetAugmentation(GolemSerum);
var VangelisVirus = new Augmentation({
name:AugmentationNames.VangelisVirus, repCost:7.5e3, moneyCost:550e6,
info:"A synthetic symbiotic virus that is injected into the human brain tissue. The Vangelis virus " +
"heightens the senses and focus of its host, and also enhances its intuition.<br><br>" +
"This augmentation:<br>" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 10%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 4%.<br>" +
"Increases the player's dexterity experience gain rate by 10%."
});
VangelisVirus.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus);
var VangelisVirus3 = new Augmentation({
name:AugmentationNames.VangelisVirus3, repCost:15e3, moneyCost:2.2e9,
info:"An improved version of Vangelis, a synthetic symbiotic virus that is " +
"injected into the human brain tissue. On top of the benefits of the original " +
"virus, this also grants an accelerated healing factor and enhanced " +
"agility/reflexes.<br><br>" +
"This augmentation:<br>" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%.<br>" +
"Increases the player's defense and dexterity experience gain rate by 10%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 5%.",
prereqs:[AugmentationNames.VangelisVirus]
});
VangelisVirus3.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus3);
var INTERLINKED = new Augmentation({
name:AugmentationNames.INTERLINKED, repCost:10e3, moneyCost:1.1e9,
info:"The DNA is genetically modified to enhance the human's body " +
"extracellular matrix (ECM). This improves the ECM's ability to " +
"structurally support the body and grants heightened strength and " +
"durability.<br><br>" +
"This augmentation:<br>" +
"Increases the player's experience gain rate for all combat stats by 5%.<br>" +
"Increases the player's Bladeburner max stamina by 10%."
});
INTERLINKED.addToFactions([BladeburnersFactionName]);
resetAugmentation(INTERLINKED);
var BladeRunner = new Augmentation({
name:AugmentationNames.BladeRunner, repCost:8e3, moneyCost:1.65e9,
info:"A cybernetic foot augmentation that was specially created for Bladeburners " +
"during the Synthoid Uprising. The organic musculature of the human foot " +
"is enhanced with flexible carbon nanotube matrices that are controlled by " +
"intelligent servo-motors.<br><br>" +
"This augmentation:<br>" +
"Increases the player's agility by 5%.<br>" +
"Increases the player's Bladeburner max stamina by 5%.<br>" +
"Increases the player's Bladeburner stamina gain rate by 5%.<br>"
});
BladeRunner.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeRunner);
var BladeArmor = new Augmentation({
name:AugmentationNames.BladeArmor, repCost:5e3, moneyCost:275e6,
info:"A powered exoskeleton suit (exosuit) designed as armor for Bladeburner units. This " +
"exoskeleton is incredibly adaptable and can protect the wearer from blunt, piercing, " +
"concussive, thermal, chemical, and electric trauma. It also enhances the user's " +
"strength and agility.<br><br>" +
"This augmentation:<br>" +
"Increases all of the player's combat stats by 4%.<br>" +
"Increases the player's Bladeburner stamina gain rate by 2%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 3%.",
});
BladeArmor.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmor);
var BladeArmorPowerCells = new Augmentation({
name:AugmentationNames.BladeArmorPowerCells, repCost:7.5e3, moneyCost:550e6,
info:"Upgrades the BLADE-51b Tesla Armor with Ion Power Cells, which are capable of " +
"more efficiently storing and using power.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 5%.<br>" +
"Increases the player's Bladeburner stamina gain rate by 2%.<br>" +
"Increases the player's Bladeburner max stamina by 5%.",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorPowerCells.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorPowerCells);
var BladeArmorEnergyShielding = new Augmentation({
name:AugmentationNames.BladeArmorEnergyShielding, repCost:8.5e3, moneyCost:1.1e9,
info:"Upgrades the BLADE-51b Tesla Armor with a plasma energy propulsion system " +
"that is capable of projecting an energy shielding force field.<br><br>" +
"This augmentation:<br>" +
"Increases the player's defense by 5%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 6%.",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorEnergyShielding.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorEnergyShielding);
var BladeArmorUnibeam = new Augmentation({
name:AugmentationNames.BladeArmorUnibeam, repCost:12.5e3, moneyCost:3.3e9,
info:"Upgrades the BLADE-51b Tesla Armor with a concentrated deuterium-fluoride laser " +
"weapon. It's precision an accuracy makes it useful for quickly neutralizing " +
"threats while keeping casualties to a minimum.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 8%.",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorUnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorUnibeam);
var BladeArmorOmnibeam = new Augmentation({
name:AugmentationNames.BladeArmorOmnibeam, repCost:25e3, moneyCost:5.5e9,
info:"Upgrades the BLADE-51b Tesla Armor Unibeam augmentation to use " +
"multiple-fiber system. The upgraded weapon uses multiple fiber laser " +
"modules that combine together to form a single, more powerful beam of up to " +
"2000MW.<br><br>" +
"This augmentation:<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 10%.",
prereqs:[AugmentationNames.BladeArmorUnibeam]
});
BladeArmorOmnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorOmnibeam);
var BladeArmorIPU = new Augmentation({
name:AugmentationNames.BladeArmorIPU, repCost: 6e3, moneyCost:220e6,
info:"Upgrades the BLADE-51b Tesla Armor with an AI Information Processing " +
"Unit that was specially designed to analyze Synthoid related data and " +
"information.<br><br>" +
"This augmentation:<br>" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%.<br>" +
"Increases the player's success chance in Bladeburner contracts/operations by 2%.",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorIPU.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorIPU);
var BladesSimulacrum = new Augmentation({
name:AugmentationNames.BladesSimulacrum, repCost:3e3, moneyCost:80e9,
info:"A highly-advanced matter phase-shifter module that is embedded " +
"in the brainstem and cerebellum. This augmentation allows " +
"the user to project and control a holographic simulacrum within an " +
"extremely large radius. These specially-modified holograms were specially " +
"weaponized by Bladeburner units to be used against Synthoids.<br><br>" +
"This augmentation allows you to perform Bladeburner actions and other " +
"actions (such as working, commiting crimes, etc.) at the same time."
});
BladesSimulacrum.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladesSimulacrum);
}
//Update costs based on how many have been purchased
var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultipleAugMultiplier, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length);
for (var name in Augmentations) {
if (Augmentations.hasOwnProperty(name)) {
Augmentations[name].baseCost *= mult;
}
}
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].reapplyAllAugmentations();
}
//Resets an Augmentation during (re-initizliation)
function resetAugmentation(newAugObject) {
if (!(newAugObject instanceof Augmentation)) {
throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation");
}
var name = newAugObject.name;
if (augmentationExists(name)) {
delete Augmentations[name];
}
AddToAugmentations(newAugObject);
}
function applyAugmentation(aug, reapply=false) {
Augmentations[aug.name].owned = true;
switch(aug.name) {
//Combat stat augmentations
case AugmentationNames.Targeting1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.10;
break;
case AugmentationNames.Targeting2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.20;
break;
case AugmentationNames.Targeting3:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.30;
break;
case AugmentationNames.SyntheticHeart: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.5;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.5;
break;
case AugmentationNames.SynfibrilMuscle: //Medium-high level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.3;
break;
case AugmentationNames.CombatRib1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.1;
break;
case AugmentationNames.CombatRib2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.14;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.14;
break;
case AugmentationNames.CombatRib3:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.18;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.18;
break;
case AugmentationNames.NanofiberWeave: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2;
break;
case AugmentationNames.SubdermalArmor: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 2.2;
break;
case AugmentationNames.WiredReflexes: //Low level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05;
break;
case AugmentationNames.GrapheneBoneLacings: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.7;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.7;
break;
case AugmentationNames.BionicSpine: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.15;
break;
case AugmentationNames.GrapheneBionicSpine: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.6;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.6;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.6;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.6;
break;
case AugmentationNames.BionicLegs: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.6;
break;
case AugmentationNames.GrapheneBionicLegs: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 2.5;
break;
//Labor stats augmentations
case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.6;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.6;
break;
case AugmentationNames.TITN41Injection:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.SpeechProcessor: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2;
break;
//Hacking augmentations
case AugmentationNames.BitWire:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05;
break;
case AugmentationNames.ArtificialBioNeuralNetwork: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.12;
break;
case AugmentationNames.ArtificialSynapticPotentiation: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.05;
break;
case AugmentationNames.EnhancedMyelinSheathing: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08;
break;
case AugmentationNames.SynapticEnhancement: //Low Level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
break;
case AugmentationNames.NeuralRetentionEnhancement: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.DataJack: //Med low level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.25;
break;
case AugmentationNames.ENM: //Medium level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCore: //Medium level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.07;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.07;
break;
case AugmentationNames.ENMCoreV2: //Medium high level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCoreV3: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1;
break;
case AugmentationNames.ENMAnalyzeEngine: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.1;
break;
case AugmentationNames.ENMDMA: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.2;
break;
case AugmentationNames.Neuralstimulator: //Medium Level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.12;
break;
case AugmentationNames.NeuralAccelerator:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.2;
break;
case AugmentationNames.CranialSignalProcessorsG1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05;
break;
case AugmentationNames.CranialSignalProcessorsG2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.07;
break;
case AugmentationNames.CranialSignalProcessorsG3:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.09;
break;
case AugmentationNames.CranialSignalProcessorsG4:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.25;
break;
case AugmentationNames.CranialSignalProcessorsG5:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.25;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.75;
break;
case AugmentationNames.NeuronalDensification:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
break;
//Work augmentations
case AugmentationNames.NuoptimalInjectorImplant: //Low medium level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.2;
break;
case AugmentationNames.SpeechEnhancement: //Low level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.1;
break;
case AugmentationNames.FocusWire: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.2;
break;
case AugmentationNames.PCDNI: //Med level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08;
break;
case AugmentationNames.PCDNIOptimizer: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.75;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1;
break;
case AugmentationNames.PCDNINeuralNetwork: //High level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.ADRPheromone1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.1;
break;
case AugmentationNames.ADRPheromone2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.2;
break;
//Hacknet Node Augmentations
case AugmentationNames.HacknetNodeCPUUpload:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeCacheUpload:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.10;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_level_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeNICUpload:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.9;
break;
case AugmentationNames.HacknetNodeKernelDNI:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.25;
break;
case AugmentationNames.HacknetNodeCoreDNI:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.45;
break;
//Misc augmentations
case AugmentationNames.NeuroFluxGovernor:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.01;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.99;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_ram_cost_mult *= 0.99;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_core_cost_mult *= 0.99;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_level_cost_mult *= 0.99;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.01;
if (!reapply) {
Augmentations[aug.name].level = aug.level;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].level = aug.level;
break;
}
}
}
break;
case AugmentationNames.Neurotrainer1: //Low Level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.1;
break;
case AugmentationNames.Neurotrainer2: //Medium level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.Neurotrainer3: //High Level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.2;
break;
case AugmentationNames.Hypersight: //Medium high level
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.25;
break;
case AugmentationNames.HemoRecirculator:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.08;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.08;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.08;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.08;
break;
case AugmentationNames.SmartSonar:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.25;
break;
case AugmentationNames.PowerRecirculator:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.1;
break;
//Unique augmentations (for factions)
case AugmentationNames.QLink:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 2;
break;
case AugmentationNames.TheRedPill:
break;
case AugmentationNames.SPTN97:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.75;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.75;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.75;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.75;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15;
break;
case AugmentationNames.HiveMind:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 3;
break;
case AugmentationNames.CordiARCReactor:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.35;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.35;
break;
case AugmentationNames.SmartJaw:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.5;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.5;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.25;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.25;
break;
case AugmentationNames.Neotra:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.55;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.55;
break;
case AugmentationNames.Xanipher:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.nextSENS:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2;
break;
case AugmentationNames.OmniTekInfoLoad:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.PhotosyntheticCells:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.4;
break;
case AugmentationNames.Neurolink:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.TheBlackHand:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1;
break;
case AugmentationNames.CRTX42AA:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15;
break;
case AugmentationNames.Neuregen:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.4;
break;
case AugmentationNames.CashRoot:
break;
case AugmentationNames.NutriGen:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.2;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.2;
break;
case AugmentationNames.INFRARet:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.25;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.1;
break;
case AugmentationNames.DermaForce:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4;
break;
case AugmentationNames.GrapheneBrachiBlades:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.3;
break;
case AugmentationNames.GrapheneBionicArms:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.85;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.85;
break;
case AugmentationNames.BrachiBlades:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.15;
break;
case AugmentationNames.BionicArms:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.3;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.3;
break;
case AugmentationNames.SNA:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.15;
break;
//Bladeburner augmentations
case AugmentationNames.EsperEyewear:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05;
break;
case AugmentationNames.EMS4Recombination:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02;
break;
case AugmentationNames.OrionShoulder:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.04;
break;
case AugmentationNames.HyperionV1:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.06;
break;
case AugmentationNames.HyperionV2:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.08;
break;
case AugmentationNames.GolemSerum:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.07;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.07;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.07;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.07;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.05;
break;
case AugmentationNames.VangelisVirus:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.04;
break;
case AugmentationNames.VangelisVirus3:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.05;
break;
case AugmentationNames.INTERLINKED:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.1;
break;
case AugmentationNames.BladeRunner:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.05;
break;
case AugmentationNames.BladeArmor:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.04;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.04;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.04;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.04;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03;
break;
case AugmentationNames.BladeArmorPowerCells:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.05;
break;
case AugmentationNames.BladeArmorEnergyShielding:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.06;
break;
case AugmentationNames.BladeArmorUnibeam:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.08;
break;
case AugmentationNames.BladeArmorOmnibeam:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.1;
break;
case AugmentationNames.BladeArmorIPU:
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.15;
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.02;
break;
case AugmentationNames.BladesSimulacrum: //No multiplier effect
break;
default:
throw new Error("ERROR: No such augmentation!");
return;
}
if (aug.name === AugmentationNames.NeuroFluxGovernor) {
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
//Already have this aug, just upgrade the level
return;
}
}
}
if (!reapply) {
var ownedAug = new PlayerOwnedAugmentation(aug.name);
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.push(ownedAug);
}
}
function PlayerOwnedAugmentation(name) {
this.name = name;
this.level = 1;
}
function installAugmentations(cbScript=null) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length == 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_14__["dialogBoxCreate"])("You have not purchased any Augmentations to install!");
return false;
}
var augmentationList = "";
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) {
var aug = Augmentations[_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name];
if (aug == null) {
console.log("ERROR. Invalid augmentation");
continue;
}
applyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i]);
augmentationList += (aug.name + "<br>");
}
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations = [];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_14__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " +
"to install the following Augmentations:<br>" + augmentationList +
"<br>You wake up in your home...you feel different...");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_7__[/* prestigeAugmentation */ "a"])();
//Run a script after prestiging
if (cbScript && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_19__["isString"])(cbScript)) {
var home = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].getHomeComputer();
for (var i = 0; i < home.scripts.length; ++i) {
if (home.scripts[i].filename === cbScript) {
var script = home.scripts[i];
var ramUsage = script.ramUsage;
var ramAvailable = home.maxRam - home.ramUsed;
if (ramUsage > ramAvailable) {
return; //Not enough RAM
}
var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_9__[/* RunningScript */ "b"](script, []); //No args
runningScriptObj.threads = 1; //Only 1 thread
home.runningScripts.push(runningScriptObj);
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__[/* addWorkerScript */ "c"])(runningScriptObj, home);
}
}
}
}
function augmentationExists(name) {
return Augmentations.hasOwnProperty(name);
}
//Used for testing balance
function giveAllAugmentations() {
for (var name in Augmentations) {
var aug = Augmentations[name];
if (aug == null) {continue;}
var ownedAug = new PlayerOwnedAugmentation(name);
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.push(ownedAug);
}
_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].reapplyAllAugmentations();
}
function displayAugmentationsContent() {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent);
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("h1", {
innerText:"Purchased Augmentations",
}));
//Bladeburner text, once mechanic is unlocked
var bladeburnerText = "\n";
if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bitNodeN === 6 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__[/* hasBladeburnerSF */ "c"]) {
bladeburnerText = "Bladeburner Progress\n\n";
}
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("pre", {
width:"70%", whiteSpace:"pre-wrap", display:"block",
innerText:"Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them.\n" +
"WARNING: Installing your Augmentations resets most of your progress, including:\n\n" +
"Stats/Skill levels and Experience\n" +
"Money\n" +
"Scripts on every computer but your home computer\n" +
"Purchased servers\n" +
"Hacknet Nodes\n" +
"Faction/Company reputation\n" +
"Stocks\n" +
bladeburnerText +
"Installing Augmentations lets you start over with the perks and benefits granted by all " +
"of the Augmentations you have ever installed. Also, you will keep any scripts and RAM/Core upgrades " +
"on your home computer (but you will lose all programs besides NUKE.exe)."
}));
//Install Augmentations button
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", innerText:"Install Augmentations",
tooltip:"'I never asked for this'",
clickListener:()=>{
installAugmentations();
return false;
}
}));
//Backup button
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button flashing-button", innerText:"Backup Save (Export)",
tooltip:"It's always a good idea to backup/export your save!",
clickListener:()=>{
_SaveObject__WEBPACK_IMPORTED_MODULE_8__[/* saveObject */ "b"].exportGame();
return false;
}
}));
//Purchased/queued augmentations list
var queuedAugmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("ul", {class:"augmentations-list"});
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) {
var augName = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name;
var aug = Augmentations[augName];
var displayName = augName;
if (augName === AugmentationNames.NeuroFluxGovernor) {
displayName += " - Level " + (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].level);
}
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
queuedAugmentationsList.appendChild(accordion[0]);
}
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(queuedAugmentationsList);
//Installed augmentations list
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("h1", {
innerText:"Installed Augmentations", marginTop:"8px",
}));
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("p", {
width:"70%", whiteSpace:"pre-wrap",
innerText:"List of all Augmentations (including Source Files) that have been " +
"installed. You have gained the effects of these Augmentations."
}));
var augmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("ul", {class:"augmentations-list"});
//Expand/Collapse All buttons
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Expand All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (!allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Collapse All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
//Sort Buttons
const sortInOrderButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort in Order",
tooltip:"Sorts the Augmentations alphabetically and Source Files in numerical order (1, 2, 3,...)",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20__["removeChildrenFromElement"])(augmentationsList);
//Create a copy of Player's Source Files and augs array and sort them
var sourceFiles = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].sourceFiles.slice();
var augs = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.slice();
sourceFiles.sort((sf1, sf2)=>{
return sf1.n - sf2.n;
});
augs.sort((aug1, aug2)=>{
return aug1.name <= aug2.name ? -1 : 1;
});
displaySourceFiles(augmentationsList, sourceFiles);
displayAugmentations(augmentationsList, augs);
_Settings__WEBPACK_IMPORTED_MODULE_12__["Settings"].OwnedAugmentationsOrder = _SettingEnums__WEBPACK_IMPORTED_MODULE_11__["OwnedAugmentationsOrderSetting"].Alphabetically;
}
});
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(sortInOrderButton);
const sortByAcquirementTimeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort by Acquirement Time",
tooltip:"Sorts the Augmentations and Source Files based on when you acquired them (same as default)",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_20__["removeChildrenFromElement"])(augmentationsList);
displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].sourceFiles);
displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations);
_Settings__WEBPACK_IMPORTED_MODULE_12__["Settings"].OwnedAugmentationsOrder = _SettingEnums__WEBPACK_IMPORTED_MODULE_11__["OwnedAugmentationsOrderSetting"].AcquirementTime;
}
});
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(sortByAcquirementTimeButton);
//Source Files - Temporary...Will probably put in a separate pane Later
if (_Settings__WEBPACK_IMPORTED_MODULE_12__["Settings"].OwnedAugmentationsOrder === _SettingEnums__WEBPACK_IMPORTED_MODULE_11__["OwnedAugmentationsOrderSetting"].Alphabetically) {
sortInOrderButton.click();
} else {
sortByAcquirementTimeButton.click();
}
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(augmentationsList);
}
//Creates the accordion elements to display Augmentations
// @listElement - List DOM element to append accordion elements to
// @augs - Array of Augmentation objects
function displayAugmentations(listElement, augs) {
for (var i = 0; i < augs.length; ++i) {
var augName = augs[i].name;
var aug = Augmentations[augName];
var displayName = augName;
if (augName === AugmentationNames.NeuroFluxGovernor) {
displayName += " - Level " + (augs[i].level);
}
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
listElement.appendChild(accordion[0]);
}
}
//Creates the accordion elements to display Source Files
// @listElement - List DOM element to append accordion elements to
// @sourceFiles - Array of Source File objects
function displaySourceFiles(listElement, sourceFiles) {
for (var i = 0; i < sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + sourceFiles[i].n;
var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_13__[/* SourceFiles */ "b"][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + sourceFiles[i].n);
continue;
}
const maxLevel = sourceFiles[i].n == 12 ? "∞" : "3";
var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_15__["createAccordionElement"])({
hdrText:sourceFileObject.name + "<br>" + "Level " + (sourceFiles[i].lvl) + " / "+maxLevel,
panelText:sourceFileObject.info
});
listElement.appendChild(accordion[0]);
}
}
/***/ }),
/* 22 */
/*!****************************!*\
!*** ./src/StockMarket.js ***!
\****************************/
/*! exports provided: StockMarket, StockSymbols, SymbolToStockMap, initStockSymbols, initStockMarket, initSymbolToStockMap, stockMarketCycle, buyStock, sellStock, shortStock, sellShort, processStockPrices, displayStockMarketContent, updateStockTicker, updateStockPlayerPosition, loadStockMarket, setStockMarketContentCreated, placeOrder, cancelOrder, Order, OrderTypes, PositionTypes */
/*! exports used: OrderTypes, PositionTypes, StockMarket, StockSymbols, SymbolToStockMap, cancelOrder, displayStockMarketContent, initStockMarket, initStockSymbols, initSymbolToStockMap, loadStockMarket, placeOrder, processStockPrices, sellShort, setStockMarketContentCreated, shortStock, stockMarketCycle, updateStockPlayerPosition */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return StockSymbols; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return SymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return initStockSymbols; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return initSymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return stockMarketCycle; });
/* unused harmony export buyStock */
/* unused harmony export sellStock */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return shortStock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return sellShort; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return processStockPrices; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return displayStockMarketContent; });
/* unused harmony export updateStockTicker */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return updateStockPlayerPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return loadStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return setStockMarketContentCreated; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return placeOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return cancelOrder; });
/* unused harmony export Order */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OrderTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PositionTypes; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Stock */ 25);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* 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_createElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
var OrderTypes = {
LimitBuy: "Limit Buy Order",
LimitSell: "Limit Sell Order",
StopBuy: "Stop Buy Order",
StopSell: "Stop Sell Order"
}
var PositionTypes = {
Long: "L",
Short: "S"
}
function placeOrder(stock, shares, price, type, position, workerScript=null) {
var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]);
var order = new Order(stock, shares, price, type, position);
if (isNaN(shares) || isNaN(price)) {
if (tixApi) {
workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
}
return false;
}
if (StockMarket["Orders"] == null) {
var orders = {};
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;}
orders[stock.symbol] = [];
}
}
StockMarket["Orders"] = orders;
}
StockMarket["Orders"][stock.symbol].push(order);
//Process to see if it should be executed immediately
processOrders(order.stock, order.type, order.pos);
updateStockOrderList(order.stock);
return true;
}
//Returns true if successfully cancels an order, false otherwise
function cancelOrder(params, workerScript=null) {
var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]);
if (StockMarket["Orders"] == null) {return false;}
if (params.order && params.order instanceof Order) {
var order = params.order;
//An 'Order' object is passed in
var stockOrders = StockMarket["Orders"][order.stock.symbol];
for (var i = 0; i < stockOrders.length; ++i) {
if (order == stockOrders[i]) {
stockOrders.splice(i, 1);
updateStockOrderList(order.stock);
return true;
}
}
return false;
} else if (params.stock && params.shares && params.price && params.type &&
params.pos && params.stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["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_10__[/* numeralWrapper */ "a"].format(params.price, '$0.000a');
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);
updateStockOrderList(order.stock);
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 executeOrder(order) {
var stock = order.stock;
var orderBook = StockMarket["Orders"];
var stockOrders = orderBook[stock.symbol];
var res = true;
console.log("Executing the following order:");
console.log(order);
switch (order.type) {
case OrderTypes.LimitBuy:
case OrderTypes.StopBuy:
if (order.pos === PositionTypes.Long) {
res = buyStock(order.stock, order.shares) && res;
} else if (order.pos === PositionTypes.Short) {
res = shortStock(order.stock, order.shares) && res;
}
break;
case OrderTypes.LimitSell:
case OrderTypes.StopSell:
if (order.pos === PositionTypes.Long) {
res = sellStock(order.stock, order.shares) && res;
} else if (order.pos === PositionTypes.Short) {
res = sellShort(order.stock, order.shares) && res;
}
break;
}
if (res) {
//Remove order from order book
for (var i = 0; i < stockOrders.length; ++i) {
if (order == stockOrders[i]) {
stockOrders.splice(i, 1);
updateStockOrderList(order.stock);
return;
}
}
console.log("ERROR: Could not find the following Order in Order Book: ");
console.log(order);
} else {
console.log("Order failed to execute");
}
}
function Order(stock, shares, price, type, position) {
this.stock = stock;
this.shares = shares;
this.price = price;
this.type = type;
this.pos = position;
}
Order.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Order", this);
}
Order.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Order, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Order = Order;
let StockMarket = {} //Full name to stock object
let StockSymbols = {} //Full name to symbol
let SymbolToStockMap = {}; //Symbol to Stock object
function loadStockMarket(saveString) {
if (saveString === "") {
StockMarket = {};
} else {
StockMarket = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"]);
}
}
function initStockSymbols() {
//Stocks for companies at which you can work
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp] = "ECP";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp] = "MGCP";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries] = "BLD";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated] = "CLRK";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated] = "OMTK";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma] = "FSIG";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational] = "KGI";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies] = "FLCM";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies] = "STM";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm] = "DCOMM";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs] = "HLS";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife] = "VITA";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems] = "ICRS";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy] = "UNV";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp] = "AERO";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems] = "OMN";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical] = "NVMD";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity] = "WDS";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp] = "LXO";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction] = "RHOC";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises] = "APHE";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities] = "SYSC";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek] = "CTK";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies] = "NTLK";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware] = "OMGA";
StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff] = "FNS";
//Stocks for other companies
StockSymbols["Sigma Cosmetics"] = "SGC";
StockSymbols["Joes Guns"] = "JGN";
StockSymbols["Catalyst Ventures"] = "CTYS";
StockSymbols["Microdyne Technologies"] = "MDYN";
StockSymbols["Titan Laboratories"] = "TITN";
}
function initStockMarket() {
for (var stk in StockMarket) {
if (StockMarket.hasOwnProperty(stk)) {
delete StockMarket[stk];
}
}
const randInt = _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"];
var ecorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp;
var ecorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](ecorp, StockSymbols[ecorp], randInt(40, 50) / 100, true, 19, randInt(17e3, 28e3));
StockMarket[ecorp] = ecorpStk;
var megacorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp;
var megacorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](megacorp, StockSymbols[megacorp], randInt(40,50)/100, true, 19, randInt(24e3, 34e3));
StockMarket[megacorp] = megacorpStk;
var blade = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries;
var bladeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](blade, StockSymbols[blade], randInt(70, 80)/100, true, 13, randInt(12e3, 25e3));
StockMarket[blade] = bladeStk;
var clarke = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated;
var clarkeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](clarke, StockSymbols[clarke], randInt(65, 75)/100, true, 12, randInt(10e3, 25e3));
StockMarket[clarke] = clarkeStk;
var omnitek = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated;
var omnitekStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omnitek, StockSymbols[omnitek], randInt(60, 70)/100, true, 12, randInt(32e3, 43e3));
StockMarket[omnitek] = omnitekStk;
var foursigma = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma;
var foursigmaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](foursigma, StockSymbols[foursigma], randInt(100, 110)/100, true, 17, randInt(50e3, 80e3));
StockMarket[foursigma] = foursigmaStk;
var kuaigong = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational;
var kuaigongStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](kuaigong, StockSymbols[kuaigong], randInt(75, 85)/100, true, 10, randInt(16e3, 28e3));
StockMarket[kuaigong] = kuaigongStk;
var fulcrum = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies;
var fulcrumStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](fulcrum, StockSymbols[fulcrum], randInt(120, 130)/100, true, 16, randInt(29e3, 36e3));
StockMarket[fulcrum] = fulcrumStk;
var storm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies;
var stormStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](storm, StockSymbols[storm], randInt(80, 90)/100, true, 7, randInt(20e3, 25e3));
StockMarket[storm] = stormStk;
var defcomm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm;
var defcommStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](defcomm, StockSymbols[defcomm], randInt(60, 70)/100, true, 10, randInt(6e3, 19e3));
StockMarket[defcomm] = defcommStk;
var helios = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs;
var heliosStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](helios, StockSymbols[helios], randInt(55, 65)/100, true, 9, randInt(10e3, 18e3));
StockMarket[helios] = heliosStk;
var vitalife = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife;
var vitalifeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](vitalife, StockSymbols[vitalife], randInt(70, 80)/100, true, 7, randInt(8e3, 14e3));
StockMarket[vitalife] = vitalifeStk;
var icarus = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems;
var icarusStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](icarus, StockSymbols[icarus], randInt(60, 70)/100, true, 7.5, randInt(12e3, 24e3));
StockMarket[icarus] = icarusStk;
var universalenergy = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy;
var universalenergyStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](universalenergy, StockSymbols[universalenergy], randInt(50, 60)/100, true, 10, randInt(16e3, 29e3));
StockMarket[universalenergy] = universalenergyStk;
var aerocorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp;
var aerocorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](aerocorp, StockSymbols[aerocorp], randInt(55, 65)/100, true, 6, randInt(8e3, 17e3));
StockMarket[aerocorp] = aerocorpStk;
var omnia = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems;
var omniaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omnia, StockSymbols[omnia], randInt(65, 75)/100, true, 4.5, randInt(6e3, 15e3));
StockMarket[omnia] = omniaStk;
var solaris = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems;
var solarisStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](solaris, StockSymbols[solaris], randInt(70, 80)/100, true, 8.5, randInt(14e3, 28e3));
StockMarket[solaris] = solarisStk;
var globalpharm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals;
var globalpharmStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](globalpharm, StockSymbols[globalpharm], randInt(55, 65)/100, true, 10.5, randInt(12e3, 30e3));
StockMarket[globalpharm] = globalpharmStk;
var nova = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical;
var novaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](nova, StockSymbols[nova], randInt(70, 80)/100, true, 5, randInt(15e3, 27e3));
StockMarket[nova] = novaStk;
var watchdog = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity;
var watchdogStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](watchdog, StockSymbols[watchdog], randInt(240, 260)/100, true, 1.5, randInt(4e3, 8.5e3));
StockMarket[watchdog] = watchdogStk;
var lexocorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp;
var lexocorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](lexocorp, StockSymbols[lexocorp], randInt(115, 135)/100, true, 6, randInt(4.5e3, 8e3));
StockMarket[lexocorp] = lexocorpStk;
var rho = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction;
var rhoStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](rho, StockSymbols[rho], randInt(50, 70)/100, true, 1, randInt(2e3, 7e3));
StockMarket[rho] = rhoStk;
var alpha = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises;
var alphaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](alpha, StockSymbols[alpha], randInt(175, 205)/100, true, 10, randInt(4e3, 8.5e3));
StockMarket[alpha] = alphaStk;
var syscore = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities;
var syscoreStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](syscore, StockSymbols[syscore], randInt(150, 170)/100, true, 3, randInt(3e3, 8e3));
StockMarket[syscore] = syscoreStk;
var computek = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek;
var computekStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](computek, StockSymbols[computek], randInt(80, 100)/100, true, 4, randInt(1e3, 6e3));
StockMarket[computek] = computekStk;
var netlink = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies;
var netlinkStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](netlink, StockSymbols[netlink], randInt(400, 430)/100, true, 1, randInt(1e3, 5e3));
StockMarket[netlink] = netlinkStk;
var omega = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware;
var omegaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omega, StockSymbols[omega], randInt(90, 110)/100, true, 0.5, randInt(1e3, 8e3));
StockMarket[omega] = omegaStk;
var fns = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff;
var fnsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](fns, StockSymbols[fns], randInt(70, 80)/100, false, 1, randInt(500, 4.5e3));
StockMarket[fns] = fnsStk;
var sigmacosm = "Sigma Cosmetics";
var sigmacosmStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](sigmacosm, StockSymbols[sigmacosm], randInt(260, 300)/100, true, 0, randInt(1.5e3, 3.5e3));
StockMarket[sigmacosm] = sigmacosmStk;
var joesguns = "Joes Guns";
var joesgunsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](joesguns, StockSymbols[joesguns], randInt(360, 400)/100, true, 1, randInt(250, 1.5e3));
StockMarket[joesguns] = joesgunsStk;
var catalyst = "Catalyst Ventures";
var catalystStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](catalyst, StockSymbols[catalyst], randInt(120, 175)/100, true, 13.5, randInt(250, 1.5e3));
StockMarket[catalyst] = catalystStk;
var microdyne = "Microdyne Technologies";
var microdyneStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](microdyne, StockSymbols[microdyne], randInt(70, 80)/100, true, 8, randInt(15e3, 30e3));
StockMarket[microdyne] = microdyneStk;
var titanlabs = "Titan Laboratories";
var titanlabsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](titanlabs, StockSymbols[titanlabs], randInt(50, 70)/100, true, 11, randInt(12e3, 24e3));
StockMarket[titanlabs] = titanlabsStk;
var orders = {};
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;}
orders[stock.symbol] = [];
}
}
StockMarket["Orders"] = orders;
StockMarket.storedCycles = 0;
StockMarket.lastUpdate = 0;
}
function initSymbolToStockMap() {
for (var name in StockSymbols) {
if (StockSymbols.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (stock == null) {
console.error(`Could not find Stock for ${name}`);
continue;
}
var symbol = StockSymbols[name];
SymbolToStockMap[symbol] = stock;
}
}
}
function stockMarketCycle() {
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;}
var thresh = 0.6;
if (stock.b) {thresh = 0.4;}
if (Math.random() < thresh) {
stock.b = !stock.b;
}
}
}
}
//Returns true if successful, false otherwise
function buyStock(stock, shares) {
// Validate arguments
shares = Math.round(shares);
if (shares == 0 || shares < 0) { return false; }
if (stock == null || isNaN(shares)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to buy stock. This may be a bug, contact developer");
return false;
}
var totalPrice = stock.price * shares;
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + ".");
return false;
}
var origTotal = stock.playerShares * stock.playerAvgPx;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission);
var newTotal = origTotal + totalPrice;
stock.playerShares = Math.round(stock.playerShares + shares);
stock.playerAvgPx = newTotal / stock.playerShares;
updateStockPlayerPosition(stock);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + " in commission fees.");
return true;
}
//Returns true if successful and false otherwise
function sellStock(stock, shares) {
if (shares == 0) {return false;}
if (stock == null || shares < 0 || isNaN(shares)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell stock. This may be a bug, contact developer");
return false;
}
shares = Math.round(shares);
if (shares > stock.playerShares) {shares = stock.playerShares;}
if (shares === 0) {return false;}
var gains = stock.price * shares - _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(gains);
stock.playerShares = Math.round(stock.playerShares - shares);
if (stock.playerShares == 0) {
stock.playerAvgPx = 0;
}
updateStockPlayerPosition(stock);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " +
"a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(gains, '($0.000a)') + ".");
return true;
}
//Returns true if successful and false otherwise
function shortStock(stock, shares, workerScript=null) {
var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]);
// Validate arguments
shares = Math.round(shares);
if (shares === 0 || shares < 0) { return false; }
if (stock == null || isNaN(shares)) {
if (tixApi) {
workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments.");
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to initiate a short position in a stock. This is probably " +
"due to an invalid quantity. Otherwise, this may be a bug, so contact developer");
}
return false;
}
var totalPrice = stock.price * shares;
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) {
if (tixApi) {
workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have enough " +
"money to purchase this short position. You need " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + ".");
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + ".");
}
return false;
}
var origTotal = stock.playerShortShares * stock.playerAvgShortPx;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission);
var newTotal = origTotal + totalPrice;
stock.playerShortShares = Math.round(stock.playerShortShares + shares);
stock.playerAvgShortPx = newTotal / stock.playerShortShares;
updateStockPlayerPosition(stock);
if (tixApi) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) {
workerScript.scriptRef.log("Bought a short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + " in commission fees.");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + " in commission fees.");
}
return true;
}
//Returns true if successful and false otherwise
function sellShort(stock, shares, workerScript=null) {
var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]);
if (stock == null || isNaN(shares) || shares < 0) {
if (tixApi) {
workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments.");
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell a short position in a stock. This is probably " +
"due to an invalid quantity. Otherwise, this may be a bug, so contact developer");
}
return false;
}
shares = Math.round(shares);
if (shares > stock.playerShortShares) {shares = stock.playerShortShares;}
if (shares === 0) {return false;}
var origCost = shares * stock.playerAvgShortPx;
var profit = ((stock.playerAvgShortPx - stock.price) * shares) - _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
if (isNaN(profit)) {profit = 0;}
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(origCost + profit);
if (tixApi) {
workerScript.scriptRef.onlineMoneyMade += profit;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].scriptProdSinceLastAug += profit;
}
stock.playerShortShares = Math.round(stock.playerShortShares - shares);
if (stock.playerShortShares === 0) {
stock.playerAvgShortPx = 0;
}
updateStockPlayerPosition(stock);
if (tixApi) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) {
workerScript.scriptRef.log("Sold your short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " +
"a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(origCost + profit, '($0.000a)') + ".");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " +
"a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(origCost + profit, '($0.000a)') + ".");
}
return true;
}
function processStockPrices(numCycles=1) {
if (StockMarket.storedCycles == null || isNaN(StockMarket.storedCycles)) { StockMarket.storedCycles = 0; }
StockMarket.storedCycles += numCycles;
// Stock Prices updated every 6 seconds on average. But if there are stored
// cycles they update 50% faster, so every 4 seconds
const msPerStockUpdate = 6e3;
const cyclesPerStockUpdate = msPerStockUpdate / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MilliPerCycle;
if (StockMarket.storedCycles < cyclesPerStockUpdate) { return; }
const timeNow = new Date().getTime();
if (timeNow - StockMarket.lastUpdate < 4e3) { return; }
StockMarket.lastUpdate = timeNow;
StockMarket.storedCycles -= cyclesPerStockUpdate;
var v = Math.random();
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) { continue; }
var av = (v * stock.mv) / 100;
if (isNaN(av)) {av = .02;}
var chc = 50;
if (stock.b) {
chc = (chc + stock.otlkMag) / 100;
if (isNaN(chc)) {chc = 0.5;}
} else {
chc = (chc - stock.otlkMag) / 100;
if (isNaN(chc)) {chc = 0.5;}
}
if (stock.price >= stock.cap) {
chc = 0.1; // "Soft Limit" on stock price. It could still go up but its unlikely
stock.b = false;
}
var c = Math.random();
if (c < chc) {
stock.price *= (1 + av);
processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short);
processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long);
processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long);
processOrders(stock, OrderTypes.StopSell, PositionTypes.Short);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {
updateStockTicker(stock, true);
}
} else {
stock.price /= (1 + av);
processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long);
processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short);
processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short);
processOrders(stock, OrderTypes.StopSell, PositionTypes.Long);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {
updateStockTicker(stock, false);
}
}
var 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 < 0) {
stock.otlkMag *= -1;
stock.b = !stock.b;
}
}
}
}
//Checks and triggers any orders for the specified stock
function processOrders(stock, orderType, posType) {
var orderBook = StockMarket["Orders"];
if (orderBook == null) {
var orders = {};
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;}
orders[stock.symbol] = [];
}
}
StockMarket["Orders"] = orders;
return; //Newly created, so no orders to process
}
var stockOrders = orderBook[stock.symbol];
if (stockOrders == null || !(stockOrders.constructor === Array)) {
console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()");
stockOrders = [];
return;
}
for (var i = 0; i < stockOrders.length; ++i) {
var order = stockOrders[i];
if (order.type === orderType && order.pos === posType) {
switch(order.type) {
case OrderTypes.LimitBuy:
if (order.pos === PositionTypes.Long && stock.price <= order.price) {
executeOrder/*66*/(order);
} else if (order.pos === PositionTypes.Short && stock.price >= order.price) {
executeOrder/*66*/(order);
}
break;
case OrderTypes.LimitSell:
if (order.pos === PositionTypes.Long && stock.price >= order.price) {
executeOrder/*66*/(order);
} else if (order.pos === PositionTypes.Short && stock.price <= order.price) {
executeOrder/*66*/(order);
}
break;
case OrderTypes.StopBuy:
if (order.pos === PositionTypes.Long && stock.price >= order.price) {
executeOrder/*66*/(order);
} else if (order.pos === PositionTypes.Short && stock.price <= order.price) {
executeOrder/*66*/(order);
}
break;
case OrderTypes.StopSell:
if (order.pos === PositionTypes.Long && stock.price <= order.price) {
executeOrder/*66*/(order);
} else if (order.pos === PositionTypes.Short && stock.price >= order.price) {
executeOrder/*66*/(order);
}
break;
default:
console.log("Invalid order type: " + order.type);
return;
}
}
}
}
function setStockMarketContentCreated(b) {
stockMarketContentCreated = b;
}
var stockMarketContentCreated = false;
var stockMarketPortfolioMode = false;
var COMM = _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
function displayStockMarketContent() {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount = false;}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess = false;}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData = false;}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi = false;}
function stylePurchaseButton(btn, cost, flag, initMsg, purchasedMsg) {
btn.innerText = initMsg;
btn.classList.remove("a-link-button");
btn.classList.remove("a-link-button-bought");
btn.classList.remove("a-link-button-inactive");
if (!flag && _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gte(cost)) {
btn.classList.add("a-link-button");
} else if (flag) {
btn.innerText = purchasedMsg;
btn.classList.add("a-link-button-bought");
} else {
btn.classList.add("a-link-button-inactive");
}
}
//Purchase WSE Account button
var wseAccountButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account");
stylePurchaseButton(wseAccountButton, _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount,
"Buy WSE Account - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, '($0.000a)'),
"WSE Account - Purchased");
wseAccountButton.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount = true;
initStockMarket();
initSymbolToStockMap();
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost);
displayStockMarketContent();
return false;
});
//Purchase TIX API Access account
var tixApiAccessButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api");
stylePurchaseButton(tixApiAccessButton, _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess,
"Buy Trade Information eXchange (TIX) API Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, '($0.000a)'),
"TIX API Access - Purchased");
tixApiAccessButton.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess = true;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost);
displayStockMarketContent();
return false;
});
//Purchase Four Sigma Market Data Feed
var marketDataButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-4s-data");
stylePurchaseButton(marketDataButton, _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketData4SCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData,
"Buy 4S Market Data Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketData4SCost, '($0.000a)'),
"4S Market Data - Purchased");
marketDataButton.addEventListener("click", function() {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketData4SCost)) { return false; }
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData = true;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketData4SCost);
displayStockMarketContent();
return false;
});
marketDataButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", {
class:"tooltiptext",
innerText:"Lets you view additional pricing and volatility information about stocks"
}));
marketDataButton.style.marginRight = "2px"; //Adjusts following help tip to be slightly closer
//4S Market Data Help Tip
var marketDataHelpTip = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-4s-data-help-tip");
marketDataHelpTip.style.marginTop = "10px";
marketDataHelpTip.addEventListener("click", ()=>{
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Access to the 4S Market Data feed will display two additional pieces " +
"of information about each stock: Price Forecast & Volatility<br><br>" +
"Price Forecast indicates the probability the stock has of increasing or " +
"decreasing. A '+' forecast means the stock has a higher chance of increasing " +
"than decreasing, and a '-' means the opposite. The number of '+/-' symbols " +
"is used to illustrate the magnitude of these probabilities. For example, " +
"'+++' means that the stock has a significantly higher chance of increasing " +
"than decreasing, while '+' means that the stock only has a slightly higher chance " +
"of increasing than decreasing.<br><br>" +
"Volatility represents the maximum percentage by which a stock's price " +
"can change every tick (a tick occurs every few seconds while the game " +
"is running).<br><br>" +
"A stock's price forecast can change over time. This is also affected by volatility. " +
"The more volatile a stock is, the more its price forecast will change.");
return false;
});
//Purchase Four Sigma Market Data TIX API (Requires TIX API Access)
var marketDataTixButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-4s-tix-api");
stylePurchaseButton(marketDataTixButton, _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketDataTixApi4SCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi,
"Buy 4S Market Data TIX API Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketDataTixApi4SCost, '($0.000a)'),
"4S Market Data TIX API - Purchased");
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess) {
marketDataTixButton.addEventListener("click", function() {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketDataTixApi4SCost)) { return false; }
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi = true;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MarketDataTixApi4SCost);
displayStockMarketContent();
return false;
});
marketDataTixButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", {
class:"tooltiptext",
innerText:"Lets you access 4S Market Data through Netscript"
}));
} else {
marketDataTixButton.classList.remove("a-link-button");
marketDataTixButton.classList.remove("a-link-button-bought");
marketDataTixButton.classList.remove("a-link-button-inactive");
marketDataTixButton.classList.add("a-link-button-inactive");
marketDataTixButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", {
class:"tooltiptext",
innerText:"Requires TIX API Access"
}));
}
var stockList = document.getElementById("stock-market-list");
if (stockList == null) {return;}
//UI Elements that should only appear if you have WSE account access
var commissionText = document.getElementById("stock-market-commission");
var modeBtn = document.getElementById("stock-market-mode");
var expandBtn = document.getElementById("stock-market-expand-tickers");
var collapseBtn = document.getElementById("stock-market-collapse-tickers");
var watchlistFilter = document.getElementById("stock-market-watchlist-filter");
var watchlistUpdateBtn = document.getElementById("stock-market-watchlist-filter-update");
//If Player doesn't have account, clear stocks UI and return
if (!_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) {
stockMarketContentCreated = false;
while (stockList.firstChild) {
stockList.removeChild(stockList.firstChild);
}
commissionText.style.visibility = "hidden";
modeBtn.style.visibility = "hidden";
expandBtn.style.visibility = "hidden";
collapseBtn.style.visibility = "hidden";
watchlistFilter.style.visibility = "hidden";
watchlistUpdateBtn.style.visibility = "hidden";
return;
} else {
commissionText.style.visibility = "visible";
modeBtn.style.visibility = "visible";
expandBtn.style.visibility = "visible";
collapseBtn.style.visibility = "visible";
watchlistFilter.style.visibility = "visible";
watchlistUpdateBtn.style.visibility = "visible";
}
//Create stock market content if you have an account
if (!stockMarketContentCreated && _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) {
console.log("Creating Stock Market UI");
commissionText.innerHTML =
"Commission Fees: Every transaction you make has a " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, '($0.000a)') + " commission fee.<br><br>" +
"WARNING: When you reset after installing Augmentations, the Stock Market is reset. " +
"This means all your positions are lost, so make sure to sell your stocks before installing " +
"Augmentations!";
var investopediaButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-investopedia");
investopediaButton.addEventListener("click", function() {
var txt = "When making a transaction on the stock market, there are two " +
"types of positions: Long and Short. A Long position is the typical " +
"scenario where you buy a stock and earn a profit if the price of that " +
"stock increases. Meanwhile, a Short position is the exact opposite. " +
"In a Short position you purchase shares of a stock and earn a profit " +
"if the price of that stock decreases. This is also called 'shorting' a stock.<br><br>" +
"NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.<br><br>" +
"There are three different types of orders you can make to buy or sell " +
"stocks on the exchange: Market Order, Limit Order, and Stop Order. " +
"Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " +
"later on in the game.<br><br>" +
"When you place a Market Order to buy or sell a stock, the order executes " +
"immediately at whatever the current price of the stock is. For example " +
"if you choose to short a stock with 5000 shares using a Market Order, " +
"you immediately purchase those 5000 shares in a Short position at whatever " +
"the current market price is for that stock.<br><br>" +
"A Limit Order is an order that only executes under certain conditions. " +
"A Limit Order is used to buy or sell a stock at a specified price or better. " +
"For example, lets say you purchased a Long position of 100 shares of some stock " +
"at a price of $10 per share. You can place a Limit Order to sell those 100 shares " +
"at $50 or better. The Limit Order will execute when the price of the stock reaches a " +
"value of $50 or higher.<br><br>" +
"A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " +
"at a specified price (before the price gets 'worse'). For example, lets say you purchased " +
"a Short position of 100 shares of some stock at a price of $100 per share. " +
"The current price of the stock is $80 (a profit of $20 per share). You can place a " +
"Stop Order to sell the Short position if the stock's price reaches $90 or higher. " +
"This can be used to lock in your profits and limit any losses.<br><br>" +
"Here is a summary of how each order works and when they execute:<br><br>" +
"In a LONG Position:<br><br>" +
"A Limit Order to buy will execute if the stock's price <= order's price<br>" +
"A Limit Order to sell will execute if the stock's price >= order's price<br>" +
"A Stop Order to buy will execute if the stock's price >= order's price<br>" +
"A Stop Order to sell will execute if the stock's price <= order's price<br><br>" +
"In a SHORT Position:<br><br>" +
"A Limit Order to buy will execute if the stock's price >= order's price<br>" +
"A Limit Order to sell will execute if the stock's price <= order's price<br>" +
"A Stop Order to buy will execute if the stock's price <= order's price<br>" +
"A Stop Order to sell will execute if the stock's price >= order's price.";
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])(txt);
return false;
});
//Switch to Portfolio Mode Button
if (modeBtn) {
stockMarketPortfolioMode = false;
modeBtn.innerHTML = "Switch to 'Portfolio' Mode" +
"<span class='tooltiptext'>Displays only the stocks for which you have shares or orders</span>";
modeBtn.addEventListener("click", switchToPortfolioMode);
}
//Expand/Collapse tickers buttons
var stockList = document.getElementById("stock-market-list");
if (expandBtn) {
expandBtn.addEventListener("click", ()=>{
var tickerHdrs = stockList.getElementsByClassName("accordion-header");
for (var i = 0; i < tickerHdrs.length; ++i) {
if (!tickerHdrs[i].classList.contains("active")) {
tickerHdrs[i].click();
}
}
});
}
if (collapseBtn) {
collapseBtn.addEventListener("click",()=>{
var tickerHdrs = stockList.getElementsByClassName("accordion-header");
for (var i = 0; i < tickerHdrs.length; ++i) {
if (tickerHdrs[i].classList.contains("active")) {
tickerHdrs[i].click();
}
}
});
}
//Watchlish filter
if (watchlistFilter && watchlistUpdateBtn) {
//Initialize value in watchlist
if (StockMarket.watchlistFilter) {
watchlistFilter.value = StockMarket.watchlistFilter; //Remove whitespace
}
watchlistUpdateBtn.addEventListener("click", ()=> {
let filterValue = watchlistFilter.value.toString();
StockMarket.watchlistFilter = filterValue.replace(/\s/g, '');
if (stockMarketPortfolioMode) {
switchToPortfolioMode();
} else {
switchToDisplayAllMode();
}
});
watchlistFilter.addEventListener("keyup", (e)=>{
e.preventDefault();
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__["KEY"].ENTER) {watchlistUpdateBtn.click();}
})
} else {
console.warn("Stock Market Watchlist DOM elements could not be found");
}
createAllStockTickers();
stockMarketContentCreated = true;
}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) {
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"]) {
updateStockTicker(stock, null);
updateStockOrderList(stock);
}
}
}
}
}
//Displays only stocks you have position/order in
function switchToPortfolioMode() {
stockMarketPortfolioMode = true;
var modeBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode");
if (modeBtn) {
modeBtn.innerHTML = "Switch to 'All stocks' Mode" +
"<span class='tooltiptext'>Displays all stocks on the WSE</span>";
modeBtn.addEventListener("click", switchToDisplayAllMode);
}
createAllStockTickers();
}
//Displays all stocks
function switchToDisplayAllMode() {
stockMarketPortfolioMode = false;
var modeBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode");
if (modeBtn) {
modeBtn.innerHTML = "Switch to 'Portfolio' Mode" +
"<span class='tooltiptext'>Displays only the stocks for which you have shares or orders</span>";
modeBtn.addEventListener("click", switchToPortfolioMode);
}
createAllStockTickers();
}
function createAllStockTickers() {
var stockList = document.getElementById("stock-market-list");
if (stockList == null) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__[/* exceptionAlert */ "a"])("Error creating Stock Tickers UI. DOM element with ID 'stock-market-list' could not be found");
}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__["removeChildrenFromElement"])(stockList);
var orderBook = StockMarket["Orders"];
if (orderBook == null) {
var orders = {};
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;}
orders[stock.symbol] = [];
}
}
StockMarket["Orders"] = orders;
orderBook = StockMarket["Orders"];
}
let watchlist = null;
if (StockMarket.watchlistFilter != null && StockMarket.watchlistFilter !== "") {
let filter = StockMarket.watchlistFilter.replace(/\s/g, '');
watchlist = filter.split(",");
}
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} //orders property is an array
if (watchlist && !watchlist.includes(stock.symbol)) {continue;} //Watchlist filtering
let stockOrders = orderBook[stock.symbol];
if (stockMarketPortfolioMode) {
if (stock.playerShares === 0 && stock.playerShortShares === 0 &&
stockOrders.length === 0) {continue;}
}
createStockTicker(stock);
}
}
setStockTickerClickHandlers(); //Clicking headers opens/closes panels
}
function createStockTicker(stock) {
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {
console.log("Invalid stock in createStockSticker()");
return;
}
var tickerId = "stock-market-ticker-" + stock.symbol;
var li = document.createElement("li"), hdr = document.createElement("button");
hdr.classList.add("accordion-header");
hdr.setAttribute("id", tickerId + "-hdr");
hdr.innerHTML = stock.name + " - " + stock.symbol + " - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)');
//Div for entire panel
var stockDiv = document.createElement("div");
stockDiv.classList.add("accordion-panel");
stockDiv.setAttribute("id", tickerId + "-panel");
/* Create panel DOM */
var qtyInput = document.createElement("input"),
longShortSelect = document.createElement("select"),
orderTypeSelect = document.createElement("select"),
buyButton = document.createElement("span"),
sellButton = document.createElement("span"),
buyMaxButton = document.createElement("span"),
sellAllButton = document.createElement("span"),
positionTxt = document.createElement("p"),
orderList = document.createElement("ul");
qtyInput.classList.add("stock-market-input");
qtyInput.placeholder = "Quantity (Shares)";
qtyInput.setAttribute("id", tickerId + "-qty-input");
qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " +
" || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) " +
" || (95<event.keyCode && event.keyCode<106) " +
" || (event.keyCode==8) || (event.keyCode==9) " +
" || (event.keyCode>34 && event.keyCode<40) " +
" || (event.keyCode==46) )");
longShortSelect.classList.add("stock-market-input");
longShortSelect.setAttribute("id", tickerId + "-pos-selector");
var longOpt = document.createElement("option");
longOpt.text = "Long";
longShortSelect.add(longOpt);
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 2)) {
var shortOpt = document.createElement("option");
shortOpt.text = "Short";
longShortSelect.add(shortOpt);
}
orderTypeSelect.classList.add("stock-market-input");
orderTypeSelect.setAttribute("id", tickerId + "-order-selector");
var marketOpt = document.createElement("option");
marketOpt.text = "Market Order";
orderTypeSelect.add(marketOpt);
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 3)) {
var limitOpt = document.createElement("option");
limitOpt.text = "Limit Order";
orderTypeSelect.add(limitOpt);
var stopOpt = document.createElement("option");
stopOpt.text = "Stop Order";
orderTypeSelect.add(stopOpt);
}
buyButton.classList.add("stock-market-input");
buyButton.classList.add("a-link-button");
buyButton.innerHTML = "Buy";
buyButton.addEventListener("click", ()=>{
var pos = longShortSelect.options[longShortSelect.selectedIndex].text;
pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short;
var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text;
var shares = Number(document.getElementById(tickerId + "-qty-input").value);
if (isNaN(shares)) {return false;}
switch (ordType) {
case "Market Order":
pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null);
break;
case "Limit Order":
case "Stop Order":
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerText = "Place Buy " + ordType;
noBtn.innerText = "Cancel Order";
yesBtn.addEventListener("click", ()=>{
var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type;
if (ordType === "Limit Order") {
type = OrderTypes.LimitBuy;
} else {
type = OrderTypes.StopBuy;
}
placeOrder(stock, shares, price, type, pos);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType);
break;
default:
console.log("ERROR: Invalid order type");
break;
}
return false;
});
sellButton.classList.add("stock-market-input");
sellButton.classList.add("a-link-button");
sellButton.innerHTML = "Sell";
sellButton.addEventListener("click", ()=>{
var pos = longShortSelect.options[longShortSelect.selectedIndex].text;
pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short;
var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text;
var shares = Number(document.getElementById(tickerId + "-qty-input").value);
if (isNaN(shares)) {return false;}
switch (ordType) {
case "Market Order":
pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null);
break;
case "Limit Order":
case "Stop Order":
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerText = "Place Sell " + ordType;
noBtn.innerText = "Cancel Order";
yesBtn.addEventListener("click", ()=>{
var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type;
if (ordType === "Limit Order") {
type = OrderTypes.LimitSell;
} else {
type = OrderTypes.StopSell;
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
placeOrder(stock, shares, price, type, pos);
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType);
break;
default:
console.log("ERROR: Invalid order type");
break;
}
return false;
});
buyMaxButton.classList.add("stock-market-input");
buyMaxButton.classList.add("a-link-button");
buyMaxButton.innerHTML = "Buy MAX";
buyMaxButton.addEventListener("click", ()=>{
var pos = longShortSelect.options[longShortSelect.selectedIndex].text;
pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short;
var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text;
var money = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.toNumber();
switch (ordType) {
case "Market Order":
var shares = Math.floor((money - COMM) / stock.price);
pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null);
break;
case "Limit Order":
case "Stop Order":
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerText = "Place Buy " + ordType;
noBtn.innerText = "Cancel Order";
yesBtn.addEventListener("click", ()=>{
var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type;
if (ordType === "Limit Order") {
type = OrderTypes.LimitBuy;
} else {
type = OrderTypes.StopBuy;
}
var shares = Math.floor((money-COMM) / price);
placeOrder(stock, shares, price, type, pos);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType);
break;
default:
console.log("ERROR: Invalid order type");
break;
}
return false;
});
sellAllButton.classList.add("stock-market-input");
sellAllButton.classList.add("a-link-button");
sellAllButton.innerHTML = "Sell ALL";
sellAllButton.addEventListener("click", ()=>{
var pos = longShortSelect.options[longShortSelect.selectedIndex].text;
pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short;
var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text;
switch (ordType) {
case "Market Order":
if (pos === PositionTypes.Long) {
var shares = stock.playerShares;
sellStock(stock, shares);
} else {
var shares = stock.playerShortShares;
sellShort(stock, shares, null);
}
break;
case "Limit Order":
case "Stop Order":
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: 'Sell All' only works for Market Orders")
break;
default:
console.log("ERROR: Invalid order type");
break;
}
return false;
});
positionTxt.setAttribute("id", tickerId + "-position-text");
positionTxt.classList.add("stock-market-position-text");
stock.posTxtEl = positionTxt;
orderList.setAttribute("id", tickerId + "-order-list");
orderList.classList.add("stock-market-order-list");
stockDiv.appendChild(qtyInput);
stockDiv.appendChild(longShortSelect);
stockDiv.appendChild(orderTypeSelect);
stockDiv.appendChild(buyButton);
stockDiv.appendChild(sellButton);
stockDiv.appendChild(buyMaxButton);
stockDiv.appendChild(sellAllButton);
stockDiv.appendChild(positionTxt);
stockDiv.appendChild(orderList);
li.appendChild(hdr);
li.appendChild(stockDiv);
document.getElementById("stock-market-list").appendChild(li);
updateStockTicker(stock, true);
updateStockPlayerPosition(stock);
updateStockOrderList(stock);
}
function setStockTickerClickHandlers() {
var stockList = document.getElementById("stock-market-list");
var tickerHdrs = stockList.getElementsByClassName("accordion-header");
if (tickerHdrs == null) {
console.log("ERROR: Could not find header elements for stock tickers");
return;
}
for (var i = 0; i < tickerHdrs.length; ++i) {
tickerHdrs[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
}
//'increase' argument is a boolean indicating whether the price increased or decreased
function updateStockTicker(stock, increase) {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;}
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {
console.log("Invalid stock in updateStockTicker():");
console.log(stock);
return;
}
var tickerId = "stock-market-ticker-" + stock.symbol;
if (stock.playerShares > 0 || stock.playerShortShares > 0) {
updateStockPlayerPosition(stock);
}
var hdr = document.getElementById(tickerId + "-hdr");
if (hdr == null) {
if (!stockMarketPortfolioMode) {
let watchlist = StockMarket.watchlistFilter;
if (watchlist !== "" && watchlist.includes(stock.symbol)) {
console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol);
}
}
return;
}
let hdrText = stock.name + " (" + stock.symbol + ") - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)');
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData) {
hdrText += " - Volatility: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.mv, '0,0.00') + "%" +
" - Price Forecast: ";
if (stock.b) {
hdrText += "+".repeat(Math.floor(stock.otlkMag/10) + 1);
} else {
hdrText += "-".repeat(Math.floor(stock.otlkMag/10) + 1);
}
}
hdr.innerText = hdrText;
if (increase != null) {
increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red";
}
}
function updateStockPlayerPosition(stock) {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;}
if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {
console.log("Invalid stock in updateStockPlayerPosition():");
console.log(stock);
return;
}
var tickerId = "stock-market-ticker-" + stock.symbol;
if (stockMarketPortfolioMode) {
if (stock.playerShares === 0 && stock.playerShortShares === 0 &&
StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] &&
StockMarket["Orders"][stock.symbol].length === 0) {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-hdr");
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-panel");
return;
} else {
//If the ticker hasn't been created, create it (handles updating)
//If it has been created, continue normally
if (document.getElementById(tickerId + "-hdr") == null) {
createStockTicker(stock);
setStockTickerClickHandlers();
return;
}
}
}
if (!(stock.posTxtEl instanceof Element)) {
stock.posTxtEl = document.getElementById(tickerId + "-position-text");
}
if (stock.posTxtEl == null) {
console.log("ERROR: Could not find stock position element for: " + stock.symbol);
return;
}
//Calculate returns
const totalCost = stock.playerShares * stock.playerAvgPx;
let gains = (stock.price - stock.playerAvgPx) * stock.playerShares;
let percentageGains = gains / totalCost;
if (isNaN(percentageGains)) { percentageGains = 0; }
const shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx;
let shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares;
let shortPercentageGains = shortGains/ shortTotalCost;
if (isNaN(shortPercentageGains)) { shortPercentageGains = 0; }
stock.posTxtEl.innerHTML =
"<h1 class='tooltip stock-market-position-text'>Long Position: " +
"<span class='tooltiptext'>Shares in the long position will increase " +
"in value if the price of the corresponding stock increases</span></h1>" +
"<br>Shares: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerShares, '0,0') +
"<br>Average Price: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerAvgPx, '$0.000a') +
" (Total Cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalCost, '$0.000a') + ")" +
"<br>Profit: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(gains, '$0.000a') +
" (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(percentageGains, '0.00%') + ")<br><br>";
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 2)) {
stock.posTxtEl.innerHTML +=
"<h1 class='tooltip stock-market-position-text'>Short Position: " +
"<span class='tooltiptext'>Shares in short position will increase " +
"in value if the price of the corresponding stock decreases</span></h1>" +
"<br>Shares: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerShortShares, '0,0') +
"<br>Average Price: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerAvgShortPx, '$0.000a') +
" (Total Cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortTotalCost, '$0.000a') + ")" +
"<br>Profit: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortGains, '$0.000a') +
" (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortPercentageGains, '0.00%') + ")" +
"<br><br><h1 class='stock-market-position-text'>Orders: </h1>";
}
}
function updateStockOrderList(stock) {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;}
var tickerId = "stock-market-ticker-" + stock.symbol;
var orderList = document.getElementById(tickerId + "-order-list");
if (orderList == null) {
//Log only if its a valid error
if (!stockMarketPortfolioMode) {
let watchlist = StockMarket.watchlistFilter;
if (watchlist !== "" && watchlist.includes(stock.symbol)) {
console.log("ERROR: Could not find order list for " + stock.symbol);
}
}
return;
}
var orderBook = StockMarket["Orders"];
if (orderBook == null) {
console.log("ERROR: Could not find order book in stock market");
return;
}
var stockOrders = orderBook[stock.symbol];
if (stockOrders == null) {
console.log("ERROR: Could not find orders for: " + stock.symbol);
return;
}
if (stockMarketPortfolioMode) {
if (stock.playerShares === 0 && stock.playerShortShares === 0 &&
StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] &&
StockMarket["Orders"][stock.symbol].length === 0) {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-hdr");
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-panel");
return;
} else {
//If the ticker hasn't been created, create it (handles updating)
//If it has been created, continue normally
if (document.getElementById(tickerId + "-hdr") == null) {
createStockTicker(stock);
setStockTickerClickHandlers();
return;
}
}
}
//Remove everything from list
while (orderList.firstChild) {
orderList.removeChild(orderList.firstChild);
}
for (var i = 0; i < stockOrders.length; ++i) {
(function() {
var order = stockOrders[i];
var li = document.createElement("li");
li.style.padding = "4px";
var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position");
li.style.color = "white";
li.innerText = order.type + " - " + posText + " - " +
order.shares + " @ " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(order.price, '($0.000a)');
var cancelButton = document.createElement("span");
cancelButton.classList.add("stock-market-order-cancel-btn");
cancelButton.classList.add("a-link-button");
cancelButton.innerHTML = "Cancel Order";
cancelButton.addEventListener("click", function() {
cancelOrder({order: order}, null);
return false;
});
li.appendChild(cancelButton);
orderList.appendChild(li);
}());
}
}
/***/ }),
/* 23 */
/*!******************************!*\
!*** ./src/CreateProgram.js ***!
\******************************/
/*! exports provided: Programs, displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */
/*! exports used: Programs, displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Programs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return displayCreateProgramContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getNumAvailableCreateProgram; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initCreateProgramButtons; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__);
// a function that returns a requirement for a program that requires only that
// the player has at least the given skill level.
function requireLevel(lvl) {
return function() {
return _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill >= lvl;
}
}
function Program(name, create) {
this.name = name;
this.create = create;
}
Program.prototype.htmlID = function() {
const name = this.name.endsWith('.exe') ? this.name.slice(0, -('.exe'.length)) : this.name;
return "create-program-"+name;
}
/* Create programs */
const Programs = {
NukeProgram: new Program("NUKE.exe", {
level: 1,
tooltip:"This virus is used to gain root access to a machine if enough ports are opened.",
req: requireLevel(1),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes,
}),
BruteSSHProgram: new Program("BruteSSH.exe", {
level: 50,
tooltip:"This program executes a brute force attack that opens SSH ports",
req: requireLevel(50),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes * 2,
}),
FTPCrackProgram: new Program("FTPCrack.exe", {
level: 100,
tooltip:"This program cracks open FTP ports",
req: requireLevel(100),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour,
}),
RelaySMTPProgram: new Program("relaySMTP.exe", {
level: 250,
tooltip:"This program opens SMTP ports by redirecting data",
req: requireLevel(250),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours,
}),
HTTPWormProgram: new Program("HTTPWorm.exe", {
level: 500,
tooltip:"This virus opens up HTTP ports",
req: requireLevel(500),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer4Hours,
}),
SQLInjectProgram: new Program("SQLInject.exe", {
level: 750,
tooltip:"This virus opens SQL ports",
req: requireLevel(750),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer8Hours,
}),
DeepscanV1: new Program("DeepscanV1.exe", {
level: 75,
tooltip:"This program allows you to use the scan-analyze command with a depth up to 5",
req: requireLevel(75),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour,
}),
DeepscanV2: new Program("DeepscanV2.exe", {
level: 400,
tooltip:"This program allows you to use the scan-analyze command with a depth up to 10",
req: requireLevel(400),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours,
}),
ServerProfiler: new Program("ServerProfiler.exe", {
level: 75,
tooltip:"This program is used to display hacking and Netscript-related information about servers",
req: requireLevel(75),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour,
}),
AutoLink: new Program("AutoLink.exe", {
level: 25,
tooltip:"This program allows you to directly connect to other servers through the 'scan-analyze' command",
req: requireLevel(25),
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour,
}),
BitFlume: new Program("b1t_flum3.exe", {
level: 1,
tooltip:"This program creates a portal to the BitNode Nexus (allows you to restart and switch BitNodes)",
req: function() {return _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].sourceFiles.length > 0 && _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill >= 1},
time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes / 20,
}),
// special because you can't create it.
Flight: new Program("fl1ght.exe"),
};
// this has the same key as 'Programs', not program names
const aLinks = {};
function displayCreateProgramContent() {
for(const key in aLinks) {
const p = Programs[key]
aLinks[key].style.display = "none";
if(!_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hasProgram(p.name) && p.create.req()){
aLinks[key].style.display = "inline-block";
}
}
}
//Returns the number of programs that are currently available to be created
function getNumAvailableCreateProgram() {
var count = 0;
for(const key in Programs) {
if(Programs[key].create === undefined) { // a program we can't create
continue
}
if(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hasProgram(Programs[key].name)) { // can't create it twice
continue
}
if(!Programs[key].create.req()) { // if you don't fullfill the creation requirement
continue
}
count++;
}
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].firstProgramAvailable === false && count > 0) {
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].firstProgramAvailable = true;
document.getElementById("create-program-tab").style.display = "list-item";
document.getElementById("hacking-menu-header").click();
document.getElementById("hacking-menu-header").click();
}
return count;
}
function initCreateProgramButtons() {
var createProgramList = document.getElementById("create-program-list");
for(const key in Programs) {
if(Programs[key].create === undefined) {
continue
}
const elem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", {
class: "a-link-button", id: Programs[key].htmlID(), innerText: Programs[key].name,
tooltip: Programs[key].create.tooltip,
});
aLinks[key] = elem;
createProgramList.appendChild(elem);
}
for(const key in aLinks) {
const p = Programs[key]
aLinks[key].addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].startCreateProgramWork(p.name, p.create.time, p.create.level);
return false;
});
}
}
/***/ }),
/* 24 */
/*!********************************!*\
!*** ./src/NetscriptWorker.js ***!
\********************************/
/*! exports provided: WorkerScript, workerScripts, NetscriptPorts, runScriptsLoop, killWorkerScript, addWorkerScript, updateOnlineScriptTimes, prestigeWorkerScripts */
/*! exports used: NetscriptPorts, WorkerScript, addWorkerScript, killWorkerScript, prestigeWorkerScripts, runScriptsLoop, updateOnlineScriptTimes, workerScripts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return workerScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptsLoop; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return killWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return addWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return updateOnlineScriptTimes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeWorkerScripts; });
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI */ 64);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _JSInterpreter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./JSInterpreter */ 119);
/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEnvironment */ 105);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./NetscriptJSEvaluator */ 106);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./NetscriptPort */ 68);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! escodegen */ 99);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(escodegen__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn */ 46);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 87);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 52);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 77);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__);
const walk = __webpack_require__(/*! acorn/dist/walk */ 136);
function WorkerScript(runningScriptObj) {
this.name = runningScriptObj.filename;
this.running = false;
this.serverIp = null;
this.code = runningScriptObj.scriptRef.code;
this.env = new _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_4__[/* Environment */ "a"](this);
this.env.set("args", runningScriptObj.args.slice());
this.output = "";
this.ramUsage = 0;
this.scriptRef = runningScriptObj;
this.errorMessage = "";
this.args = runningScriptObj.args.slice();
this.delay = null;
this.fnWorker = null; //Workerscript for a function call
this.checkingRam = false;
this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM. Used for static RAM evaluation
this.disableLogs = {}; //Stores names of fns that should have logs disabled
//Properties used for dynamic RAM evaluation
this.dynamicRamUsage = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ScriptBaseRamCost;
this.dynamicLoadedFns = {};
}
//Returns the server on which the workerScript is running
WorkerScript.prototype.getServer = function() {
return _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][this.serverIp];
}
//Returns the Script object for the underlying script
WorkerScript.prototype.getScript = function() {
let server = this.getServer();
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === this.name) {
return server.scripts[i];
}
}
console.log("ERROR: Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong");
return null;
}
//Returns the Script object for the specified script
WorkerScript.prototype.getScriptOnServer = function(fn, server) {
if (server == null) {
server = this.getServer();
}
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === fn) {
return server.scripts[i];
}
}
return null;
}
WorkerScript.prototype.shouldLog = function(fn) {
return (this.disableLogs.ALL == null && this.disableLogs[fn] == null);
}
WorkerScript.prototype.log = function(txt) {
this.scriptRef.log(txt);
}
//Array containing all scripts that are running across all servers, to easily run them all
let workerScripts = [];
var NetscriptPorts = [];
for (var i = 0; i < _Constants__WEBPACK_IMPORTED_MODULE_1__["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_0__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]);
workerScripts[i].env.stopFlag = true;
}
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* 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 */ "d"])(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 */ "d"])(
workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || ""));
throw workerScript;
} else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(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_13__["dialogBoxCreate"])("Error processing Imports in " + workerScript.name + ":<br>" + 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 = [];
for (let i = 0; i < arguments.length-1; ++i) {
fnArgs.push(arguments[i]);
}
let cb = arguments[arguments.length-1];
let fnPromise = entry.apply(null, fnArgs);
fnPromise.then(function(res) {
cb(res);
});
}
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_3__[/* Interpreter */ "a"](codeWithImports, interpreterInitialization, codeLineOffset);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Syntax ERROR in " + workerScript.name + ":<br>" + 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()) {
window.setTimeout(runInterpreter, _Settings__WEBPACK_IMPORTED_MODULE_10__["Settings"].CodeInstructionRunTime);
} else {
resolve(workerScript);
}
} catch(e) {
e = e.toString();
if (!Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(e)) {
e = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "d"])(workerScript, e);
}
workerScript.errorMessage = e;
return reject(workerScript);
}
}
try {
runInterpreter();
} catch(e) {
if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["isString"])(e)) {
workerScript.errorMessage = e;
return reject(workerScript);
} else if (e instanceof 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_12__["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;
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_12__["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_11__["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_11__["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_11__["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__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][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__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].ramUsed += workerScripts[j].ramUsage;
}
//Delete script from Active Scripts
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]);
for (var j = 0; j < _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts.length; j++) {
if (_Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts[j].filename == name &&
Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__["compareArrays"])(_Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts[j].args, workerScripts[i].args)) {
_Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts.splice(j, 1);
break;
}
}
//Delete script from workerScripts
workerScripts.splice(i, 1);
}
}
if (scriptDeleted) {Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* 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;}
/*
try {
var ast = parse(workerScripts[i].code, {sourceType:"module"});
//console.log(ast);
} catch (e) {
console.log("Error parsing script: " + workerScripts[i].name);
dialogBoxCreate("Syntax ERROR in " + workerScripts[i].name + ":<br>" + e);
workerScripts[i].env.stopFlag = true;
continue;
}
workerScripts[i].running = true;
p = evaluate(ast, workerScripts[i]);
*/
}
//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_13__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
console.log("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 WorkerScript) {
if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(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_13__["dialogBoxCreate"])("Script runtime error: <br>Server Ip: " + serverIp +
"<br>Script name: " + scriptName +
"<br>Args:" + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__["arrayToString"])(w.args) + "<br>" + 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 */ "b"])(w)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["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_13__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev");
console.log(w);
}
});
}
}
setTimeout(runScriptsLoop, 6000);
}
//Queues a script to be killed by settings its stop flag to true. Then, the code will reject
//all of its promises recursively, and when it does so it will no longer be running.
//The runScriptsLoop() will then delete the script from worker scripts
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_14__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) {
workerScripts[i].env.stopFlag = true;
Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* killNetscriptDelay */ "c"])(workerScripts[i]);
//Recursively kill all functions
var curr = workerScripts[i];
while (curr.fnWorker) {
curr.fnWorker.env.stopFlag = true;
Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* killNetscriptDelay */ "c"])(curr.fnWorker);
curr = curr.fnWorker;
}
return true;
}
}
return false;
}
//Queues a 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_16__["roundToTwo"])(runningScriptObj.scriptRef.ramUsage * threads);
var ramAvailable = server.maxRam - server.ramUsed;
if (ramUsage > ramAvailable) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " +
Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__["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_16__["roundToTwo"])(server.ramUsed + ramUsage);
//Create the WorkerScript
var s = new WorkerScript(runningScriptObj);
s.serverIp = server.ip;
s.ramUsage = ramUsage;
//Add the WorkerScript to the Active Scripts list
Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* 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_2__["Engine"]._idleSpeed) / 1000; //seconds
for (var i = 0; i < workerScripts.length; ++i) {
workerScripts[i].scriptRef.onlineRunningTime += time;
}
}
/***/ }),
/* 25 */
/*!**********************!*\
!*** ./src/Stock.ts ***!
\**********************/
/*! no static exports found */
/*! exports used: Stock */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 13);
const getRandomInt_1 = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/**
* Represents the valuation of a company in the World Stock Exchange.
*/
class Stock {
/**
* Initializes a Stock from a JSON save state
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Stock, value.data);
}
constructor(name = "", symbol = "", mv = 1, b = true, otlkMag = 0, initPrice = 10e3) {
this.name = name;
this.symbol = symbol;
this.price = initPrice;
this.playerShares = 0;
this.playerAvgPx = 0;
this.playerShortShares = 0;
this.playerAvgShortPx = 0;
this.mv = mv;
this.b = b;
this.otlkMag = otlkMag;
this.cap = getRandomInt_1.getRandomInt(initPrice * 1e3, initPrice * 25e3);
this.posTxtEl = null;
}
/**
* Serialize the Stock to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Stock", this);
}
}
exports.Stock = Stock;
JSONReviver_1.Reviver.constructors.Stock = Stock;
/***/ }),
/* 26 */
/*!*****************************************!*\
!*** ./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 */ 185);
const CompanyPosition_1 = __webpack_require__(/*! ./CompanyPosition */ 81);
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);
});
/***/ }),
/* 27 */
/*!******************************************************!*\
!*** ./utils/uiHelpers/removeChildrenFromElement.ts ***!
\******************************************************/
/*! no static exports found */
/*! exports used: removeChildrenFromElement */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __webpack_require__(/*! ../helpers/isString */ 37);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 51);
/**
* 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;
/***/ }),
/* 28 */
/*!***********************!*\
!*** ./src/Script.js ***!
\***********************/
/*! exports provided: updateScriptEditorContent, loadAllRunningScripts, findRunningScript, RunningScript, Script, AllServersMap, scriptEditorInit, isScriptFilename */
/*! exports used: AllServersMap, RunningScript, Script, findRunningScript, isScriptFilename, loadAllRunningScripts, scriptEditorInit, updateScriptEditorContent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return updateScriptEditorContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return loadAllRunningScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return findRunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return RunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Script; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllServersMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return scriptEditorInit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isScriptFilename; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Fconf */ 45);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial */ 33);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile */ 60);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn */ 46);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 87);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 83);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 77);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__);
var ace = __webpack_require__(/*! brace */ 244);
var beautify = __webpack_require__(/*! js-beautify */ 243).js_beautify;
__webpack_require__(/*! brace/mode/javascript */ 242);
__webpack_require__(/*! ../netscript */ 178);
__webpack_require__(/*! brace/theme/chaos */ 241);
__webpack_require__(/*! brace/theme/chrome */ 240);
__webpack_require__(/*! brace/theme/monokai */ 239);
__webpack_require__(/*! brace/theme/solarized_dark */ 238);
__webpack_require__(/*! brace/theme/solarized_light */ 237);
__webpack_require__(/*! brace/theme/terminal */ 236);
__webpack_require__(/*! brace/theme/twilight */ 235);
__webpack_require__(/*! brace/theme/xcode */ 234);
__webpack_require__(/*! brace/keybinding/vim */ 233);
__webpack_require__(/*! brace/keybinding/emacs */ 232);
__webpack_require__(/*! brace/ext/language_tools */ 231);
// Importing this doesn't work for some reason.
const walk = __webpack_require__(/*! acorn/dist/walk */ 136);
var keybindings = {
ace: null,
vim: "ace/keyboard/vim",
emacs: "ace/keyboard/emacs",
};
function isScriptFilename(f) {
return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns");
}
var scriptEditorRamCheck = null, scriptEditorRamText = null;
function scriptEditorInit() {
//Create buttons at the bottom of script editor
var wrapper = document.getElementById("script-editor-buttons-wrapper");
if (wrapper == null) {
console.log("Error finding 'script-editor-buttons-wrapper'");
return;
}
var beautifyButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerText:"Beautify",
clickListener:()=>{
beautifyScript();
return false;
}
});
var closeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerText:"Save & Close (Ctrl/Cmd + b)",
clickListener:()=>{
saveAndCloseScriptEditor();
return false;
}
});
scriptEditorRamText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("p", {
display:"inline-block", margin:"10px", id:"script-editor-status-text"
});
var checkboxLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["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"
});
scriptEditorRamCheck = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("input", {
type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check",
margin:"4px", marginTop: "8px",
});
scriptEditorRamCheck.checked = true;
var documentationButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", {
display:"inline-block", class:"a-link-button", innerText:"Netscript Documentation",
href:"https://bitburner.readthedocs.io/en/latest/index.html",
target:"_blank"
});
wrapper.appendChild(beautifyButton);
wrapper.appendChild(closeButton);
wrapper.appendChild(scriptEditorRamText);
wrapper.appendChild(scriptEditorRamCheck);
wrapper.appendChild(checkboxLabel);
wrapper.appendChild(documentationButton);
//Initialize ACE Script editor
var editor = ace.edit('javascript-editor');
editor.getSession().setMode('ace/mode/netscript');
editor.setTheme('ace/theme/monokai');
document.getElementById('javascript-editor').style.fontSize='16px';
editor.setOption("showPrintMargin", false);
/* Script editor options */
//Theme
var themeDropdown = document.getElementById("script-editor-option-theme");
if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
var initialIndex = 2;
for (var i = 0; i < themeDropdown.options.length; ++i) {
if (themeDropdown.options[i].value === _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
initialIndex = i;
break;
}
}
themeDropdown.selectedIndex = initialIndex;
} else {
themeDropdown.selectedIndex = 2;
}
themeDropdown.onchange = function() {
var val = themeDropdown.value;
_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme = val;
var themePath = "ace/theme/" + val.toLowerCase();
editor.setTheme(themePath);
};
themeDropdown.onchange();
//Keybinding
var keybindingDropdown = document.getElementById("script-editor-option-keybinding");
if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
var initialIndex = 0;
for (var i = 0; i < keybindingDropdown.options.length; ++i) {
if (keybindingDropdown.options[i].value === _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
initialIndex = i;
break;
}
}
keybindingDropdown.selectedIndex = initialIndex;
} else {
keybindingDropdown.selectedIndex = 0;
}
keybindingDropdown.onchange = function() {
var val = keybindingDropdown.value;
_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding = val;
editor.setKeyboardHandler(keybindings[val.toLowerCase()]);
};
keybindingDropdown.onchange();
//Highlight Active line
var highlightActiveChkBox = document.getElementById("script-editor-option-highlightactiveline");
highlightActiveChkBox.onchange = function() {
editor.setHighlightActiveLine(highlightActiveChkBox.checked);
};
//Show Invisibles
var showInvisiblesChkBox = document.getElementById("script-editor-option-showinvisibles");
showInvisiblesChkBox.onchange = function() {
editor.setShowInvisibles(showInvisiblesChkBox.checked);
};
//Use Soft Tab
var softTabChkBox = document.getElementById("script-editor-option-usesofttab");
softTabChkBox.onchange = function() {
editor.getSession().setUseSoftTabs(softTabChkBox.checked);
};
//Jshint Maxerr
var maxerr = document.getElementById("script-editor-option-maxerr");
var maxerrLabel = document.getElementById("script-editor-option-maxerror-value-label");
maxerrLabel.innerHTML = maxerr.value;
maxerr.onchange = function() {
editor.getSession().$worker.send("changeOptions", [{maxerr:maxerr.value}]);
maxerrLabel.innerHTML = maxerr.value;
}
//Configure some of the VIM keybindings
ace.config.loadModule('ace/keyboard/vim', function(module) {
var VimApi = module.CodeMirror.Vim;
VimApi.defineEx('write', 'w', function(cm, input) {
saveAndCloseScriptEditor();
});
VimApi.defineEx('quit', 'q', function(cm, input) {
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
});
VimApi.defineEx('xwritequit', 'x', function(cm, input) {
saveAndCloseScriptEditor();
});
VimApi.defineEx('wqwritequit', 'wq', function(cm, input) {
saveAndCloseScriptEditor();
});
});
//Function autocompleter
editor.setOption("enableBasicAutocompletion", true);
var autocompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
if (prefix.length === 0) {callback(null, []); return;}
var words = [];
var fns = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_5__[/* NetscriptFunctions */ "a"])(null);
for (let name in fns) {
if (fns.hasOwnProperty(name)) {
words.push({
name: name,
value: name,
});
//Get functions from namespaces
const namespaces = ["bladeburner", "hacknet", "codingcontract", "gang"];
if (namespaces.includes(name)) {
let namespace = fns[name];
if (typeof namespace !== "object") {continue;}
let namespaceFns = Object.keys(namespace);
for (let i = 0; i < namespaceFns.length; ++i) {
words.push({
name: namespaceFns[i],
value: namespaceFns[i],
});
}
}
}
}
callback(null, words);
},
}
editor.completers = [autocompleter];
}
//Updates RAM usage in script
async function updateScriptEditorContent() {
var filename = document.getElementById("script-editor-filename").value;
if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !isScriptFilename(filename)) {
scriptEditorRamText.innerText = "N/A";
return;
}
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
var codeCopy = code.repeat(1);
var ramUsage = await calculateRamUsage(codeCopy);
if (ramUsage !== -1) {
scriptEditorRamText.innerText = "RAM: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__[/* numeralWrapper */ "a"].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__WEBPACK_IMPORTED_MODULE_9__["Settings"].DisableHotkeys === true) {return;}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].ScriptEditor)) {
//Ctrl + b
if (e.keyCode == 66 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
saveAndCloseScriptEditor();
}
}
});
function beautifyScript() {
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
code = beautify(code, { indent_size: 4 })
editor.setValue(code);
}
function saveAndCloseScriptEditor() {
var filename = document.getElementById("script-editor-filename").value;
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].isRunning && _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialSteps */ "d"].TerminalTypeScript) {
//Make sure filename + code properly follow tutorial
if (filename !== "foodnstuff.script") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["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_15__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!");
return;
}
//Save the script
let s = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer();
for (var i = 0; i < s.scripts.length; i++) {
if (filename == s.scripts[i].filename) {
s.scripts[i].saveScript();
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialNextStep */ "b"])();
}
}
//If the current script does NOT exist, create a new one
let script = new Script();
script.saveScript();
s.scripts.push(script);
return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialNextStep */ "b"])();
}
if (filename == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("You must specify a filename!");
return;
}
if (checkValidFilename(filename) == false) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores");
return;
}
var s = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer();
if (filename === ".fconf") {
try {
Object(_Fconf__WEBPACK_IMPORTED_MODULE_2__[/* parseFconfSettings */ "d"])(code);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])(`Invalid .fconf file: ${e}`);
return;
}
} else if (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();
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
return;
}
}
//If the current script does NOT exist, create a new one
var script = new Script();
script.saveScript();
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_1__["Engine"].loadTerminalContent();
return;
}
}
var textFile = new _TextFile__WEBPACK_IMPORTED_MODULE_11__["TextFile"](filename, code);
s.textFiles.push(textFile);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Invalid filename. Must be either a script (.script) or " +
" or text file (.txt)")
return;
}
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
}
//Checks that the string contains only valid characters for a filename, which are alphanumeric,
// underscores, hyphens, and dots
function checkValidFilename(filename) {
var regex = /^[.a-zA-Z0-9_-]+$/;
if (filename.match(regex)) {
return true;
}
return false;
}
function Script(fn = "", code = "", server = "") {
this.filename = fn;
this.code = code;
this.ramUsage = 0;
this.server = server; //IP of server this script is on
this.module = "";
if (this.code !== "") {this.updateRamUsage();}
};
//Get the script data from the Script Editor and save it to the object
Script.prototype.saveScript = function() {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].ScriptEditor)) {
//Update code and filename
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
this.code = code.replace(/^\s+|\s+$/g, '');
var filename = document.getElementById("script-editor-filename").value;
this.filename = filename;
//Server
this.server = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].currentServer;
//Calculate/update ram usage, execution time, etc.
this.updateRamUsage();
this.module = "";
}
}
//Updates how much RAM the script uses when it is running.
Script.prototype.updateRamUsage = async function() {
var codeCopy = this.code.repeat(1);
var res = await calculateRamUsage(codeCopy);
if (res !== -1) {
this.ramUsage = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__["roundToTwo"])(res);
}
}
// These special strings are used to reference the presence of a given logical
// construct within a user script.
const specialReferenceIF = "__SPECIAL_referenceIf";
const specialReferenceFOR = "__SPECIAL_referenceFor";
const specialReferenceWHILE = "__SPECIAL_referenceWhile";
// The global scope of a script is registered under this key during parsing.
const memCheckGlobalKey = ".__GLOBAL__";
// Calcluates the amount of RAM a script uses. Uses parsing and AST walking only,
// rather than NetscriptEvaluator. This is useful because NetscriptJS code does
// not work under NetscriptEvaluator.
async function parseOnlyRamCalculate(server, code, workerScript) {
try {
// Maps dependent identifiers to their dependencies.
//
// The initial identifier is __SPECIAL_INITIAL_MODULE__.__GLOBAL__.
// It depends on all the functions declared in the module, all the global scopes
// of its imports, and any identifiers referenced in this global scope. Each
// function depends on all the identifiers referenced internally.
// We walk the dependency graph to calculate RAM usage, given that some identifiers
// reference Netscript functions which have a RAM cost.
let dependencyMap = {};
// Scripts we've parsed.
const completedParses = new Set();
// Scripts we've discovered that need to be parsed.
const parseQueue = [];
// Parses a chunk of code with a given module name, and updates parseQueue and dependencyMap.
function parseCode(code, moduleName) {
const result = parseOnlyCalculateDeps(code, moduleName);
completedParses.add(moduleName);
// Add any additional modules to the parse queue;
for (let i = 0; i < result.additionalModules.length; ++i) {
if (!completedParses.has(result.additionalModules[i])) {
parseQueue.push(result.additionalModules[i]);
}
}
// Splice all the references in.
//Spread syntax not supported in edge, use Object.assign instead
//dependencyMap = {...dependencyMap, ...result.dependencyMap};
dependencyMap = Object.assign(dependencyMap, result.dependencyMap);
}
const initialModule = "__SPECIAL_INITIAL_MODULE__";
parseCode(code, initialModule);
while (parseQueue.length > 0) {
// Get the code from the server.
const nextModule = parseQueue.shift();
let code;
if (nextModule.startsWith("https://") || nextModule.startsWith("http://")) {
try {
const module = await eval('import(nextModule)');
code = "";
for (const prop in module) {
if (typeof module[prop] === 'function') {
code += module[prop].toString() + ";\n";
}
}
} catch(e) {
console.error(`Error dynamically importing module from ${nextModule} for RAM calculations: ${e}`);
return -1;
}
} else {
const script = server.getScript(nextModule);
if (!script) return -1; // No such script on the server.
code = script.code;
}
parseCode(code, nextModule);
}
// Finally, walk the reference map and generate a ram cost. The initial set of keys to scan
// are those that start with __SPECIAL_INITIAL_MODULE__.
let ram = _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptBaseRamCost;
const unresolvedRefs = Object.keys(dependencyMap).filter(s => s.startsWith(initialModule));
const resolvedRefs = new Set();
while (unresolvedRefs.length > 0) {
const ref = unresolvedRefs.shift();
// Check if this is one of the special keys, and add the appropriate ram cost if so.
if (ref === "hacknet" && !resolvedRefs.has("hacknet")) {
ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost;
}
if (ref === "document" && !resolvedRefs.has("document")) {
ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptDomRamCost;
}
if (ref === "window" && !resolvedRefs.has("window")) {
ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptDomRamCost;
}
resolvedRefs.add(ref);
if (ref.endsWith(".*")) {
// A prefix reference. We need to find all matching identifiers.
const prefix = ref.slice(0, ref.length - 2);
for (let ident of Object.keys(dependencyMap).filter(k => k.startsWith(prefix))) {
for (let dep of dependencyMap[ident] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
}
}
} else {
// An exact reference. Add all dependencies of this ref.
for (let dep of dependencyMap[ref] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
}
}
// Check if this ident is a function in the workerscript env. If it is, then we need to
// get its RAM cost. We do this by calling it, which works because the running script
// is in checkingRam mode.
//
// TODO it would be simpler to just reference a dictionary.
try {
function applyFuncRam(func) {
if (typeof func === "function") {
try {
let res;
if (func.constructor.name === "AsyncFunction") {
res = 0; // Async functions will always be 0 RAM
} else {
res = func.apply(null, []);
}
if (typeof res === "number") {
return res;
}
return 0;
} catch(e) {
console.log("ERROR applying function: " + e);
return 0;
}
} else {
return 0;
}
}
//Special logic for namespaces (Bladeburner, CodingCOntract)
var func;
if (ref in workerScript.env.vars.bladeburner) {
func = workerScript.env.vars.bladeburner[ref];
} else if (ref in workerScript.env.vars.codingcontract) {
func = workerScript.env.vars.codingcontract[ref];
} else if (ref in workerScript.env.vars.gang) {
func = workerScript.env.vars.gang[ref];
} else {
func = workerScript.env.get(ref);
}
ram += applyFuncRam(func);
} catch (error) {continue;}
}
return ram;
} catch (error) {
// console.info("parse or eval error: ", error);
// This is not unexpected. The user may be editing a script, and it may be in
// a transitory invalid state.
return -1;
}
}
// Parses one script and calculates its ram usage, for the global scope and each function.
// Returns a cost map and a dependencyMap for the module. Returns a reference map to be joined
// onto the main reference map, and a list of modules that need to be parsed.
function parseOnlyCalculateDeps(code, currentModule) {
const ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(code, {sourceType:"module", ecmaVersion: 8});
// Everything from the global scope goes in ".". Everything else goes in ".function", where only
// the outermost layer of functions counts.
const globalKey = currentModule + memCheckGlobalKey;
const dependencyMap = {};
dependencyMap[globalKey] = new Set();
// If we reference this internal name, we're really referencing that external name.
// Filled when we import names from other modules.
let internalToExternal = {};
var additionalModules = [];
// References get added pessimistically. They are added for thisModule.name, name, and for
// any aliases.
function addRef(key, name) {
const s = dependencyMap[key] || (dependencyMap[key] = new Set());
if (name in internalToExternal) {
s.add(internalToExternal[name]);
}
s.add(currentModule + "." + name);
s.add(name); // For builtins like hack.
}
//A list of identifiers that resolve to "native Javascript code"
const objectPrototypeProperties = Object.getOwnPropertyNames(Object.prototype);
// If we discover a dependency identifier, state.key is the dependent identifier.
// walkDeeper is for doing recursive walks of expressions in composites that we handle.
function commonVisitors() {
return {
Identifier: (node, st, walkDeeper) => {
if (objectPrototypeProperties.includes(node.name)) {return;}
addRef(st.key, node.name);
},
WhileStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceWHILE);
node.test && walkDeeper(node.test, st);
node.body && walkDeeper(node.body, st);
},
DoWhileStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceWHILE);
node.test && walkDeeper(node.test, st);
node.body && walkDeeper(node.body, st);
},
ForStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceFOR);
node.init && walkDeeper(node.init, st);
node.test && walkDeeper(node.test, st);
node.update && walkDeeper(node.update, st);
node.body && walkDeeper(node.body, st);
},
IfStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceIF);
node.test && walkDeeper(node.test, st);
node.consequent && walkDeeper(node.consequent, st);
node.alternate && walkDeeper(node.alternate, st);
},
MemberExpression: (node, st, walkDeeper) => {
node.object && walkDeeper(node.object, st);
node.property && walkDeeper(node.property, st);
},
}
}
//Spread syntax not supported in Edge yet, use Object.assign
/*
walk.recursive(ast, {key: globalKey}, {
ImportDeclaration: (node, st, walkDeeper) => {
const importModuleName = node.source.value;
additionalModules.push(importModuleName);
// This module's global scope refers to that module's global scope, no matter how we
// import it.
dependencyMap[st.key].add(importModuleName + memCheckGlobalKey);
for (let i = 0; i < node.specifiers.length; ++i) {
const spec = node.specifiers[i];
if (spec.imported !== undefined && spec.local !== undefined) {
// We depend on specific things.
internalToExternal[spec.local.name] = importModuleName + "." + spec.imported.name;
} else {
// We depend on everything.
dependencyMap[st.key].add(importModuleName + ".*");
}
}
},
FunctionDeclaration: (node, st, walkDeeper) => {
// Don't use walkDeeper, because we are changing the visitor set.
const key = currentModule + "." + node.id.name;
walk.recursive(node, {key: key}, commonVisitors());
},
...commonVisitors()
});
*/
walk.recursive(ast, {key: globalKey}, Object.assign({
ImportDeclaration: (node, st, walkDeeper) => {
const importModuleName = node.source.value;
additionalModules.push(importModuleName);
// This module's global scope refers to that module's global scope, no matter how we
// import it.
dependencyMap[st.key].add(importModuleName + memCheckGlobalKey);
for (let i = 0; i < node.specifiers.length; ++i) {
const spec = node.specifiers[i];
if (spec.imported !== undefined && spec.local !== undefined) {
// We depend on specific things.
internalToExternal[spec.local.name] = importModuleName + "." + spec.imported.name;
} else {
// We depend on everything.
dependencyMap[st.key].add(importModuleName + ".*");
}
}
},
FunctionDeclaration: (node, st, walkDeeper) => {
// Don't use walkDeeper, because we are changing the visitor set.
const key = currentModule + "." + node.id.name;
walk.recursive(node, {key: key}, commonVisitors());
},
}, commonVisitors()));
return {dependencyMap: dependencyMap, additionalModules: additionalModules};
}
async function calculateRamUsage(codeCopy) {
//Create a temporary/mock WorkerScript and an AST from the code
var currServ = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer();
var workerScript = new _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__[/* WorkerScript */ "b"]({
filename:"foo",
scriptRef: {code:""},
args:[]
});
workerScript.checkingRam = true; //Netscript functions will return RAM usage
workerScript.serverIp = currServ.ip;
try {
return await parseOnlyRamCalculate(currServ, codeCopy, workerScript);
} catch (e) {
console.log("Failed to parse ram using new method. Falling back.", e);
}
// Try the old way.
try {
var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(codeCopy, {sourceType:"module"});
} catch(e) {
return -1;
}
//Search through AST, scanning for any 'Identifier' nodes for functions, or While/For/If nodes
var queue = [], ramUsage = _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptBaseRamCost;
var whileUsed = false, forUsed = false, ifUsed = false;
queue.push(ast);
while (queue.length != 0) {
var exp = queue.shift();
switch (exp.type) {
case "ImportDeclaration":
//Gets an array of all imported functions as AST expressions
//and pushes them on the queue.
var res = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__[/* evaluateImport */ "a"])(exp, workerScript, true);
for (var i = 0; i < res.length; ++i) {
queue.push(res[i]);
}
break;
case "BlockStatement":
case "Program":
for (var i = 0; i < exp.body.length; ++i) {
if (exp.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
queue.push(exp.body[i]);
}
}
break;
case "WhileStatement":
if (!whileUsed) {
ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptWhileRamCost;
whileUsed = true;
}
break;
case "ForStatement":
if (!forUsed) {
ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost;
forUsed = true;
}
break;
case "IfStatement":
if (!ifUsed) {
ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost;
ifUsed = true;
}
break;
case "Identifier":
if (exp.name in workerScript.env.vars) {
var func = workerScript.env.get(exp.name);
if (typeof func === "function") {
try {
var res = func.apply(null, []);
if (typeof res === "number") {
ramUsage += res;
}
} catch(e) {
console.log("ERROR applying function: " + e);
}
}
}
break;
default:
break;
}
for (var prop in exp) {
if (exp.hasOwnProperty(prop)) {
if (exp[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
queue.push(exp[prop]);
}
}
}
}
//Special case: hacknetnodes array
if (codeCopy.includes("hacknet")) {
ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost;
}
return ramUsage;
}
Script.prototype.download = function() {
var filename = this.filename + ".js";
var file = new Blob([this.code], {type: 'text/plain'});
if (window.navigator.msSaveOrOpenBlob) {// IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
} else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
Script.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("Script", this);
}
Script.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(Script, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.Script = Script;
//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 count = 0;
var total = 0;
let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1);
if (skipScriptLoad) {console.log("Skipping the load of any scripts during startup");}
for (var property in _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"]) {
if (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"].hasOwnProperty(property)) {
var server = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][property];
//Reset each server's RAM usage to 0
server.ramUsed = 0;
//Reset modules on all scripts
for (var i = 0; i < server.scripts.length; ++i) {
server.scripts[i].module = "";
}
if (skipScriptLoad) {
//Start game with no scripts
server.runningScripts.length = 0;
} else {
for (var j = 0; j < server.runningScripts.length; ++j) {
count++;
server.runningScripts[j].scriptRef.module = "";
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__[/* addWorkerScript */ "c"])(server.runningScripts[j], server);
//Offline production
total += scriptCalculateOfflineProduction(server.runningScripts[j]);
}
}
}
}
return total;
console.log("Loaded " + count.toString() + " running scripts");
}
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_7__[/* Player */ "a"].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__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][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__WEBPACK_IMPORTED_MODULE_8__[/* processSingleServerGrowth */ "k"])(serv, timesGrown * 450);
runningScriptObj.log(serv.hostname + " grown by " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__[/* numeralWrapper */ "a"].format(growth * 100 - 100, '0.000000%') + " from grow() calls made while offline");
}
}
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__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][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_7__[/* Player */ "a"].gainMoney(production);
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_7__[/* Player */ "a"].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__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][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_0__["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__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][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_0__["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_17__["compareArrays"])(server.runningScripts[i].args, args)) {
return server.runningScripts[i];
}
}
return null;
}
function RunningScript(script, args) {
if (script == null || script == undefined) {return;}
this.filename = script.filename;
this.args = args;
this.scriptRef = script;
this.server = script.server; //IP Address only
this.logs = []; //Script logging. Array of strings, with each element being a log entry
this.logUpd = false;
//Stats to display on the Scripts menu, and used to determine offline progress
this.offlineRunningTime = 0.01; //Seconds
this.offlineMoneyMade = 0;
this.offlineExpGained = 0;
this.onlineRunningTime = 0.01; //Seconds
this.onlineMoneyMade = 0;
this.onlineExpGained = 0;
this.threads = 1;
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
RunningScript.prototype.log = function(txt) {
if (this.logs.length > _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].MaxLogCapacity) {
//Delete first element and add new log entry to the end.
//TODO Eventually it might be better to replace this with circular array
//to improve performance
this.logs.shift();
}
let logEntry = txt;
if (_Fconf__WEBPACK_IMPORTED_MODULE_2__[/* FconfSettings */ "a"].ENABLE_TIMESTAMPS) {
logEntry = "[" + Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__["getTimestamp"])() + "] " + logEntry;
}
this.logs.push(logEntry);
this.logUpd = true;
}
RunningScript.prototype.displayLog = function() {
for (var i = 0; i < this.logs.length; ++i) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__["post"])(this.logs[i]);
}
}
RunningScript.prototype.clearLog = function() {
this.logs.length = 0;
}
//Update the moneyStolen and numTimesHack maps when hacking
RunningScript.prototype.recordHack = function(serverIp, moneyGained, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][0] += moneyGained;
this.dataMap[serverIp][1] += n;
}
//Update the grow map when calling grow()
RunningScript.prototype.recordGrow = function(serverIp, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][2] += n;
}
//Update the weaken map when calling weaken() {
RunningScript.prototype.recordWeaken = function(serverIp, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][3] += n;
}
RunningScript.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("RunningScript", this);
}
RunningScript.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(RunningScript, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.RunningScript = RunningScript;
//Creates an object that creates a map/dictionary with the IP of each existing server as
//a key. Initializes every key with a specified value that can either by a number or an array
function AllServersMap(arr=false, filterOwned=false) {
for (var ip in _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"]) {
if (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"].hasOwnProperty(ip)) {
if (filterOwned && (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip].purchasedByPlayer || _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip].hostname === "home")) {
continue;
}
if (arr) {
this[ip] = [0, 0, 0, 0];
} else {
this[ip] = 0;
}
}
}
}
AllServersMap.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("AllServersMap", this);
}
AllServersMap.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(AllServersMap, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.AllServersMap = AllServersMap;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 29 */
/*!****************************!*\
!*** ./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 _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1);
/* 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 */ 8);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction/Faction */ 54);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./RedPill */ 55);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/createProgressBarText */ 79);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 61);
/* 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_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/appendLineBreaks */ 59);
/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/helpers/clearObject */ 74);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 83);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/uiHelpers/removeElement */ 67);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27__);
var CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"];
var CyclesPerSecond = 5; //Game cycle is 200 ms
var StaminaGainPerSecond = 0.0085;
var BaseStaminaLoss = 0.285; //Base stamina loss per action. Increased based on difficulty
var MaxStaminaToGainFactor = 70000; //Max Stamina is divided by this to get bonus stamina gain
var 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
var DiffMultExponentialFactor = 0.28;
var DiffMultLinearFactor = 650;
var EffAgiLinearFactor = 40e3;
var EffDexLinearFactor = 40e3;
var EffAgiExponentialFactor = 0.032;
var EffDexExponentialFactor = 0.03;
var BaseRecruitmentTimeNeeded = 300; //Base time needed (s) to complete a Recruitment action
var PopulationThreshold = 1e9; //Population at which success rates start being affected
var ChaosThreshold = 50; //City chaos level after which it starts making tasks harder
var BaseStatGain = 1; //Base stat gain per second
var BaseIntGain = 0.001; //Base intelligence stat gain
var ActionCountGrowthPeriod = 300; //Time (s) it takes for action count to grow by its specified value
var RankToFactionRepFactor = 2; //Delta Faction Rep = this * Delta Rank
var RankNeededForFaction = 25;
var ContractSuccessesPerLevel = 3.5; //How many successes you need to level up a contract
var OperationSuccessesPerLevel = 3; //How many successes you need to level up an op
var RanksPerSkillPoint = 4; //How many ranks needed to get 1 Skill Point
var ContractBaseMoneyGain = 50e3; //Base Money Gained per contract
//DOM related variables
var ActiveActionCssClass = "bladeburner-active-action";
//Console related stuff
var consoleHistoryIndex = 0;
var consoleHelpText = {
helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.<br><br>" +
"automate [var] [val] [hi/low] Configure simple automation for Bladeburner tasks<br>" +
"clear/cls Clear the console<br>" +
"help [cmd] Display this help text, or help text for a specific command<br>" +
"log [en/dis] [type] Enable or disable logging for events and actions<br>" +
"skill [action] [name] Level or display info about your Bladeburner skills<br>" +
"start [type] [name] Start a Bladeburner action/task<br>" +
"stop Stops your current Bladeburner action/task<br>",
automate:"automate [var] [val] [hi/low]<br><br>" +
"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.<br><br>" +
"automate status - Check the current status of your automation and get a brief description of what it'll do<br>" +
"automate en - Enable the automation feature<br>" +
"automate dis - Disable the automation feature<br><br>" +
"There are four properties that must be set for this automation to work properly. Here is how to set them:<br><br>" +
"automate stamina 100 high<br>" +
"automate contract Tracking high<br>" +
"automate stamina 50 low<br>" +
'automate general "Field Analysis" low<br><br>' +
"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<br><br>Clears the console",
cls:"cls<br><br>Clears the console",
help:"help [command]<br><br>" +
"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:<br><br>" +
"help automate<br><br>" +
"will display specific information about using the automate console command",
log:"log [en/dis] [type]<br><br>" +
"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:<br><br>" +
"[general, contracts, ops, blackops, events]<br><br>" +
"The logging for these categories can be enabled or disabled like so:<br><br>" +
"log dis contracts - Disables logging that occurs when contracts are completed<br>" +
"log en contracts - Enables logging that occurs when contracts are completed<br>" +
"log dis events - Disables logging for Bladeburner random events<br><br>" +
"Logging can be universally enabled/disabled using the 'all' keyword:<br><br>" +
"log dis all<br>" +
"log en all",
skill:"skill [action] [name]<br><br>" +
"Level or display information about your skills.<br><br>" +
"To display information about all of your skills and your multipliers, use:<br><br>" +
"skill list<br><br>" +
"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:<br><br>" +
"skill list Reaper<br>" +
'skill list "Digital Observer"<br><br>' +
"This console command can also be used to level up skills:<br><br>" +
"skill level [skill name]",
start:"start [type] [name]<br><br>" +
"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:<br><br>" +
"[general, contract, op, blackop]<br><br>" +
"Examples:<br><br>" +
'start contract Tracking<br>' +
'start op "Undercover Operation"<br>',
stop:"stop<br><br>" +
"Stop your current action and go idle",
}
//Keypresses for Console
$(document).keydown(function(event) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Bladeburner)) {
//if (DomElems.consoleInput && !event.ctrlKey && !event.shiftKey && !event.altKey) {
// DomElems.consoleInput.focus();
//}
if (!(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner instanceof Bladeburner)) {return;}
let consoleHistory = _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner.consoleHistory;
//NOTE: Keycodes imported from Terminal.js
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11__["KEY"].ENTER) {
event.preventDefault();
var command = DomElems.consoleInput.value;
if (command.length > 0) {
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner.postToConsole("> " + command);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner.resetConsoleInput();
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner.executeConsoleCommands(command);
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11__["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;
setTimeout(function(){DomElems.consoleInput.selectionStart = DomElems.consoleInput.selectionEnd = 10000; }, 0);
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_11__["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 : _Locations__WEBPACK_IMPORTED_MODULE_7__["Locations"].Sector12;
//Synthoid population and estimate
this.pop = params.pop ? params.pop : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["getRandomInt"])(800e6, 1.2*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_24__["getRandomInt"])(5, 100);
this.commsEst = this.comms + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_15__["Generic_toJSON"])("City", this);
}
City.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(City, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["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;}
//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)) * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].BladeburnerSkillCost);
}
var Skills = {};
var SkillNames = {
BladesIntuition: "Blade's Intuition",
Reaper: "Reaper",
Cloak: "Cloak",
Marksman: "Marksman",
WeaponProficiency: "Weapon Proficiency",
Overclock: "Overclock",
EvasiveSystem: "Evasive System",
ShortCircuit: "Short-Circuit",
DigitalObserver: "Digital Observer",
Datamancer: "Datamancer",
Tracer: "Tracer",
CybersEdge: "Cyber's Edge"
}
//Base Class for Contracts, Operations, and BlackOps
function Action(params={}) {
this.name = params.name ? params.name : "";
this.desc = params.desc ? params.desc : "";
//Difficulty scales with level
//Exact formula is not set in stone
//Initial design: baseDifficulty * (difficultyFac ^ level)?
//difficulty Fac is slightly greater than 1
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_24__["getRandomInt"])(1e3, 25e3);
this.countGrowth = params.countGrowth ? params.countGrowth : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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
var sum = 0;
for (var 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)
var defaultDecays = {hack:0.9,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.9,int:0.9};
this.decays = params.decays ? params.decays : defaultDecays;
for (var decay in this.decays) {
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 */ "a"].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 *= (city.popEst / PopulationThreshold);
} else {
competence *= (city.pop / PopulationThreshold);
}
//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 */ "a"].bladeburner_success_chance_mult;
if (isNaN(competence)) {throw new Error("Competence calculated as NaN in Action.getSuccessChance()");}
return Math.min(1, competence / difficulty);
}
//Tests for success. Should be called when an action has completed
// @inst - Bladeburner Object
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 */ "a"].agility * inst.skillMultipliers.effAgi;
var effDexterity = _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].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_15__["Generic_toJSON"])("Action", this);
}
Action.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(Action, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Reviver"].constructors.Action = Action;
var GeneralActions = {}; //Training, Field Analysis, Recruitment, etc.
//Action Identifier
var ActionTypes = Object.freeze({
"Idle": 1,
"Contract": 2,
"Operation": 3,
"BlackOp": 4,
"BlackOperation": 4,
"Training": 5,
"Recruitment": 6,
"FieldAnalysis": 7,
"Field Analysis": 7
});
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_15__["Generic_toJSON"])("ActionIdentifier", this);
}
ActionIdentifier.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(ActionIdentifier, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["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_15__["Generic_toJSON"])("Contract", this);
}
Contract.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(Contract, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["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_15__["Generic_toJSON"])("Operation", this);
}
Operation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(Operation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["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_15__["Generic_toJSON"])("BlackOperation", this);
}
BlackOperation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(BlackOperation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Reviver"].constructors.BlackOperation = BlackOperation;
var 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_24__["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 = _Locations__WEBPACK_IMPORTED_MODULE_7__["Locations"].Sector12;
//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_5__["Factions"]["Bladeburners"];
if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__[/* joinFaction */ "c"])(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.<br><br>" +
"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_24__["getRandomInt"])(25, 500), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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.<br><br>" +
"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_24__["getRandomInt"])(5, 500), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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.<br><br>" +
"Successfully copmleting 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_24__["getRandomInt"])(5, 500), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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.<br><br>Successful " +
"Investigation ops will increase the accuracy of your " +
"synthoid data.<br><br>" +
"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_24__["getRandomInt"])(1, 250), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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.<br><br>" +
"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_24__["getRandomInt"])(1, 250), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(1, 300), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(1, 200), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(1, 250), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(1, 200), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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() {
//Extreme 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 */ "a"].bitNodeN);
}
//If the Player starts doing some other actions, set action to idle and alert
if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].BladesSimulacrum].owned === false && _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].isWorking) {
if (this.action.type !== ActionTypes["Idle"]) {
let msg = "Your Bladeburner action was cancelled because you started doing something else.";
if (this.automateEnabled) {
msg += `<br><br>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_13__["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_24__["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_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Bladeburner)) {
this.updateContent();
}
}
}
Bladeburner.prototype.calculateMaxStamina = function() {
var effAgility = _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].agility * this.skillMultipliers.effAgi;
var maxStamina = (Math.pow(effAgility, 0.8) + this.staminaBonus);
maxStamina *= this.skillMultipliers.stamina;
maxStamina *= _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].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 */ "a"].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 */ "a"].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_5__["factionExists"])(bladeburnersFactionName)) {
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][bladeburnersFactionName];
if (!(bladeburnerFac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_4__["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 */ "a"].faction_rep_mult * favorBonus);
}
}
//Gain skill points. You get 1 every 4 ranks
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,
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_22__[/* exceptionAlert */ "a"])(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_22__[/* exceptionAlert */ "a"])(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_22__[/* exceptionAlert */ "a"])(e);
}
break;
case ActionTypes["Training"]:
this.actionTimeToComplete = 30;
break;
case ActionTypes["Recruitment"]:
this.actionTimeToComplete = this.getRecruitmentTime();
break;
case ActionTypes["FieldAnalysis"]:
case ActionTypes["Field Analysis"]:
this.actionTimeToComplete = 30;
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;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainMoney(moneyGain);
}
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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].BladeburnerRank, 10);
this.changeRank(gain);
if (isOperation && this.logging.ops) {
this.log(action.name + " successfully completed! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(gain, 3) + " rank");
} else if (!isOperation && this.logging.contracts) {
this.log(action.name + " contract successfully completed! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(gain, 3) + " rank and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].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 */ "a"].takeDamage(damage)) {
++this.numHosp;
this.moneyLost += (_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].HospitalCostPerHp * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].max_hp);
}
}
var logLossText = "";
if (loss > 0) {logLossText += "Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(loss, 3) + " rank.";}
if (damage > 0) {logLossText += "Took " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_22__[/* exceptionAlert */ "a"])(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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["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 */ "a"].bitNodeN);
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Bladeburner)) {
this.createActionAndSkillsContent();
}
if (this.logging.blackops) {
this.log(action.name + " successful! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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 */ "a"].takeDamage(damage)) {
++this.numHosp;
this.moneyLost += (_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].HospitalCostPerHp * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].max_hp);
}
}
teamLossMax = Math.floor(teamCount);
if (this.logging.blackops) {
this.log(action.name + " failed! Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(rankLoss, 1) + " rank and took " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_24__["getRandomInt"])(1, teamLossMax);
this.teamSize -= losses;
this.teamLost += losses;
if (this.logging.blackops) {
this.log("You lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(losses, 0) + " team members during " + action.name);
}
}
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_22__[/* exceptionAlert */ "a"])(e);
}
break;
case ActionTypes["Training"]:
this.stamina -= (0.5 * BaseStaminaLoss);
var strExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].strength_exp_mult,
defExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].defense_exp_mult,
dexExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].dexterity_exp_mult,
agiExpGain = 30 * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].agility_exp_mult,
staminaGain = 0.04 * this.skillMultipliers.stamina;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainStrengthExp(strExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainDefenseExp(defExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainDexterityExp(dexExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainAgilityExp(agiExpGain);
this.staminaBonus += (staminaGain);
if (this.logging.general) {
this.log("Training completed. Gained: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(strExpGain, 1) + " str exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(defExpGain, 1) + " def exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(dexExpGain, 1) + " dex exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(agiExpGain, 1) + " agi exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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 */ "a"].hacking_skill, 0.3) +
0.04 * Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].intelligence, 0.9) +
0.02 * Math.pow(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].charisma, 0.3);
eff *= _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].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 */ "a"].hacking_exp_mult,
charismaExpGain = 20 * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].charisma_exp_mult;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainHackingExp(hackingExpGain);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainIntelligenceExp(BaseIntGain);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainCharismaExp(charismaExpGain);
this.changeRank(0.1 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["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_23__["formatNumber"])(hackingExpGain, 1) + " hacking exp, and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(charismaExpGain, 1) + " charisma exp");
}
this.startAction(this.action); //Repeat action
break;
case ActionTypes["Recruitment"]:
var successChance = this.getRecruitmentSuccessChance();
console.log("Bladeburner recruitment success chance: " + successChance);
if (Math.random() < successChance) {
var expGain = 2 * BaseStatGain * this.actionTimeToComplete;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainCharismaExp(expGain);
++this.teamSize;
if (this.logging.general) {
this.log("Successfully recruited a team member! Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(expGain, 1) + " charisma exp");
}
} else {
var expGain = BaseStatGain * this.actionTimeToComplete;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainCharismaExp(expGain);
if (this.logging.general) {
this.log("Failed to recruit a team member. Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(expGain, 1) + " charisma exp");
}
}
this.startAction(this.action); //Repeat action
break;
default:
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_24__["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_24__["getRandomInt"])(0, max);
this.teamSize -= losses;
this.teamLost += losses;
if (this.logging.ops && losses > 0) {
this.log("Lost " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_24__["getRandomInt"])(-3, -1);
city.changePopulationByPercentage(change, {nonZero:true});
}
city.changeChaosByPercentage(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(-3, -1));
break;
case "Assassination":
if (success) {
city.changePopulationByCount(-1, {estChange:-1});
}
city.changeChaosByPercentage(Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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 */ "a"].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 */ "a"].charisma, 0.45) / (this.teamSize + 1);
}
//Process stat gains from Contracts, Operations, and Black Operations
//@action(Action obj) - Derived action class
//@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;
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainHackingExp(unweightedGain * action.weights.hack * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].hacking_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainStrengthExp(unweightedGain * action.weights.str * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].strength_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainDefenseExp(unweightedGain * action.weights.def * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].defense_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainDexterityExp(unweightedGain * action.weights.dex * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].dexterity_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainAgilityExp(unweightedGain * action.weights.agi * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].agility_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainCharismaExp(unweightedGain * action.weights.cha * _Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].charisma_exp_mult);
_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].gainIntelligenceExp(unweightedIntGain * action.weights.int);
}
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_24__["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_24__["getRandomInt"])(0, 5)];
while (destCityName === sourceCityName) {
destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["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_24__["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_24__["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_24__["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_24__["getRandomInt"])(5, 10) / 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_24__["getRandomInt"])(5, 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");
}
}
//20% 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_24__["getRandomInt"])(0, 5)];
while (destCityName === sourceCityName) {
destCityName = CityNames[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["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_24__["getRandomInt"])(3, 15) / 100;
if (rand < 0.05 && sourceCity.comms > 0) { //5% chance for community migration
percentage *= Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_24__["getRandomInt"])(2, 4); //Migration increases population change
--sourceCity.comms;
++destCity.comms;
}
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
destCity.pop += count;
}
var 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_19__["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_19__["createElement"])("div", {
height:"60%", display:"block", position:"relative",
});
//Overview and Action/Skill pane
DomElems.overviewDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("div", {
width:"30%", display:"inline-block", border:"1px solid white",
});
DomElems.actionAndSkillsDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["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_19__["createElement"])("table", {class:"bladeburner-console-table"});
DomElems.consoleInputRow = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("tr", {class:"bladeburner-console-input-row", id:"bladeubrner-console-input-row"});
DomElems.consoleInputCell = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("td", {class:"bladeburner-console-input-cell"});
DomElems.consoleInputHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("pre", {innerText:"> "});
DomElems.consoleInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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);
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_14__["removeChildrenFromElement"])(DomElems.bladeburnerDiv);
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_26__["removeElement"])(DomElems.bladeburnerDiv);
}
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["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_19__["createElement"])("p", {
innerText:"Rank: ",
display:"inline-block",
tooltip:"Your rank within the Bladeburner division",
});
DomElems.overviewStamina = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
display:"inline-block",
});
DomElems.overviewStaminaHelpTip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("div", {
class:"help-tip",
innerText:"?",
clickListener: ()=> {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Performing actions will use up your stamina.<br><br>" +
"Your max stamina is determined primarily by your agility stat.<br><br>" +
"Your stamina gain rate is determined by both your agility and your " +
"max stamina. Higher max stamina leads to a higher gain rate.<br><br>" +
"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).<br><br>" +
"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_19__["createElement"])("p", {
display:"block",
});
DomElems.overviewEstPop = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("div", {
innerText:"?", class:"help-tip",
clickListener:()=>{
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["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.<br><br>" +
"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.<br><br>" +
"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_19__["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_19__["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_19__["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_19__["createElement"])("p", {display:"block"});
DomElems.overviewAugSuccessMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {display:"block"});
DomElems.overviewAugMaxStaminaMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {display:"block"});
DomElems.overviewAugStaminaGainMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {display:"block"});
DomElems.overviewAugAnalysisMult = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {display:"block"});
DomElems.overviewDiv.appendChild(DomElems.overviewRank);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__["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_17__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewEstComms);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(DomElems.overviewChaos);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__["appendLineBreaks"])(DomElems.overviewDiv, 2);
DomElems.overviewDiv.appendChild(DomElems.overviewBonusTime);
DomElems.overviewDiv.appendChild(DomElems.overviewSkillPoints);
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__["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_17__["appendLineBreaks"])(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("a", { //Cancel Button
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27__["removeElementById"])(popupId); return false;
}
}))
popupArguments.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["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_27__["removeElementById"])(popupId);
inst.updateOverviewContent();
return false;
}
}));
})(this, i);
}
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20__["createPopup"])(popupId, popupArguments);
}
}));
//Faction button
const bladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["factionExists"])(bladeburnersFactionName)) {
var bladeburnerFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][bladeburnersFactionName];
if (!(bladeburnerFac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_4__["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_19__["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_3__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__[/* displayFactionContent */ "a"])(bladeburnersFactionName);
} else {
if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__[/* joinFaction */ "c"])(bladeburnerFac);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Congratulations! You were accepted into the Bladeburners faction");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(DomElems.overviewDiv);
this.createOverviewContent();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You need a rank of 25 to join the Bladeburners Faction!")
}
}
return false;
}
}));
}
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("br"));
DomElems.overviewDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("br"));
this.updateOverviewContent();
}
Bladeburner.prototype.createActionAndSkillsContent = function() {
if (DomElems.currentTab == null) {DomElems.currentTab = "general";}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(DomElems.actionAndSkillsDiv);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["clearObject"])(DomElems.generalActions);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["clearObject"])(DomElems.contracts);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["clearObject"])(DomElems.operations);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["clearObject"])(DomElems.blackops);
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_18__["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_19__["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_19__["createElement"])("p", {
display:"block", margin:"4px", padding:"4px"
});
//List for actions/skills
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(DomElems.actionsAndSkillsList);
DomElems.actionsAndSkillsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["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.<br><br>" +
"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_19__["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.<br><br>" +
"Operations can affect the chaos level and Synthoid population of your " +
"current city. The exact effects vary between different Operations.<br><br>" +
"For operations, you can use a team. You must first recruit team members. " +
"Having a larger team will improves your chances of success.<br><br>" +
"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_19__["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.<br><br>" +
"<b>Your ultimate goal to climb through the ranks of Bladeburners is to complete " +
"all of the Black Ops.</b><br><br>" +
"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 = 0; i < blackops.length; ++i) {
DomElems.blackops[blackops[i].name] = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("div", {
class:"bladeburner-action", name:blackops[i].name
});
DomElems.actionsAndSkillsList.appendChild(DomElems.blackops[blackops[i].name]);
if (this.blackops[[blackops[i].name]] == null) {break;} //Can't be found in completed blackops
}
}
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.<br><br>" +
"Note that when upgrading a skill, the benefit for that skill is additive. " +
"However, the effects of different skills with each other is multiplicative.<br><br>"
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_23__["formatNumber"])(mult, 3);
switch(multKeys[i]) {
case "successChanceAll":
DomElems.actionsAndSkillsDesc.innerHTML += "Total Success Chance: x" + mult + "<br>";
break;
case "successChanceStealth":
DomElems.actionsAndSkillsDesc.innerHTML += "Stealth Success Chance: x" + mult + "<br>";
break;
case "successChanceKill":
DomElems.actionsAndSkillsDesc.innerHTML += "Retirement Success Chance: x" + mult + "<br>";
break;
case "successChanceContract":
DomElems.actionsAndSkillsDesc.innerHTML += "Contract Success Chance: x" + mult + "<br>";
break;
case "successChanceOperation":
DomElems.actionsAndSkillsDesc.innerHTML += "Operation Success Chance: x" + mult + "<br>";
break;
case "successChanceEstimate":
DomElems.actionsAndSkillsDesc.innerHTML += "Synthoid Data Estimate: x" + mult + "<br>";
break;
case "actionTime":
DomElems.actionsAndSkillsDesc.innerHTML += "Action Time: x" + mult + "<br>";
break;
case "effHack":
DomElems.actionsAndSkillsDesc.innerHTML += "Hacking Skill: x" + mult + "<br>";
break;
case "effStr":
DomElems.actionsAndSkillsDesc.innerHTML += "Strength: x" + mult + "<br>";
break;
case "effDef":
DomElems.actionsAndSkillsDesc.innerHTML += "Defense: x" + mult + "<br>";
break;
case "effDex":
DomElems.actionsAndSkillsDesc.innerHTML += "Dexterity: x" + mult + "<br>";
break;
case "effAgi":
DomElems.actionsAndSkillsDesc.innerHTML += "Agility: x" + mult + "<br>";
break;
case "effCha":
DomElems.actionsAndSkillsDesc.innerHTML += "Charisma: x" + mult + "<br>";
break;
case "effInt":
DomElems.actionsAndSkillsDesc.innerHTML += "Intelligence: x" + mult + "<br>";
break;
case "stamina":
DomElems.actionsAndSkillsDesc.innerHTML += "Stamina: x" + mult + "<br>";
break;
case "weaponAbility":
//DomElems.actionsAndSkillsDesc.innerHTML +=
break;
case "gunAbility":
//DomElems.actionsAndSkillsDesc.innerHTML
break;
default:
console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]);
break;
}
}
}
//Skill Points
DomElems.skillPointsDisplay = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
innerHTML:"<br><strong>Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.skillPoints, 0) + "</strong>"
});
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_19__["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_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Bladeburner)) {return;}
DomElems.overviewRank.childNodes[0].nodeValue = "Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.rank, 2);
DomElems.overviewStamina.innerText = "Stamina: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.stamina, 3) + " / " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.maxStamina, 3);
DomElems.overviewGen1.innerHTML =
"Stamina Penalty: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])((1-this.calculateStaminaPenalty())*100, 1) + "%<br><br>" +
"Team Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.teamSize, 0) + "<br>" +
"Team Members Lost: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.teamLost, 0) + "<br><br>" +
"Num Times Hospitalized: " + this.numHosp + "<br>" +
"Money Lost From Hospitalizations: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(this.moneyLost, "$0.000a") + "<br><br>" +
"Current City: " + this.city + "<br>";
DomElems.overviewEstPop.childNodes[0].nodeValue = "Est. Synthoid Population: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(this.getCurrentCity().popEst, "0.000a");
DomElems.overviewEstComms.childNodes[0].nodeValue = "Est. Synthoid Communities: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.getCurrentCity().comms, 0);
DomElems.overviewChaos.childNodes[0].nodeValue = "City Chaos: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.getCurrentCity().chaos);
DomElems.overviewSkillPoints.innerText = "Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_23__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner_success_chance_mult*100, 1) + "%";
DomElems.overviewAugMaxStaminaMult.innerText = "Aug. Max Stamina Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner_max_stamina_mult*100, 1) + "%";
DomElems.overviewAugStaminaGainMult.innerText = "Aug. Stamina Gain Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].bladeburner_stamina_gain_mult*100, 1) + "%";
DomElems.overviewAugAnalysisMult.innerText = "Aug. Field Analysis Mult: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_8__[/* Player */ "a"].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 = "<br><strong>Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.skillPoints, 0) + "</strong>";
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_14__["removeChildrenFromElement"])(el);
var isActive = el.classList.contains(ActiveActionCssClass);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("h2", { //Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.actionTimeCurrent, 0) + " / " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["createElement"])("p", {
display:"block",
innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__["createProgressBarText"])({progress:progress})
}));
} else {
//Start button
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("pre", { //Info
innerHTML:action.desc, display:"inline-block"
}));
}
Bladeburner.prototype.updateContractsUIElement = function(el, action) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(el);
var isActive = el.classList.contains(ActiveActionCssClass);
var estimatedSuccessChance = action.getSuccessChance(this, {est:true});
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("h2", { //Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.actionTimeCurrent, 0) + " / " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["createElement"])("p", {
display:"block",
innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__["createProgressBarText"])({progress:progress})
}));
} else { //Start button
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("a", {
class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"&uarr;",
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_19__["createElement"])("a", {
class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"&darr;",
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_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("pre", { //Info
display:"inline-block",
innerHTML:action.desc + "\n\n" +
"Estimated success chance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" +
"Time Required (s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["createElement"])("br"));
var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox";
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("label", {
for:autolevelCheckboxId, innerText:"Autolevel",color:"white",
tooltip:"Automatically increase contract level when possible"
}));
var autolevelCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("input", {
type:"checkbox", id:autolevelCheckboxId, margin:"4px",
checked:action.autoLevel,
changeListener:()=>{
action.autoLevel = autolevelCheckbox.checked;
}
});
el.appendChild(autolevelCheckbox);
}
Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(el);
var isActive = el.classList.contains(ActiveActionCssClass);
var estimatedSuccessChance = action.getSuccessChance(this, {est:true});
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("h2", { //Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.actionTimeCurrent, 0) + " / " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["createElement"])("p", {
display:"block",
innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__["createProgressBarText"])({progress:progress})
}));
} else { //Start button and set Team Size button
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("a", {
innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["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_19__["createElement"])("input", {
type:"number", placeholder: "Team Members"
});
var setBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_13__["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_27__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("a", {
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20__["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_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("a", {
class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"&uarr;",
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_19__["createElement"])("a", {
class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"&darr;",
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_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("pre", {
display:"inline-block",
innerHTML:action.desc + "\n\n" +
"Estimated success chance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" +
"Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(actionTime, 1) + "\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_19__["createElement"])("br"));
var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox";
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("label", {
for:autolevelCheckboxId, innerText:"Autolevel",color:"white",
tooltip:"Automatically increase operation level when possible"
}));
var autolevelCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("input", {
type:"checkbox", id:autolevelCheckboxId, margin:"4px",
checked:action.autoLevel,
changeListener:()=>{
action.autoLevel = autolevelCheckbox.checked;
}
});
el.appendChild(autolevelCheckbox);
}
Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["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_19__["createElement"])("h2", {
innerText:action.name + " (COMPLETED)", display:"block",
}));
return;
}
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("h2", { //Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(this.actionTimeCurrent, 0) + " / " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["createElement"])("p", {
display:"block",
innerText:Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_12__["createProgressBarText"])({progress:progress})
}));
} else {
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_19__["createElement"])("a", { //Set Team Size Button
innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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_19__["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_19__["createElement"])("input", {
type:"number", placeholder: "Team Members"
});
var setBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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_13__["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_27__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("a", {
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_27__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_20__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]);
}
}));
}
//Info
Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_17__["appendLineBreaks"])(el, 2);
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
display:"inline-block",
innerHTML:"<br>" + action.desc + "<br><br>",
}));
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
display:"block", color:hasReqdRank ? "white" : "red",
innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(action.reqdRank, 0) + "<br>"
}));
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
display:"inline-block",
innerHTML:"Estimated Success Chance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" +
"Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(actionTime, 1),
}))
}
Bladeburner.prototype.updateSkillsUIElement = function(el, skill) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["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_19__["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_19__["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_17__["appendLineBreaks"])(el, 2);
if (maxLvl) {
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
color:"red", display:"block",
innerText:"MAX LEVEL"
}));
} else {
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["createElement"])("p", {
display:"block",
innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["formatNumber"])(pointCost, 0),
}));
}
el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_19__["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('<tr><td class="bladeburner-console-line" style="color: var(--my-font-color); white-space:pre-wrap;">' + input + '</td></tr>');
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_25__["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_22__[/* exceptionAlert */ "a"])(e);
}
}
//A single 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
var args = [];
var start = 0, i = 0;
while (i < command.length) {
var c = command.charAt(i);
if (c === '"') {
var 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.parseCommandArguments 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_23__["formatNumber"])(this.automateThreshLow, 0) +
", you will automatically switch to " + this.automateActionLow.name +
". When your stamina recovers to " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["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("<br>");
}
}
}
}
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_23__["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_23__["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":
//DomElems.actionsAndSkillsDesc.innerHTML +=
break;
case "gunAbility":
//DomElems.actionsAndSkillsDesc.innerHTML
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_23__["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_23__["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;
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.scriptRef.log("Starting bladeburner action with type " + type + " and name " + name);
}
return true;
} catch(e) {
this.resetAction();
workerScript.scriptRef.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_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["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_5__["Factions"]["Bladeburners"];
if (bladeburnerFac.isMember) {
return true;
} else if (this.rank >= RankNeededForFaction) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__[/* joinFaction */ "c"])(bladeburnerFac);
if (workerScript.shouldLog("joinBladeburnerFaction")) {
workerScript.log("Joined Bladeburners Faction");
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Bladeburner)) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["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_15__["Generic_toJSON"])("Bladeburner", this);
}
Bladeburner.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(Bladeburner, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["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:5, costInc:2,
successChanceAll:3
});
Skills[SkillNames.Reaper] = new Skill({
name:SkillNames.Reaper,
desc:"Each level of this skill increases your " +
"effective combat stats for Bladeburner actions by 3%",
baseCost:3, costInc:2,
effStr:3, effDef:3, effDex:3, effAgi: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:3, costInc:1,
successChanceStealth:5.5
});
//TODO Marksman
//TODO Weapon Proficiency
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: 95)",
baseCost:5, costInc:1.1, maxLvl:95,
actionTime:1
});
Skills[SkillNames.EvasiveSystem] = new Skill({
name:SkillNames.EvasiveSystem,
desc:"Each level of this skill increases your effective " +
"dexterity and agility for Bladeburner actions by 5%",
baseCost:2, costInc: 1,
effDex:5, effAgi:5
});
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:3, costInc:2,
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:5, costInc:2,
successChanceOperation: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.Tracer] = new Skill({
name:SkillNames.Tracer,
desc:"Each level of this skill increases your success chance in " +
"all Contracts by 4%",
baseCost:3, costInc:2,
successChanceContract:4
});
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
});
//General Actions
var 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."
});
var 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.<br><br>" +
"Does NOT require stamina."
});
var actionName = "Recruitment";
GeneralActions[actionName] = new Action({
name:actionName,
desc:"Attempt to recruit members for your Bladeburner team. These members " +
"can help you conduct operations.<br><br>" +
"Does NOT require 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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"I do not need to remind you why sentient-level AIs pose a serious " +
"thread to all of mankind.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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).<br><br>" +
"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)<br><br>" +
"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.<br><br>" +
"It seems that the universe is not without a sense of irony.<br><br>" +
"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)<br><br>" +
"The bits are all around us. The daemons that hold the Node " +
"together can manifest themselves in many different ways.<br><br>" +
"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 */ 62)))
/***/ }),
/* 30 */
/*!*********************************!*\
!*** ./src/SpecialServerIps.js ***!
\*********************************/
/*! exports provided: SpecialServerNames, SpecialServerIps, SpecialServerIpsMap, loadSpecialServerIps, prestigeSpecialServerIps, initSpecialServerIps */
/*! exports used: SpecialServerIps, SpecialServerNames, initSpecialServerIps, loadSpecialServerIps, prestigeSpecialServerIps */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SpecialServerNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SpecialServerIps; });
/* unused harmony export SpecialServerIpsMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadSpecialServerIps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeSpecialServerIps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initSpecialServerIps; });
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* Holds IP of Special Servers */
let 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",
}
function SpecialServerIpsMap() {}
SpecialServerIpsMap.prototype.addIp = function(name, ip) {
this[name] = ip;
}
SpecialServerIpsMap.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Generic_toJSON"])("SpecialServerIpsMap", this);
}
SpecialServerIpsMap.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Generic_fromJSON"])(SpecialServerIpsMap, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Reviver"].constructors.SpecialServerIpsMap = SpecialServerIpsMap;
let SpecialServerIps = new SpecialServerIpsMap();
function prestigeSpecialServerIps() {
for (var member in SpecialServerIps) {
delete SpecialServerIps[member];
}
SpecialServerIps = null;
SpecialServerIps = new SpecialServerIpsMap();
}
function loadSpecialServerIps(saveString) {
SpecialServerIps = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Reviver"]);
}
function initSpecialServerIps() {
SpecialServerIps = new SpecialServerIpsMap();
}
/***/ }),
/* 31 */,
/* 32 */
/*!***********************************!*\
!*** ./utils/helpers/keyCodes.ts ***!
\***********************************/
/*! no static exports found */
/*! exports used: KEY */
/***/ (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,
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/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 */ 8);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__);
//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_3__["clearEventListeners"])("interactive-tutorial-exit");
exitButton.addEventListener("click", function() {
iTutorialEnd();
return false;
});
//Back button
var backButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back");
backButton.addEventListener("click", function() {
iTutorialPrevStep();
return false;
});
//Next button
var nextButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["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_3__["clearEventListeners"])("terminal-menu-link");
var statsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("stats-menu-link");
var activeScriptsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("active-scripts-menu-link");
var hacknetMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link");
var cityMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link");
var tutorialMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["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...<br><br>" +
"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. <br><br>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. <br><br>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. <br><br> " +
"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). <br><br> 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.<br><br>" +
"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!<br><br> 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. <br><br> " +
"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. <br><br> 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.<br><br> 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.<br><br>" +
"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.<br><br>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!<br><br>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. <strong style='background-color:#444;'>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.</strong> For now, just copy " +
"and paste the following code into the script editor: <br><br>" +
"while(true) { <br>" +
"&nbsp;&nbsp;hack('foodnstuff'); <br>" +
"}<br><br> " +
"For anyone with basic programming experience, this code should be straightforward. " +
"This script will continuously hack the 'foodnstuff' server.<br><br>" +
"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.<br><br>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). <br><br>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. <br><br> " +
"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! <br><br>" +
"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. " +
"<strong style='background-color:#444;'>If you are an experienced JavaScript " +
"developer, I would highly suggest you check out the section on " +
"NetscriptJS/Netscript 2.0.</strong><br><br>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.<br><br>" +
"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"].loadWorldContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.WorldDescription:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent();
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!<br><br>" +
"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. <strong style='background-color:#444;'> I know it's a lot, but I highly suggest you read " +
"(or at least skim) through this before you start playing</strong>. 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__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__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval * 5;
}
console.log("Ending interactive tutorial");
_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_4__["createElement"])("p", {
innerHTML:
"If you are new to the game, the following links may be useful for you!<br><br>" +
"<a class='a-link-button' href='http://bitburner.wikia.com/wiki/Chapt3rs_Guide_to_Getting_Started_with_Bitburner' target='_blank'>Getting Started Guide</a>" +
"<a class='a-link-button' href='http://bitburner.wikia.com/wiki/Bitburner_Wiki' target='_blank'>Wiki</a>" +
"<a class='a-link-button' href='https://bitburner.readthedocs.io/en/latest/' target='_blank'>Documentation</a><br><br>" +
"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<br><br>cat hackers-starting-handbook.lit"
});
var gotitBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__["createElement"])("a", {
class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__["removeElementById"])(popupId);
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__["createPopup"])(popupId, [txt, gotitBtn]);
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].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
}
/***/ }),
/* 34 */
/*!**************************************************!*\
!*** ./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"
];
/***/ }),
/* 35 */
/*!***********************!*\
!*** ./src/Crimes.js ***!
\***********************/
/*! exports provided: determineCrimeSuccess, findCrime, Crimes */
/*! exports used: Crimes, determineCrimeSuccess, findCrime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return determineCrimeSuccess; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return findCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Crimes; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
function Crime(name, type, time, money, difficulty, karma, params) {
this.name = name;
this.type = type;
this.time = time;
this.money = money;
this.difficulty = difficulty;
this.karma = karma;
this.hacking_success_weight = params.hacking_success_weight ? params.hacking_success_weight : 0;
this.strength_success_weight = params.strength_success_weight ? params.strength_success_weight : 0;
this.defense_success_weight = params.defense_success_weight ? params.defense_success_weight : 0;
this.dexterity_success_weight = params.dexterity_success_weight ? params.dexterity_success_weight : 0;
this.agility_success_weight = params.agility_success_weight ? params.agility_success_weight : 0;
this.charisma_success_weight = params.charisma_success_weight ? params.charisma_success_weight : 0;
this.hacking_exp = params.hacking_exp ? params.hacking_exp : 0;
this.strength_exp = params.strength_exp ? params.strength_exp : 0;
this.defense_exp = params.defense_exp ? params.defense_exp : 0;
this.dexterity_exp = params.dexterity_exp ? params.dexterity_exp : 0;
this.agility_exp = params.agility_exp ? params.agility_exp : 0;
this.charisma_exp = params.charisma_exp ? params.charisma_exp : 0;
this.intelligence_exp = params.intelligence_exp ? params.intelligence_exp : 0;
this.kills = params.kills ? params.kills : 0;
}
Crime.prototype.commit = function(div=1, singParams=null) {
if (div <= 0) {div = 1;}
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].crimeType = this.type;
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].startCrime(
this.hacking_exp/div,
this.strength_exp/div,
this.defense_exp/div,
this.dexterity_exp/div,
this.agility_exp/div,
this.charisma_exp/div,
this.money/div, this.time, singParams);
return this.time;
}
Crime.prototype.successRate = function() {
var chance = (this.hacking_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill +
this.strength_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].strength +
this.defense_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].defense +
this.dexterity_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].dexterity +
this.agility_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].agility +
this.charisma_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].charisma +
_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeWeight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].intelligence);
chance /= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel;
chance /= this.difficulty;
chance *= _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].crime_success_mult;
return Math.min(chance, 1);
}
const Crimes = {
Shoplift: new Crime("Shoplift", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift, 2e3, 15e3, 1/20, 0.1, {
dexterity_success_weight: 1,
agility_success_weight: 1,
dexterity_exp: 2,
agility_exp: 2,
}),
RobStore: new Crime("Rob Store", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore, 60e3, 400e3, 1/5, 0.5, {
hacking_exp: 30,
dexterity_exp: 45,
agility_exp: 45,
hacking_success_weight: 0.5 ,
dexterity_success_weight: 2,
agility_success_weight: 1,
intelligence_exp: 0.25 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
Mug: new Crime("Mug", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug, 4e3, 36e3, 1/5, 0.25, {
strength_exp: 3,
defense_exp: 3,
dexterity_exp: 3,
agility_exp: 3,
strength_success_weight: 1.5,
defense_success_weight: 0.5,
dexterity_success_weight: 1.5,
agility_success_weight: 0.5,
}),
Larceny: new Crime("Larceny", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny, 90e3, 800e3, 1/3, 1.5, {
hacking_exp: 45,
dexterity_exp: 60,
agility_exp: 60,
hacking_success_weight: 0.5,
dexterity_success_weight: 1,
agility_success_weight: 1,
intelligence_exp: 0.5 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
DealDrugs: new Crime("Deal Drugs", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs, 10e3, 120e3, 1, 0.5, {
dexterity_exp: 5,
agility_exp: 5,
charisma_exp: 10,
charisma_success_weight: 3,
dexterity_success_weight: 2,
agility_success_weight: 1,
}),
BondForgery: new Crime("Bond Forgery", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery, 300e3, 4.5e6, 1/2, 0.1, {
hacking_exp: 100,
dexterity_exp: 150,
charisma_exp: 15,
hacking_success_weight: 0.05,
dexterity_success_weight: 1.25,
intelligence_exp: 2 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
TraffickArms: new Crime("Traffick Arms", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms, 40e3, 600e3, 2, 1, {
strength_exp: 20,
defense_exp: 20,
dexterity_exp: 20,
agility_exp: 20,
charisma_exp: 40,
charisma_success_weight: 1,
strength_success_weight: 1,
defense_success_weight: 1,
dexterity_success_weight: 1,
agility_success_weight: 1,
}),
Homicide: new Crime("Homicide", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide, 3e3, 45e3, 1, 3, {
strength_exp: 2,
defense_exp: 2,
dexterity_exp: 2,
agility_exp: 2,
strength_success_weight: 2,
defense_success_weight: 2,
dexterity_success_weight: 0.5,
agility_success_weight: 0.5,
kills: 1,
}),
GrandTheftAuto: new Crime("Grand Theft Auto", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto, 80e3, 1.6e6, 8, 5, {
strength_exp: 20,
defense_exp: 20,
dexterity_exp: 20,
agility_exp: 80,
charisma_exp: 40,
hacking_success_weight: 1,
strength_success_weight: 1,
dexterity_success_weight: 4,
agility_success_weight: 2,
charisma_success_weight: 2,
intelligence_exp: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
Kidnap: new Crime("Kidnap", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap, 120e3, 3.6e6, 5, 6, {
strength_exp: 80,
defense_exp: 80,
dexterity_exp: 80,
agility_exp: 80,
charisma_exp: 80,
charisma_success_weight: 1,
strength_success_weight: 1,
dexterity_success_weight: 1,
agility_success_weight: 1,
intelligence_exp: 2 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
Assassination: new Crime("Assassination", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination, 300e3, 12e6, 8, 10, {
strength_exp: 300,
defense_exp: 300,
dexterity_exp: 300,
agility_exp: 300,
strength_success_weight: 1,
dexterity_success_weight: 2,
agility_success_weight: 1,
intelligence_exp: 5 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
kills: 1,
}),
Heist: new Crime("Heist", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist, 600e3, 120e6, 18, 15, {
hacking_exp: 450,
strength_exp: 450,
defense_exp: 450,
dexterity_exp: 450,
agility_exp: 450,
charisma_exp: 450,
hacking_success_weight: 1,
strength_success_weight: 1,
defense_success_weight: 1,
dexterity_success_weight: 1,
agility_success_weight: 1,
charisma_success_weight: 1,
intelligence_exp: 10 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain,
}),
};
function determineCrimeSuccess(type, moneyGained) {
var chance = 0;
var found = false;
for(const i in Crimes) {
const crime = Crimes[i];
if(crime.type == type) {
chance = crime.successRate();
found = true;
break;
}
}
if(!found) {
console.log(crime);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer");
return;
}
if (Math.random() <= chance) {
//Success
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].gainMoney(moneyGained);
return true;
} else {
//Failure
return false;
}
}
function findCrime(roughName) {
if (roughName.includes("shoplift")) {
return Crimes.Shoplift;
} else if (roughName.includes("rob") && roughName.includes("store")) {
return Crimes.RobStore;
} else if (roughName.includes("mug")) {
return Crimes.Mug;
} else if (roughName.includes("larceny")) {
return Crimes.Larceny;
} else if (roughName.includes("drugs")) {
return Crimes.DealDrugs;
} else if (roughName.includes("bond") && roughName.includes("forge")) {
return Crimes.BondForgery;
} else if (roughName.includes("traffick") && roughName.includes("arms")) {
return Crimes.TraffickArms;
} else if (roughName.includes("homicide")) {
return Crimes.Homicide;
} else if (roughName.includes("grand") && roughName.includes("auto")) {
return Crimes.GrandTheftAuto;
} else if (roughName.includes("kidnap")) {
return Crimes.Kidnap;
} else if (roughName.includes("assassinate")) {
return Crimes.Assassination;
} else if (roughName.includes("heist")) {
return Crimes.Heist;
}
return null;
}
/***/ }),
/* 36 */
/*!******************************!*\
!*** ./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 */ 48);
/* 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 */ "a"].gang instanceof _Gang__WEBPACK_IMPORTED_MODULE_1__[/* Gang */ "b"];
if (!hasAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__[/* makeRuntimeRejectMsg */ "d"])(workerScript, accessDenied);
}
}
/***/ }),
/* 37 */
/*!***********************************!*\
!*** ./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;
/***/ }),
/* 38 */
/*!************************!*\
!*** ./src/Message.js ***!
\************************/
/*! exports provided: Messages, checkForMessagesToSend, sendMessage, showMessage, loadMessages, initMessages, Message */
/*! exports used: Message, Messages, checkForMessagesToSend, initMessages, loadMessages, showMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Messages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return checkForMessagesToSend; });
/* unused harmony export sendMessage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return showMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return loadMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Message; });
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions */ 53);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./RedPill */ 55);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* Message.js */
function Message(filename="", msg="") {
this.filename = filename;
this.msg = msg;
this.recvd = false;
}
Message.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Message", this);
}
Message.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Message, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Message = Message;
//Sends message to player, including a pop up
function sendMessage(msg, forced=false) {
console.log("sending message: " + msg.filename);
msg.recvd = true;
if (forced || !_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].SuppressMessages) {
showMessage(msg);
}
addMessageToServer(msg, "home");
}
function showMessage(msg) {
var txt = "Message received from unknown sender: <br><br>" +
"<i>" + msg.msg + "</i><br><br>" +
"This message was saved as " + msg.filename + " onto your home computer.";
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(txt);
}
//Adds a message to a server
function addMessageToServer(msg, serverHostname) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_5__[/* GetServerByHostname */ "c"])(serverHostname);
if (server == null) {
console.log("WARNING: Did not locate " + 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 (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].TheRedPill].owned) {
redpillOwned = true;
}
if (redpill && redpillOwned && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].sourceFiles.length === 0 && !_RedPill__WEBPACK_IMPORTED_MODULE_4__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__[/* inMission */ "c"]) {
if (!_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
sendMessage(redpill, true);
}
} else if (redpill && redpillOwned) {
//If player has already destroyed a BitNode, message is not forced
if (!_RedPill__WEBPACK_IMPORTED_MODULE_4__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__[/* inMission */ "c"] && !_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
sendMessage(redpill);
}
} else if (jumper0 && !jumper0.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 25) {
sendMessage(jumper0);
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_1__[/* Programs */ "a"].Flight.name);
} else if (jumper1 && !jumper1.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 40) {
sendMessage(jumper1);
} else if (cybersecTest && !cybersecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 50) {
sendMessage(cybersecTest);
} else if (jumper2 && !jumper2.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 175) {
sendMessage(jumper2);
} else if (nitesecTest && !nitesecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 200) {
sendMessage(nitesecTest);
} else if (jumper3 && !jumper3.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 350) {
sendMessage(jumper3);
} else if (jumper4 && !jumper4.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 490) {
sendMessage(jumper4);
} else if (bitrunnersTest && !bitrunnersTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].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_8__["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(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. <br><br>It's real, I've seen it. And I can " +
"help you find it. But not right now. You're not ready yet.<br><br>" +
"Use this program to track your progress<br><br>" +
"The fl1ght.exe program was added to your home computer<br><br>" +
"-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper1,
"Soon you will be contacted by a hacking group known as CyberSec. " +
"They can help you with your search. <br><br>" +
"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.<br><br>" +
"-jump3R"));
AddToAllMessages(new 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. <br><br>Watch out for a hacking group known as NiteSec." +
"<br><br>-jump3R"));
AddToAllMessages(new 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. <br><br>" +
"I.I.I.I <br><br>-jump3R"));
AddToAllMessages(new 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.<br><br>" +
"-jump3R"));
//Messages from hacking factions
AddToAllMessages(new 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. <br><br>" +
"But first, you must pass our test. Find and hack our server using the Terminal. <br><br>" +
"-CyberSec"));
AddToAllMessages(new 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. <br><br>" +
"Join us, and people will fear you, too. <br><br>" +
"Find and hack our hidden server using the Terminal. Then, we will contact you again." +
"<br><br>-NiteSec"));
AddToAllMessages(new Message(MessageFilenames.BitRunnersTest,
"We know what you are doing. We know what drives you. We know " +
"what you are looking for. <br><br> " +
"We can help you find the answers.<br><br>" +
"run4theh111z"));
AddToAllMessages(new Message(MessageFilenames.RedPill,
"@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*%<br>" +
")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B)<br>" +
"@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB<br>" +
"DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
}
/***/ }),
/* 39 */
/*!****************************************!*\
!*** ./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 */ 2);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 51);
/**
* 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) {
const container = createElement_1.createElement("div", {
class: "popup-box-container",
display: "flex",
id,
});
const content = createElement_1.createElement("div", {
class: "popup-box-content",
id: `${id}-content`,
});
for (const elem of elems) {
content.appendChild(elem);
}
container.appendChild(content);
getElementById_1.getElementById("entire-game-container")
.appendChild(container);
return container;
}
exports.createPopup = createPopup;
/***/ }),
/* 40 */
/*!********************************!*\
!*** ./src/CodingContracts.ts ***!
\********************************/
/*! no static exports found */
/*! exports used: CodingContract, CodingContractResult, CodingContractRewardType, CodingContractTypes */
/***/ (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 JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 13);
const createElement_1 = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
const createPopup_1 = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
const removeElementById_1 = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
const codingcontracttypes_1 = __webpack_require__(/*! ./data/codingcontracttypes */ 183);
/* 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", {
innerText: ["You are attempting to solve a Coding Contract. You have",
`${this.getMaxNumTries() - this.tries} tries remaining,`,
"after which the contract will self-destruct.\n\n",
`${contractType.desc(this.data)}`].join(" "),
});
let answerInput;
let solveBtn;
answerInput = createElement_1.createElement("input", {
onkeydown: (e) => {
if (e.keyCode === 13 && answerInput.value !== "") {
e.preventDefault();
solveBtn.click();
}
},
placeholder: "Enter Solution here",
});
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",
});
const 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;
/***/ }),
/* 41 */
/*!***********************************!*\
!*** ./src/NetscriptFunctions.js ***!
\***********************************/
/*! exports provided: NetscriptFunctions, initSingularitySFFlags, hasSingularitySF, hasBn11SF, hasWallStreetSF, wallStreetSFLvl, hasCorporationSF, hasAISF, hasBladeburnerSF */
/*! exports used: NetscriptFunctions, hasAISF, hasBladeburnerSF, hasBn11SF, hasCorporationSF, hasWallStreetSF, initSingularitySFFlags, wallStreetSFLvl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptFunctions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initSingularitySFFlags; });
/* unused harmony export hasSingularitySF */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return hasBn11SF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return hasWallStreetSF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return wallStreetSFLvl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return hasCorporationSF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hasAISF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return hasBladeburnerSF; });
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI */ 64);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Crimes */ 35);
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Bladeburner */ 29);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company/Company */ 71);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Company_Company__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Company/CompanyPosition */ 81);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Company/CompanyPositions */ 26);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _DarkWeb__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./DarkWeb */ 76);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Hacking */ 47);
/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Gang */ 48);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Faction/Faction */ 54);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./HacknetNode */ 63);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Message */ 38);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Missions */ 53);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Stock */ 25);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./StockMarket */ 22);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./TextFile */ 60);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./NetscriptBladeburner */ 50);
/* harmony import */ var _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./NetscriptGang */ 36);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./NetscriptPort */ 68);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! decimal.js */ 31);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ../utils/helpers/isPowerOfTwo */ 120);
/* harmony import */ var _utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 52);
/* 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_IPAddress__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ../utils/IPAddress */ 57);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
var sprintf = __webpack_require__(/*! sprintf-js */ 137).sprintf,
vsprintf = __webpack_require__(/*! sprintf-js */ 137).vsprintf
var hasCorporationSF = false, //Source-File 3
hasSingularitySF = false, //Source-File 4
hasAISF = false, //Source-File 5
hasBladeburnerSF = false, //Source-File 6
hasBladeburner2079SF = false, //Source-File 7
hasWallStreetSF = false, //Source-File 8
hasBn11SF = false; //Source-File 11
var singularitySFLvl=1, wallStreetSFLvl=1;
var possibleLogs = {
ALL: true,
scan: true,
hack: true,
sleep: true,
disableLog: true,
enableLog: true,
grow: true,
weaken: true,
nuke: true,
brutessh: true,
ftpcrack: true,
relaysmtp: true,
httpworm: true,
sqlinject: true,
run:true,
exec:true,
spawn: true,
kill: true,
killall: true,
scp: true,
getHackingLevel: true,
getServerMoneyAvailable: true,
getServerSecurityLevel: true,
getServerBaseSecurityLevel: true,
getServerMinSecurityLevel: true,
getServerRequiredHackingLevel: true,
getServerMaxMoney: true,
getServerGrowth: true,
getServerNumPortsRequired: true,
getServerRam: true,
// TIX API
buyStock: true,
sellStock: true,
shortStock: true,
sellShort: true,
purchase4SMarketData: true,
purchase4SMarketDataTixApi: true,
// Singularity Functions
purchaseServer: true,
deleteServer: true,
universityCourse: true,
gymWorkout: true,
travelToCity: true,
purchaseTor: true,
purchaseProgram: true,
stopAction: true,
upgradeHomeRam: true,
workForCompany: true,
applyToCompany: true,
joinFaction: true,
workForFaction: true,
donateToFaction: true,
createProgram: true,
commitCrime: true,
// Bladeburner API
startAction: true,
upgradeSkill: true,
setTeamSize: true,
joinBladeburnerFaction: true,
// Gang API
recruitMember: true,
setMemberTask: true,
purchaseEquipment: true,
setTerritoryWarfare: true,
}
//Used to check and set flags for every Source File, despite the name of the function
function initSingularitySFFlags() {
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 3) {hasCorporationSF = true;}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 4) {
hasSingularitySF = true;
singularitySFLvl = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].lvl;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 5) {hasAISF = true;}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 8) {
hasWallStreetSF = true;
wallStreetSFLvl = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].lvl;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n === 11) {hasBn11SF = true;}
}
}
function NetscriptFunctions(workerScript) {
var updateDynamicRam = function(fnName, ramCost) {
if (workerScript.dynamicLoadedFns[fnName]) {return;}
workerScript.dynamicLoadedFns[fnName] = true;
const threads = workerScript.scriptRef.threads;
if (typeof threads !== 'number') {
console.warn(`WorkerScript detected NaN for threadcount for ${workerScript.name} on ${workerScript.serverIp}`);
threads = 1;
}
workerScript.dynamicRamUsage += (ramCost * threads);
if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript,
"Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName +
". This is probably because you somehow circumvented the static RAM " +
"calculation.<br><br>Please don't do that :(<br><br>" +
"Dynamic RAM Usage: " + workerScript.dynamicRamUsage + "<br>" +
"Static RAM Usage: " + workerScript.ramUsage);
}
};
var updateStaticRam = function(fnName, ramCost) {
if (workerScript.loadedFns[fnName]) {
return 0;
} else {
workerScript.loadedFns[fnName] = true;
return ramCost;
}
};
/**
* Gets the Server for a specific hostname/ip, throwing an error
* if the server doesn't exist.
* @param {string} Hostname or IP of the server
* @returns {Server} The specified Server
*/
var safeGetServer = function(ip, callingFnName="") {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `Invalid IP or hostname passed into ${callingFnName}() function`);
}
return server;
}
// Utility function to get Hacknet Node object
var getHacknetNode = function(i) {
if (isNaN(i)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid index specified for Hacknet Node: " + i);
}
if (i < 0 || i >= _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknetNodes.length) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Index specified for Hacknet Node is out-of-bounds: " + i);
}
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknetNodes[i];
};
var getCodingContract = function(fn, ip) {
var server = safeGetServer(ip, "getCodingContract");
return server.getContract(fn);
}
/**
* @param {number} ram The amount of server RAM to calculate cost of.
* @exception {Error} If the value passed in is not numeric, out of range, or too large of a value.
* @returns {number} The cost of
*/
const getPurchaseServerRamCostGuard = (ram) => {
const guardedRam = Math.round(ram);
if (isNaN(guardedRam) || !Object(_utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_38__["isPowerOfTwo"])(guardedRam)) {
throw Error("failed due to invalid ram argument. Must be numeric and a power of 2");
}
if (guardedRam > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerMaxRam) {
throw Error("failed because specified RAM was too high. Maximum RAM on a purchased server is " + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerMaxRam + "GB");
}
return guardedRam * _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].BaseCostFor1GBOfRamServer;
};
return {
hacknet : {
numNodes : function() {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknetNodes.length;
},
purchaseNode : function() {
return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_17__[/* purchaseHacknet */ "e"])();
},
getPurchaseNodeCost : function() {
return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_17__[/* getCostOfNextHacknetNode */ "c"])();
},
getNodeStats : function(i) {
var node = getHacknetNode(i);
return {
name: node.name,
level: node.level,
ram: node.ram,
cores: node.cores,
production: node.moneyGainRatePerSecond,
timeOnline: node.onlineTimeSeconds,
totalProduction: node.totalMoneyGenerated,
};
},
upgradeLevel : function(i, n) {
var node = getHacknetNode(i);
return node.purchaseLevelUpgrade(n);
},
upgradeRam : function(i, n) {
var node = getHacknetNode(i);
return node.purchaseRamUpgrade(n);
},
upgradeCore : function(i, n) {
var node = getHacknetNode(i);
return node.purchaseCoreUpgrade(n);
},
getLevelUpgradeCost : function(i, n) {
var node = getHacknetNode(i);
return node.calculateLevelUpgradeCost(n);
},
getRamUpgradeCost : function(i, n) {
var node = getHacknetNode(i);
return node.calculateRamUpgradeCost(n);
},
getCoreUpgradeCost : function(i, n) {
var node = getHacknetNode(i);
return node.calculateCoreUpgradeCost(n);
}
},
sprintf : sprintf,
vsprintf: vsprintf,
scan : function(ip=workerScript.serverIp, hostnames=true){
if (workerScript.checkingRam) {
return updateStaticRam("scan", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
}
updateDynamicRam("scan", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, 'Invalid IP or hostname passed into scan() command');
}
var out = [];
for (var i = 0; i < server.serversOnNetwork.length; i++) {
var entry;
if (hostnames) {
entry = server.getServerOnNetwork(i).hostname;
} else {
entry = server.getServerOnNetwork(i).ip;
}
if (entry == null) {
continue;
}
out.push(entry);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) {
workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname);
}
return out;
},
hack : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("hack", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptHackRamCost);
}
updateDynamicRam("hack", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptHackRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument");
}
var threads = workerScript.scriptRef.threads;
if (isNaN(threads) || threads < 1) {threads = 1;}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
}
//Calculate the hacking time
var hackingTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingTime */ "d"])(server); //This is in seconds
//No root access or skill level too low
if (server.hasAdminRights == false) {
workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access");
}
if (server.requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_skill) {
workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* netscriptDelay */ "e"])(hackingTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingChance */ "b"])(server);
var rand = Math.random();
var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingExpGain */ "c"])(server) * threads;
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
const percentHacked = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculatePercentMoneyHacked */ "e"])(server);
let maxThreadNeeded = Math.ceil(1/percentHacked*(server.moneyAvailable/server.moneyMax));
if (isNaN(maxThreadNeeded)) {
//Server has a 'max money' of 0 (probably).
//We'll set this to an arbitrarily large value
maxThreadNeeded = 1e6;
}
let moneyGained = Math.floor(server.moneyAvailable * percentHacked) * threads;
//Over-the-top safety checks
if (moneyGained <= 0) {
moneyGained = 0;
expGainedOnSuccess = expGainedOnFailure;
}
if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;}
server.moneyAvailable -= moneyGained;
if (server.moneyAvailable < 0) {server.moneyAvailable = 0;}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainMoney(moneyGained);
workerScript.scriptRef.onlineMoneyMade += moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].scriptProdSinceLastAug += moneyGained;
workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainHackingExp(expGainedOnSuccess);
workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")");
}
server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
return Promise.resolve(moneyGained);
} else {
//Player only gains 25% exp for failure?
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainHackingExp(expGainedOnFailure);
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(expGainedOnFailure, 4) + " exp (t=" + threads + ")");
}
return Promise.resolve(0);
}
});
},
sleep : function(time){
if (workerScript.checkingRam) {return 0;}
if (time === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument");
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) {
workerScript.scriptRef.log("Sleeping for " + time + " milliseconds");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* netscriptDelay */ "e"])(time, workerScript).then(function() {
return Promise.resolve(true);
});
},
grow : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("grow", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGrowRamCost);
}
updateDynamicRam("grow", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGrowRamCost);
var threads = workerScript.scriptRef.threads;
if (isNaN(threads) || threads < 1) {threads = 1;}
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip);
}
//No root access or skill level too low
if (server.hasAdminRights == false) {
workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access");
}
var growTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateGrowTime */ "a"])(server);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {
workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(growTime, 3) + " seconds (t=" + threads + ")");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* netscriptDelay */ "e"])(growTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable;
server.moneyAvailable += (1 * threads); //It can be grown even if it has no money
var growthPercentage = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* processSingleServerGrowth */ "k"])(server, 450 * threads);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.ip, threads);
var expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingExpGain */ "c"])(server) * threads;
if (growthPercentage == 1) {
expGain = 0;
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {
workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])((moneyAfter/moneyBefore)*100 - 100, 6) + "%. Gained " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")");
}
workerScript.scriptRef.onlineExpGained += expGain;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainHackingExp(expGain);
return Promise.resolve(moneyAfter/moneyBefore);
});
},
growthAnalyze : function(ip, growth) {
if (workerScript.checkingRam) {
return updateStaticRam("growthAnalyze", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGrowthAnalyzeRamCost);
}
updateDynamicRam("growthAnalyze", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGrowthAnalyzeRamCost);
// Check argument validity
const server = safeGetServer(ip, 'growthAnalyze');
if (isNaN(growth)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `Invalid growth argument passed into growthAnalyze: ${growth}. Must be numeric`);
}
return Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* numCycleForGrowth */ "h"])(server, Number(growth));
},
weaken : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("weaken", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptWeakenRamCost);
}
updateDynamicRam("weaken", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptWeakenRamCost);
var threads = workerScript.scriptRef.threads;
if (isNaN(threads) || threads < 1) {threads = 1;}
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip);
}
//No root access or skill level too low
if (server.hasAdminRights == false) {
workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access");
}
var weakenTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateWeakenTime */ "f"])(server);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {
workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(weakenTime, 3) + " seconds (t=" + threads + ")");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* netscriptDelay */ "e"])(weakenTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
server.weaken(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ServerWeakenAmount * threads);
workerScript.scriptRef.recordWeaken(server.ip, threads);
var expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingExpGain */ "c"])(server) * threads;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {
workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty +
". Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")");
}
workerScript.scriptRef.onlineExpGained += expGain;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainHackingExp(expGain);
return Promise.resolve(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ServerWeakenAmount * threads);
});
},
print : function(args){
if (workerScript.checkingRam) {return 0;}
if (args === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument");
}
workerScript.scriptRef.log(args.toString());
},
tprint : function(args) {
if (workerScript.checkingRam) {return 0;}
if (args === undefined || args == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument");
}
var x = args.toString();
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_28__["post"])(workerScript.scriptRef.filename + ": " + args.toString());
},
clearLog : function() {
if (workerScript.checkingRam) {return 0;}
workerScript.scriptRef.clearLog();
},
disableLog : function(fn) {
if (workerScript.checkingRam) {return 0;}
if(possibleLogs[fn]===undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to disableLog: "+fn);
}
workerScript.disableLogs[fn] = true;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) {
workerScript.scriptRef.log("Disabled logging for " + fn);
}
},
enableLog : function(fn) {
if (workerScript.checkingRam) {return 0;}
if(possibleLogs[fn]===undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to enableLog: "+fn);
}
delete workerScript.disableLogs[fn];
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) {
workerScript.scriptRef.log("Enabled logging for " + fn);
}
},
isLogEnabled : function(fn) {
if (workerScript.checkingRam) {return 0;}
if (possibleLogs[fn] === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to isLogEnabled: " + fn);
}
return workerScript.disableLogs[fn] ? false : true;
},
getScriptLogs : function(fn, ip) {
if (workerScript.checkingRam) {return 0;}
if (fn != null && typeof fn === 'string') {
// Get Logs of another script
if (ip == null) { ip = workerScript.serverIp; }
const server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.log(`getScriptLogs() failed. Invalid IP or hostname passed in: ${ip}`);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `getScriptLogs() failed. Invalid IP or hostname passed in: ${ip}`);
}
let argsForTarget = [];
for (let i = 2; i < arguments.length; ++i) {
argsForTarget.push(arguments[i]);
}
const runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* findRunningScript */ "d"])(fn, argsForTarget, server);
if (runningScriptObj == null) {
workerScript.scriptRef.log(`getScriptLogs() failed. No such script ${fn} on ${server.hostname} with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForTarget)}`);
return "";
}
return runningScriptObj.logs.slice();
}
return workerScript.scriptRef.logs.slice();
},
nuke : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].NukeProgram.name)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Not enough ports opened to use NUKE.exe virus");
}
if (server.hasAdminRights) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {
workerScript.scriptRef.log("Already have root access to " + server.hostname);
}
} else {
server.hasAdminRights = true;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {
workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access");
}
}
return true;
},
brutessh : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].BruteSSHProgram.name)) {
workerScript.scriptRef.log("You do not have the BruteSSH.exe program!");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the BruteSSH.exe program!");
}
if (!server.sshPortOpen) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {
workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)");
}
server.sshPortOpen = true;
++server.openPortCount;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {
workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname);
}
}
return true;
},
ftpcrack : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].FTPCrackProgram.name)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the FTPCrack.exe program!");
}
if (!server.ftpPortOpen) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {
workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)");
}
server.ftpPortOpen = true;
++server.openPortCount;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {
workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname);
}
}
return true;
},
relaysmtp : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].RelaySMTPProgram.name)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the relaySMTP.exe program!");
}
if (!server.smtpPortOpen) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {
workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)");
}
server.smtpPortOpen = true;
++server.openPortCount;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {
workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname);
}
}
return true;
},
httpworm : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].HTTPWormProgram.name)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the HTTPWorm.exe program!");
}
if (!server.httpPortOpen) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {
workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)");
}
server.httpPortOpen = true;
++server.openPortCount;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {
workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname);
}
}
return true;
},
sqlinject : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
}
updateDynamicRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPortProgramRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"].SQLInjectProgram.name)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the SQLInject.exe program!");
}
if (!server.sqlPortOpen) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {
workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)");
}
server.sqlPortOpen = true;
++server.openPortCount;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {
workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname);
}
}
return true;
},
run : function(scriptname,threads = 1){
if (workerScript.checkingRam) {
return updateStaticRam("run", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptRunRamCost);
}
updateDynamicRam("run", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptRunRamCost);
if (scriptname === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0");
}
var argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* runScriptFromScript */ "f"])(scriptServer, scriptname, argsForNewScript, workerScript, threads);
},
exec : function(scriptname,ip,threads = 1) {
if (workerScript.checkingRam) {
return updateStaticRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptExecRamCost);
}
updateDynamicRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptExecRamCost);
if (scriptname === undefined || ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0");
}
var argsForNewScript = [];
for (var i = 3; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip);
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* runScriptFromScript */ "f"])(server, scriptname, argsForNewScript, workerScript, threads);
},
spawn : function(scriptname, threads) {
if (workerScript.checkingRam) {
return updateStaticRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSpawnRamCost);
}
updateDynamicRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSpawnRamCost);
if (scriptname == null || threads == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()");
}
setTimeout(()=>{
if (scriptname === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "spawn() call has incorrect number of arguments. Usage: spawn(scriptname, numThreads, [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0");
}
var argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* runScriptFromScript */ "f"])(scriptServer, scriptname, argsForNewScript, workerScript, threads);
}, 20000);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) {
workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds");
}
NetscriptFunctions(workerScript).exit();
},
kill : function(filename, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptKillRamCost);
}
updateDynamicRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptKillRamCost);
if (filename === undefined || ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip);
}
var argsForKillTarget = [];
for (var i = 2; i < arguments.length; ++i) {
argsForKillTarget.push(arguments[i]);
}
var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* findRunningScript */ "d"])(filename, argsForKillTarget, server);
if (runningScriptObj == null) {
workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForKillTarget));
return false;
}
var res = Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* killWorkerScript */ "d"])(runningScriptObj, server.ip);
if (res) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {
workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die...");
}
return true;
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {
workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForKillTarget));
}
return false;
}
},
killall : function(ip=workerScript.serverIp){
if (workerScript.checkingRam) {
return updateStaticRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptKillRamCost);
}
updateDynamicRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptKillRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip);
}
var scriptsRunning = (server.runningScripts.length > 0);
for (var i = server.runningScripts.length-1; i >= 0; --i) {
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* killWorkerScript */ "d"])(server.runningScripts[i], server.ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) {
workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die");
}
return scriptsRunning;
},
exit : function() {
if (workerScript.checkingRam) {return 0;}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev");
}
if (Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* killWorkerScript */ "d"])(workerScript.scriptRef, server.ip)) {
workerScript.scriptRef.log("Exiting...");
} else {
workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer");
}
},
scp : function(scriptname, ip1, ip2) {
if (workerScript.checkingRam) {
return updateStaticRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScpRamCost);
}
updateDynamicRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScpRamCost);
if (arguments.length !== 2 && arguments.length !== 3) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
if (scriptname && scriptname.constructor === Array) {
//Recursively call scp on all elements of array
var res = false;
scriptname.forEach(function(script) {
if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) {
res = true;
};
});
return res;
}
if (!scriptname.endsWith(".lit") && !Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(scriptname) &&
!scriptname.endsWith("txt")) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() does not work with this file type. It only works for .script, .lit, and .txt files");
}
var destServer, currServ;
if (ip2 != null) { // 3 Argument version: scriptname, source, destination
if (scriptname === undefined || ip1 === undefined || ip2 === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip2);
if (destServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip2}`);
}
currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip1);
if (currServ == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip1}`);
}
} else if (ip1 != null) { // 2 Argument version: scriptname, destination
if (scriptname === undefined || ip1 === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip1);
if (destServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip1}`);
}
currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (currServ == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");
}
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
//Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_19__[/* Message */ "a"]) && currServ.messages[i] == scriptname) {
found = true;
break;
}
}
if (!found) {
workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
return false;
}
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
return true; //Already exists
}
}
destServer.messages.push(scriptname);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
return true;
}
//Scp for text files
if (scriptname.endsWith(".txt")) {
var found = false, txtFile;
for (var i = 0; i < currServ.textFiles.length; ++i) {
if (currServ.textFiles[i].fn === scriptname) {
found = true;
txtFile = currServ.textFiles[i];
break;
}
}
if (!found) {
workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
return false;
}
for (var i = 0; i < destServer.textFiles.length; ++i) {
if (destServer.textFiles[i].fn === scriptname) {
//Overwrite
destServer.textFiles[i].text = txtFile.text;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
return true;
}
}
var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_29__["TextFile"](txtFile.fn, txtFile.text);
destServer.textFiles.push(newFile);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
return true;
}
//Scp for script files
var sourceScript = null;
for (var i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
sourceScript = currServ.scripts[i];
break;
}
}
if (sourceScript == null) {
workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
return false;
}
//Overwrite script if it already exists
for (var i = 0; i < destServer.scripts.length; ++i) {
if (scriptname == destServer.scripts[i].filename) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten.");
workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname);
}
var oldScript = destServer.scripts[i];
oldScript.code = sourceScript.code;
oldScript.ramUsage = sourceScript.ramUsage;
oldScript.module = "";
return true;
}
}
//Create new script if it does not already exist
var newScript = new _Script__WEBPACK_IMPORTED_MODULE_22__[/* Script */ "c"]();
newScript.filename = scriptname;
newScript.code = sourceScript.code;
newScript.ramUsage = sourceScript.ramUsage;
newScript.server = destServer.ip;
destServer.scripts.push(newScript);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
return true;
},
ls : function(ip, grep) {
if (workerScript.checkingRam) {
return updateStaticRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
}
updateDynamicRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
if (ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip);
}
//Get the grep filter, if one exists
var filter = false;
if (arguments.length >= 2) {
filter = grep.toString();
}
var allFiles = [];
for (var i = 0; i < server.programs.length; i++) {
if (filter) {
if (server.programs[i].includes(filter)) {
allFiles.push(server.programs[i]);
}
} else {
allFiles.push(server.programs[i]);
}
}
for (var i = 0; i < server.scripts.length; i++) {
if (filter) {
if (server.scripts[i].filename.includes(filter)) {
allFiles.push(server.scripts[i].filename);
}
} else {
allFiles.push(server.scripts[i].filename);
}
}
for (var i = 0; i < server.messages.length; i++) {
if (filter) {
if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_19__[/* Message */ "a"]) {
if (server.messages[i].filename.includes(filter)) {
allFiles.push(server.messages[i].filename);
}
} else if (server.messages[i].includes(filter)) {
allFiles.push(server.messages[i]);
}
} else {
if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_19__[/* Message */ "a"]) {
allFiles.push(server.messages[i].filename);
} else {
allFiles.push(server.messages[i]);
}
}
}
for (var i = 0; i < server.textFiles.length; i++) {
if (filter) {
if (server.textFiles[i].fn.includes(filter)) {
allFiles.push(server.textFiles[i].fn);
}
} else {
allFiles.push(server.textFiles[i].fn);
}
}
for (var i = 0; i < server.contracts.length; ++i) {
if (filter) {
if (server.contracts[i].fn.includes(filter)) {
allFiles.push(server.contracts[i].fn);
}
} else {
allFiles.push(server.contracts[i].fn);
}
}
//Sort the files alphabetically then print each
allFiles.sort();
return allFiles;
},
ps : function(ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
}
updateDynamicRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptScanRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null){
workerScript.scriptRef.log("ps() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ps() failed. Invalid IP or hostname passed in: " + ip);
}
const processes = [];
for (const i in server.runningScripts) {
const script = server.runningScripts[i];
processes.push({filename:script.filename, threads: script.threads, args: script.args.slice()})
}
return processes;
},
hasRootAccess : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptHasRootAccessRamCost);
}
updateDynamicRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptHasRootAccessRamCost);
if (ip===undefined){
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null){
workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
}
return server.hasAdminRights;
},
getIp : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHostnameRamCost);
}
updateDynamicRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHostnameRamCost);
var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return scriptServer.ip;
},
getHostname : function(){
if (workerScript.checkingRam) {
return updateStaticRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHostnameRamCost);
}
updateDynamicRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHostnameRamCost);
var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return scriptServer.hostname;
},
getHackingLevel : function(){
if (workerScript.checkingRam) {
return updateStaticRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackingLevelRamCost);
}
updateDynamicRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackingLevelRamCost);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].updateSkillLevels();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) {
workerScript.scriptRef.log("getHackingLevel() returned " + _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_skill);
}
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_skill;
},
getHackingMultipliers : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
}
updateDynamicRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
return {
chance: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_chance_mult,
speed: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_speed_mult,
money: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_money_mult,
growth: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_grow_mult,
};
},
getHacknetMultipliers : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
}
updateDynamicRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
return {
production: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknet_node_money_mult,
purchaseCost: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknet_node_purchase_cost_mult,
ramCost: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknet_node_ram_cost_mult,
coreCost: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknet_node_core_cost_mult,
levelCost: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacknet_node_level_cost_mult,
};
},
getBitNodeMultipliers: function() {
if (workerScript.checkingRam) {
return updateStaticRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
}
updateDynamicRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetMultipliersRamCost);
if (!hasAISF) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run.");
}
let copy = Object.assign({}, _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"]);
return copy;
},
getServerMoneyAvailable : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);
}
if (server.hostname == "home") {
//Return player's money
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {
workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.toNumber(), 2));
}
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.toNumber();
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {
workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname);
}
return server.moneyAvailable;
},
getServerSecurityLevel : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) {
workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname);
}
return server.hackDifficulty;
},
getServerBaseSecurityLevel : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) {
workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname);
}
return server.baseDifficulty;
},
getServerMinSecurityLevel : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) {
workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname);
}
return server.minDifficulty;
},
getServerRequiredHackingLevel : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) {
workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname);
}
return server.requiredHackingSkill;
},
getServerMaxMoney : function(ip){
if (workerScript.checkingRam) {
return updateStaticRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) {
workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname);
}
return server.moneyMax;
},
getServerGrowth : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) {
workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname);
}
return server.serverGrowth;
},
getServerNumPortsRequired : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) {
workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname);
}
return server.numOpenPortsRequired;
},
getServerRam : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) {
workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(server.ramUsed, 2) + "GB]");
}
return [server.maxRam, server.ramUsed];
},
serverExists : function(ip) {
if (workerScript.checkingRam) {
return updateStaticRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
}
updateDynamicRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetServerRamCost);
return (Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip) !== null);
},
fileExists : function(filename,ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptFileExistsRamCost);
}
updateDynamicRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptFileExistsRamCost);
if (filename === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip);
}
for (var i = 0; i < server.scripts.length; ++i) {
if (filename == server.scripts[i].filename) {
return true;
}
}
for (var i = 0; i < server.programs.length; ++i) {
if (filename.toLowerCase() == server.programs[i].toLowerCase()) {
return true;
}
}
for (var i = 0; i < server.messages.length; ++i) {
if (!(server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_19__[/* Message */ "a"]) &&
filename.toLowerCase() === server.messages[i]) {
return true;
}
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_29__["getTextFile"])(filename, server);
if (txtFile != null) {
return true;
}
return false;
},
isRunning : function(filename,ip) {
if (workerScript.checkingRam) {
return updateStaticRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptIsRunningRamCost);
}
updateDynamicRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptIsRunningRamCost);
if (filename === undefined || ip === undefined) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip);
}
var argsForTargetScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForTargetScript.push(arguments[i]);
}
return (Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* findRunningScript */ "d"])(filename, argsForTargetScript, server) != null);
},
getStockSymbols : function(){
if (workerScript.checkingRam) {
return updateStaticRam("getStockSymbols", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
}
updateDynamicRam("getStockSymbols", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockSymbols()");
}
return Object.values(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* StockSymbols */ "d"]);
},
getStockPrice : function(symbol) {
if (workerScript.checkingRam) {
return updateStaticRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
}
updateDynamicRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into getStockPrice()");
}
return parseFloat(stock.price.toFixed(3));
},
getStockPosition : function(symbol) {
if (workerScript.checkingRam) {
return updateStaticRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
}
updateDynamicRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into getStockPosition()");
}
return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx];
},
buyStock : function(symbol, shares) {
if (workerScript.checkingRam) {
return updateStaticRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into buyStock()");
}
if (shares < 0 || isNaN(shares)) {
workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to buyStock()");
return 0;
}
shares = Math.round(shares);
if (shares === 0) {return 0;}
var totalPrice = stock.price * shares;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].StockMarketCommission)) {
workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(shares, 0) + " shares of " +
symbol + ". Need $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].StockMarketCommission, 2).toString());
return 0;
}
var origTotal = stock.playerShares * stock.playerAvgPx;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].StockMarketCommission);
var newTotal = origTotal + totalPrice;
stock.playerShares += shares;
stock.playerAvgPx = newTotal / stock.playerShares;
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__["Page"].StockMarket)) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* updateStockPlayerPosition */ "r"])(stock);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) {
workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(stock.price, 2) + " per share");
}
return stock.price;
},
sellStock : function(symbol, shares) {
if (workerScript.checkingRam) {
return updateStaticRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into sellStock()");
}
if (shares < 0 || isNaN(shares)) {
workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to sellStock()");
return 0;
}
shares = Math.round(shares);
if (shares > stock.playerShares) {shares = stock.playerShares;}
if (shares === 0) {return 0;}
var gains = stock.price * shares - _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].StockMarketCommission;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainMoney(gains);
//Calculate net profit and add to script stats
var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].StockMarketCommission;
if (isNaN(netProfit)) {netProfit = 0;}
workerScript.scriptRef.onlineMoneyMade += netProfit;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].scriptProdSinceLastAug += netProfit;
stock.playerShares -= shares;
if (stock.playerShares == 0) {
stock.playerAvgPx = 0;
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_36__["Page"].StockMarket)) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* updateStockPlayerPosition */ "r"])(stock);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) {
workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(stock.price, 2) + " per share. Gained " +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(gains, 2));
}
return stock.price;
},
shortStock(symbol, shares) {
if (workerScript.checkingRam) {
return updateStaticRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");
}
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()");
}
var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* shortStock */ "p"])(stock, shares, workerScript);
return res ? stock.price : 0;
},
sellShort(symbol, shares) {
if (workerScript.checkingRam) {
return updateStaticRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");
}
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()");
}
var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* sellShort */ "n"])(stock, shares, workerScript);
return res ? stock.price : 0;
},
placeOrder(symbol, shares, price, type, pos) {
if (workerScript.checkingRam) {
return updateStaticRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");
}
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()");
}
var orderType, orderPos;
type = type.toLowerCase();
if (type.includes("limit") && type.includes("buy")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].LimitBuy;
} else if (type.includes("limit") && type.includes("sell")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].LimitSell;
} else if (type.includes("stop") && type.includes("buy")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].StopBuy;
} else if (type.includes("stop") && type.includes("sell")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].StopSell;
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
}
pos = pos.toLowerCase();
if (pos.includes("l")) {
orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* PositionTypes */ "b"].Long;
} else if (pos.includes('s')) {
orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* PositionTypes */ "b"].Short;
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");
}
return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* placeOrder */ "l"])(stock, shares, price, orderType, orderPos, workerScript);
},
cancelOrder(symbol, shares, price, type, pos) {
if (workerScript.checkingRam) {
return updateStaticRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");
}
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()");
}
if (isNaN(shares) || isNaN(price)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric");
}
var orderType, orderPos;
type = type.toLowerCase();
if (type.includes("limit") && type.includes("buy")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].LimitBuy;
} else if (type.includes("limit") && type.includes("sell")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].LimitSell;
} else if (type.includes("stop") && type.includes("buy")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].StopBuy;
} else if (type.includes("stop") && type.includes("sell")) {
orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* OrderTypes */ "a"].StopSell;
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
}
pos = pos.toLowerCase();
if (pos.includes("l")) {
orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* PositionTypes */ "b"].Long;
} else if (pos.includes('s')) {
orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* PositionTypes */ "b"].Short;
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");
}
var params = {
stock: stock,
shares: shares,
price: price,
type: orderType,
pos: orderPos
};
return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* cancelOrder */ "f"])(params, workerScript);
},
getStockVolatility : function(symbol) {
if (workerScript.checkingRam) {
return updateStaticRam("getStockVolatility", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("getStockVolatility", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SDataTixApi) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have 4S Market Data TIX API Access! Cannot use getStockVolatility()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into getStockVolatility()");
}
return stock.mv / 100; //Convert from percentage to decimal
},
getStockForecast : function(symbol) {
if (workerScript.checkingRam) {
return updateStaticRam("getStockForecast", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("getStockForecast", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SDataTixApi) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have 4S Market Data TIX API Access! Cannot use getStockForecast()");
}
var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_27__[/* SymbolToStockMap */ "e"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into getStockForecast()");
}
var forecast = 50;
stock.b ? forecast += stock.otlkMag : forecast -= stock.otlkMag;
return forecast / 100; //Convert from percentage to decimal
},
purchase4SMarketData : function() {
if (workerScript.checkingRam) {
return updateStaticRam("purchase4SMarketData", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("purchase4SMarketData", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use purchase4SMarketData()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SData) {
if (workerScript.shouldLog("purchase4SMarketData")) {
workerScript.log("Already purchased 4S Market Data");
}
return true;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MarketData4SCost)) {
if (workerScript.shouldLog("purchase4SMarketData")) {
workerScript.log("Failed to purchase 4S Market Data - Not enough money");
}
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SData = true;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MarketData4SCost);
if (workerScript.shouldLog("purchase4SMarketData")) {
workerScript.log("Purchased 4S Market Data");
}
return true;
},
purchase4SMarketDataTixApi : function() {
if (workerScript.checkingRam) {
return updateStaticRam("purchase4SMarketDataTixApi", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
}
updateDynamicRam("purchase4SMarketDataTixApi", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBuySellStockRamCost);
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use purchase4SMarketDataTixApi()");
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SDataTixApi) {
if (workerScript.shouldLog("purchase4SMarketDataTixApi")) {
workerScript.log("Already purchased 4S Market Data TIX API");
}
return true;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MarketDataTixApi4SCost)) {
if (workerScript.shouldLog("purchase4SMarketDataTixApi")) {
workerScript.log("Failed to purchase 4S Market Data TIX API - Not enough money");
}
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].has4SDataTixApi = true;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].MarketDataTixApi4SCost);
if (workerScript.shouldLog("purchase4SMarketDataTixApi")) {
workerScript.log("Purchased 4S Market Data TIX API");
}
return true;
},
getPurchasedServerLimit : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getPurchasedServerLimit", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchasedServerLimit);
}
updateDynamicRam("getPurchasedServerLimit", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchasedServerLimit);
return _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerLimit;
},
getPurchasedServerMaxRam: function() {
if (workerScript.checkingRam) {
return updateStaticRam("getPurchasedServerMaxRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchasedServerMaxRam);
}
updateDynamicRam("getPurchasedServerMaxRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchasedServerMaxRam);
return _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerMaxRam;
},
getPurchasedServerCost: function(ram) {
if (workerScript.checkingRam) {
return updateStaticRam("getPurchasedServerCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchaseServerRamCost);
}
updateDynamicRam("getPurchasedServerCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetPurchaseServerRamCost);
let cost = 0;
try {
cost = getPurchaseServerRamCostGuard(ram);
} catch (e) {
workerScript.scriptRef.log("ERROR: 'getPurchasedServerCost()' " + e.message);
return Infinity;
}
return cost;
},
purchaseServer : function(hostname, ram) {
if (workerScript.checkingRam) {
return updateStaticRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
}
updateDynamicRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s+/g, '');
if (hostnameStr == "") {
workerScript.scriptRef.log("ERROR: Passed empty string for hostname argument of purchaseServer()");
return "";
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers.length >= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerLimit) {
workerScript.scriptRef.log("ERROR: You have reached the maximum limit of " + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].PurchasedServerLimit +
" servers. You cannot purchase any more.");
return "";
}
let cost = 0;
try {
cost = getPurchaseServerRamCostGuard(ram);
} catch (e) {
workerScript.scriptRef.log("ERROR: 'purchaseServer()' " + e.message);
return "";
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(cost)) {
workerScript.scriptRef.log("ERROR: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(cost, 2));
return "";
}
var newServ = new _Server__WEBPACK_IMPORTED_MODULE_23__[/* Server */ "d"]({
ip: Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_40__[/* createRandomIp */ "a"])(),
hostname: hostnameStr,
organizationName: "",
isConnectedTo: false,
adminRights: true,
purchasedByPlayer: true,
maxRam: ram,
});
Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* AddToAllServers */ "a"])(newServ);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers.push(newServ.ip);
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(cost);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) {
workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["formatNumber"])(cost, 2));
}
return newServ.hostname;
},
deleteServer : function(hostname) {
if (workerScript.checkingRam) {
return updateStaticRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
}
updateDynamicRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s\s+/g, '');
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* GetServerByHostname */ "c"])(hostnameStr);
if (server == null) {
workerScript.scriptRef.log("ERROR: Could not find server with hostname " + hostnameStr + ". deleteServer() failed");
return false;
}
if (!server.purchasedByPlayer || server.hostname === "home") {
workerScript.scriptRef.log("ERROR: Server " + server.hostname + " is not a purchased server. " +
"Cannot be deleted. deleteServer() failed");
return false;
}
var ip = server.ip;
//Can't delete server you're currently connected to
if (server.isConnectedTo) {
workerScript.scriptRef.log("ERROR: deleteServer() failed because you are currently connected to the server you are trying to delete");
return false;
}
//A server cannot delete itself
if (ip === workerScript.serverIp) {
workerScript.scriptRef.log("ERROR: Cannot call deleteServer() on self. deleteServer() failed");
return false;
}
//Delete all scripts running on server
if (server.runningScripts.length > 0) {
workerScript.scriptRef.log("ERROR: Cannot delete server " + server.hostname + " because it still has scripts running.");
return false;
}
//Delete from player's purchasedServers array
var found = false;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers.length; ++i) {
if (ip == _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers[i]) {
found = true;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers.splice(i, 1);
break;
}
}
if (!found) {
workerScript.scriptRef.log("ERROR: Could not identify server " + server.hostname +
"as a purchased server. This is likely a bug please contact game dev");
return false;
}
//Delete from all servers
delete _Server__WEBPACK_IMPORTED_MODULE_23__[/* AllServers */ "b"][ip];
//Delete from home computer
found = false;
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer();
for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (ip == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) {
workerScript.scriptRef.log("Deleted server " + hostnameStr);
}
return true;
}
}
//Wasn't found on home computer
workerScript.scriptRef.log("ERROR: Could not find server " + server.hostname +
"as a purchased server. This is likely a bug please contact game dev");
return false;
},
getPurchasedServers : function(hostname=true) {
if (workerScript.checkingRam) {
return updateStaticRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
}
updateDynamicRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptPurchaseServerRamCost);
var res = [];
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].purchasedServers.forEach(function(ip) {
if (hostname) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find server in getPurchasedServers(). This is a bug please report to game dev");
}
res.push(server.hostname);
} else {
res.push(ip);
}
});
return res;
},
write : function(port, data="", mode="a") {
if (workerScript.checkingRam) {
return updateStaticRam("write", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("write", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (!isNaN(port)) { //Write to port
//Port 1-10
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts + " are valid.");
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.write(data);
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(port)) { //Write to script or text file
var fn = port;
var server = workerScript.getServer();
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev");
}
if (Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(fn)) {
//Write to script
let script = workerScript.getScriptOnServer(fn);
if (script == null) {
//Create a new script
script = new _Script__WEBPACK_IMPORTED_MODULE_22__[/* Script */ "c"](fn, data, server.ip);
server.scripts.push(script);
return true;
}
mode === "w" ? script.code = data : script.code += data;
script.updateRamUsage();
} else {
//Write to text file
let txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_29__["getTextFile"])(fn, server);
if (txtFile == null) {
txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_29__["createTextFile"])(fn, data, server);
return true;
}
if (mode === "w") {
txtFile.write(data);
} else {
txtFile.append(data);
}
}
return true;
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for write: " + port);
}
},
tryWrite : function(port, data="") {
if (workerScript.checkingRam) {
return updateStaticRam("tryWrite", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("tryWrite", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (!isNaN(port)) {
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: tryWrite() called on invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts + " are valid.");
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.tryWrite(data);
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for tryWrite: " + port);
}
},
read : function(port) {
if (workerScript.checkingRam) {
return updateStaticRam("read", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("read", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (!isNaN(port)) { //Read from port
//Port 1-10
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts + " are valid.");
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.read();
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(port)) { //Read from script or text file
let fn = port;
let server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev");
}
if (Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(fn)) {
//Read from script
let script = workerScript.getScriptOnServer(fn);
if (script == null) {
return "";
}
return script.code;
} else {
//Read from text file
let txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_29__["getTextFile"])(fn, server);
if (txtFile !== null) {
return txtFile.text;
} else {
return "";
}
}
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for read(): " + port);
}
},
peek : function(port) {
if (workerScript.checkingRam) {
return updateStaticRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (isNaN(port)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts);
}
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.peek();
},
clear : function(port) {
if (workerScript.checkingRam) {
return updateStaticRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (!isNaN(port)) { //Clear port
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts + " are valid");
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.clear();
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(port)) { //Clear text file
var fn = port;
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev");
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_29__["getTextFile"])(fn, server);
if (txtFile != null) {
txtFile.write("");
}
} else {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for clear(): " + port);
}
return 0;
},
getPortHandle : function(port) {
if (workerScript.checkingRam) {
return updateStaticRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost * 10);
}
updateDynamicRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost * 10);
if (isNaN(port)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts);
}
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].NumNetscriptPorts + " are valid");
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_34__[/* NetscriptPort */ "a"])) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port;
},
rm : function(fn, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
}
updateDynamicRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptReadWriteRamCost);
if (ip == null || ip === "") {
ip = workerScript.serverIp;
}
var s = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (s == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `Invalid server specified for rm(): ${ip}`);
}
if (fn.includes(".exe")) {
for (var i = 0; i < s.programs.length; ++i) {
if (s.programs[i] === fn) {
s.programs.splice(i, 1);
return true;
}
}
} else if (Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(fn)) {
for (var i = 0; i < s.scripts.length; ++i) {
if (s.scripts[i].filename === fn) {
//Check that the script isnt currently running
for (var j = 0; j < s.runningScripts.length; ++j) {
if (s.runningScripts[j].filename === fn) {
workerScript.scriptRef.log("Cannot delete a script that is currently running!");
return false;
}
}
s.scripts.splice(i, 1);
return true;
}
}
} else if (fn.endsWith(".lit")) {
for (var i = 0; i < s.messages.length; ++i) {
var f = s.messages[i];
if (!(f instanceof _Message__WEBPACK_IMPORTED_MODULE_19__[/* Message */ "a"]) && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(f) && f === fn) {
s.messages.splice(i, 1);
return true;
}
}
} else if (fn.endsWith(".txt")) {
for (var i = 0; i < s.textFiles.length; ++i) {
if (s.textFiles[i].fn === fn) {
s.textFiles.splice(i, 1);
return true;
}
}
} else if (fn.endsWith(".cct")) {
for (var i = 0; i < s.contracts.length; ++i) {
if (s.contracts[i].fn === fn) {
s.contracts.splice(i, 1);
return true;
}
}
}
return false;
},
scriptRunning : function(scriptname, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptArbScriptRamCost);
}
updateDynamicRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptArbScriptRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
}
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) {
return true;
}
}
return false;
},
scriptKill : function(scriptname, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptArbScriptRamCost);
}
updateDynamicRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptArbScriptRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip);
}
var suc = false;
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) {
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* killWorkerScript */ "d"])(server.runningScripts[i], server.ip);
suc = true;
}
}
return suc;
},
getScriptName : function() {
if (workerScript.checkingRam) {return 0;}
return workerScript.name;
},
getScriptRam : function (scriptname, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
}
updateDynamicRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
}
for (var i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) {
return server.scripts[i].ramUsage;
}
}
return 0;
},
getHackTime : function(ip, hack, int) {
if (workerScript.checkingRam) {
return updateStaticRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
}
updateDynamicRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateHackingTime */ "d"])(server, hack, int); //Returns seconds
},
getGrowTime : function(ip, hack, int) {
if (workerScript.checkingRam) {
return updateStaticRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
}
updateDynamicRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateGrowTime */ "a"])(server, hack, int); //Returns seconds
},
getWeakenTime : function(ip, hack, int) {
if (workerScript.checkingRam) {
return updateStaticRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
}
updateDynamicRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_12__[/* calculateWeakenTime */ "f"])(server, hack, int); //Returns seconds
},
getScriptIncome : function(scriptname, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
}
updateDynamicRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
if (arguments.length === 0) {
//Get total script income
var res = [];
res.push(Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* updateActiveScriptsItems */ "c"])());
res.push(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].scriptProdSinceLastAug / (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].playtimeSinceLastAug/1000));
return res;
} else {
//Get income for a particular script
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
}
var argsForScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]);
}
var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* findRunningScript */ "d"])(scriptname, argsForScript, server);
if (runningScriptObj == null) {
workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForScript));
return -1;
}
return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime;
}
},
getScriptExpGain : function(scriptname, ip) {
if (workerScript.checkingRam) {
return updateStaticRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
}
updateDynamicRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetScriptRamCost);
if (arguments.length === 0) {
var total = 0;
for (var i = 0; i < _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* workerScripts */ "h"].length; ++i) {
total += (_NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* workerScripts */ "h"][i].scriptRef.onlineExpGained / _NetscriptWorker__WEBPACK_IMPORTED_MODULE_32__[/* workerScripts */ "h"][i].scriptRef.onlineRunningTime);
}
return total;
} else {
//Get income for a particular script
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* getServer */ "e"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
}
var argsForScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]);
}
var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* findRunningScript */ "d"])(scriptname, argsForScript, server);
if (runningScriptObj == null) {
workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_39__["arrayToString"])(argsForScript));
return -1;
}
return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime;
}
},
getTimeSinceLastAug : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
}
updateDynamicRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetHackTimeRamCost);
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].playtimeSinceLastAug;
},
prompt : function(txt) {
if (workerScript.checkingRam) {return 0;}
if (_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxOpen */ "e"]) {
workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open");
return false;
}
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(txt)) {txt = String(txt);}
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Yes";
noBtn.innerHTML = "No";
return new Promise(function(resolve, reject) {
yesBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxClose */ "a"])();
resolve(true);
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxClose */ "a"])();
resolve(false);
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_43__[/* yesNoBoxCreate */ "b"])(txt);
});
},
wget : async function(url, target, ip=workerScript.serverIp) {
if (workerScript.checkingRam) { return 0; }
if (!Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(target) && !target.endsWith(".txt")) {
workerSript.log(`ERROR: wget() failed because of an invalid target file: ${target}. Target file must be a script or text file`);
return Promise.resolve(false);
}
var s = safeGetServer(ip, "wget");
return new Promise(function(resolve, reject) {
$.get(url, function(data) {
let res;
if (Object(_Script__WEBPACK_IMPORTED_MODULE_22__[/* isScriptFilename */ "e"])(target)) {
res = s.writeToScriptFile(target, data);
} else {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
workerScript.log("ERROR: wget() failed");
return resolve(false);
}
if (res.overwritten) {
workerScript.log(`wget() successfully retrieved content and overwrote ${target} on ${ip}`);
return resolve(true);
}
workerScript.log(`wget successfully retrieved content to new file ${target} on ${ip}`);
return resolve(true);
}, 'text').fail(function(e) {
workerScript.log(`ERROR: wget() failed: ${JSON.stringify(e)}`);
return resolve(false)
});
});
},
getFavorToDonate: function() {
if (workerScript.checkingRam) {
return updateStaticRam("getFavorToDonate", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetFavorToDonate);
}
updateDynamicRam("getFavorToDonate", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGetFavorToDonate);
return Math.floor(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].BaseFavorToDonate * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].RepToDonateToFaction);
},
/* Singularity Functions */
universityCourse : function(universityName, className) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("universityCourse", ramCost);
}
updateDynamicRam("universityCourse", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {
workerScript.scriptRef.log(txt);
}
}
var costMult, expMult;
switch(universityName.toLowerCase()) {
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumSummitUniversity.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumSummitUniversity;
costMult = 4;
expMult = 3;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12RothmanUniversity.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12RothmanUniversity;
costMult = 3;
expMult = 2;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Volhaven) {
workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenZBInstituteOfTechnology;
costMult = 5;
expMult = 4;
break;
default:
workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed");
return false;
}
var task;
switch(className.toLowerCase()) {
case "Study Computer Science".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassStudyComputerScience;
break;
case "Data Structures".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassDataStructures;
break;
case "Networks".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassNetworks;
break;
case "Algorithms".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassAlgorithms;
break;
case "Management".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassManagement;
break;
case "Leadership".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassLeadership;
break;
default:
workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startClass(costMult, expMult, task);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {
workerScript.scriptRef.log("Started " + task + " at " + universityName);
}
return true;
},
gymWorkout : function(gymName, stat) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("gymWorkout", ramCost);
}
updateDynamicRam("gymWorkout", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {
workerScript.scriptRef.log(txt);
}
}
var costMult, expMult;
switch(gymName.toLowerCase()) {
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumCrushFitnessGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumCrushFitnessGym;
costMult = 3;
expMult = 2;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumSnapFitnessGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumSnapFitnessGym;
costMult = 10;
expMult = 5;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12IronGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12IronGym;
costMult = 1;
expMult = 1;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12PowerhouseGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12PowerhouseGym;
costMult = 20;
expMult = 10;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenMilleniumFitnessGym:
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Volhaven) {
workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenMilleniumFitnessGym;
costMult = 7;
expMult = 4;
break;
default:
workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed");
return false;
}
switch(stat.toLowerCase()) {
case "strength".toLowerCase():
case "str".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymStrength);
break;
case "defense".toLowerCase():
case "def".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDefense);
break;
case "dexterity".toLowerCase():
case "dex".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymDexterity);
break;
case "agility".toLowerCase():
case "agi".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ClassGymAgility);
break;
default:
workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed");
return false;
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {
workerScript.scriptRef.log("Started training " + stat + " at " + gymName);
}
return true;
},
travelToCity(cityname) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("travelToCity", ramCost);
}
updateDynamicRam("travelToCity", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
switch(cityname) {
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum:
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing:
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12:
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyo:
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Ishima:
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Volhaven:
if(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].TravelCost)) {
workerScript.scriptRef.log("ERROR: not enough money to travel with travelToCity().");
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: not enough money to travel with travelToCity().");
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].TravelCost);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city = cityname;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) {
workerScript.scriptRef.log("Traveled to " + cityname);
}
return true;
default:
workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity().");
return false;
}
},
purchaseTor() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseTor", ramCost);
}
updateDynamicRam("purchaseTor", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_25__[/* SpecialServerIps */ "a"]["Darkweb Server"] != null) {
workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed");
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].TorRouterCost)) {
workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].TorRouterCost);
var darkweb = new _Server__WEBPACK_IMPORTED_MODULE_23__[/* Server */ "d"]({
ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_40__[/* createRandomIp */ "a"])(), hostname:"darkweb", organizationName:"",
isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1
});
Object(_Server__WEBPACK_IMPORTED_MODULE_23__[/* AddToAllServers */ "a"])(darkweb);
_SpecialServerIps__WEBPACK_IMPORTED_MODULE_25__[/* SpecialServerIps */ "a"].addIp("Darkweb Server", darkweb.ip);
const purchaseTor = document.getElementById("location-purchase-tor");
purchaseTor.setAttribute("class", "a-link-button-bought");
purchaseTor.innerHTML = "TOR Router - Purchased";
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer().ip);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) {
workerScript.scriptRef.log("You have purchased a Tor router!");
}
return true;
},
purchaseProgram(programName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseProgram", ramCost);
}
updateDynamicRam("purchaseProgram", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_25__[/* SpecialServerIps */ "a"]["Darkweb Server"] == null) {
workerScript.scriptRef.log("ERROR: You do not have the TOR router. purchaseProgram() failed.");
return false;
}
programName = programName.toLowerCase();
let item = null;
for(const key in _DarkWeb__WEBPACK_IMPORTED_MODULE_11__[/* DarkWebItems */ "a"]) {
const i = _DarkWeb__WEBPACK_IMPORTED_MODULE_11__[/* DarkWebItems */ "a"][key];
if(i.program.toLowerCase() == programName) {
item = i;
}
}
if(item == null) {
workerScript.scriptRef.log("ERROR: Invalid program name passed into purchaseProgram().");
return false;
}
if(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(item.price)) {
workerScript.scriptRef.log("Not enough money to purchase " + item.program);
return false;
}
if(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(item.program)) {
workerScript.scriptRef.log('You already have the '+item.program+' program');
return true;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(item.price);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer().programs.push(item.program);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
workerScript.scriptRef.log("You have purchased the "+item.program+" program. The new program can be found on your home computer.");
}
return true;
},
getStats : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getStats", ramCost);
}
updateDynamicRam("getStats", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return {};
}
}
return {
hacking: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_skill,
strength: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].strength,
defense: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].defense,
dexterity: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].dexterity,
agility: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].agility,
charisma: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].charisma,
intelligence: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].intelligence
}
},
getCharacterInformation : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getCharacterInformation", ramCost);
}
updateDynamicRam("getCharacterInformation", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return {};
}
}
var companyPositionTitle = "";
if (_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_8__["CompanyPositions"][_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition] instanceof _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_7__["CompanyPosition"]) {
companyPositionTitle = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition;
}
return {
bitnode: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN,
city: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city,
company: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyName,
factions: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factions.slice(),
jobTitle: companyPositionTitle,
mult: {
agility: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].agility_mult,
agilityExp: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].agility_exp_mult,
companyRep: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].company_rep_mult,
crimeMoney: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].crime_money_mult,
crimeSuccess: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].crime_success_mult,
defense: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].defense_mult,
defenseExp: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].defense_exp_mult,
dexterity: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].dexterity_mult,
dexterityExp: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].dexterity_exp_mult,
factionRep: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].faction_rep_mult,
hacking: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_mult,
hackingExp: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hacking_exp_mult,
strength: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].strength_mult,
strengthExp: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].strength_exp_mult,
workMoney: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].work_money_mult,
},
timeWorked: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].timeWorked,
tor: _SpecialServerIps__WEBPACK_IMPORTED_MODULE_25__[/* SpecialServerIps */ "a"].hasOwnProperty("Darkweb Server"),
workHackExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workHackExpGained,
workStrExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workStrExpGained,
workDefExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workDefExpGained,
workDexExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workDexExpGained,
workAgiExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workAgiExpGained,
workChaExpGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workChaExpGained,
workRepGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workRepGained,
workMoneyGain: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].workMoneyGained,
};
},
isBusy : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("isBusy", ramCost);
}
updateDynamicRam("isBusy", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return;
}
}
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking;
},
stopAction : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn1RamCost / 2;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("stopAction", ramCost);
}
updateDynamicRam("stopAction", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) {
workerScript.scriptRef.log(txt);
}
return true;
}
return false;
},
upgradeHomeRam : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("upgradeHomeRam", ramCost);
}
updateDynamicRam("upgradeHomeRam", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
const cost = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getUpgradeHomeRamCost();
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(cost)) {
workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money");
return false;
}
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getHomeComputer();
homeComputer.maxRam *= 2;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) {
workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
}
return true;
},
getUpgradeHomeRamCost : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost / 2;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getUpgradeHomeRamCost", ramCost);
}
updateDynamicRam("getUpgradeHomeRamCost", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].getUpgradeHomeRamCost();
},
workForCompany : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("workForCompany", ramCost);
}
updateDynamicRam("workForCompany", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission.");
return;
}
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_8__["CompanyPositions"][_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition];
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition === "" || !(companyPosition instanceof _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_7__["CompanyPosition"])) {
workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job");
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
workerScript.scriptRef.log(txt);
}
}
if (companyPosition.isPartTimeJob()) {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startWorkPartTime();
} else {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startWork();
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
workerScript.log(`Began working at ${_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyName} as a ${_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition}`);
}
return true;
},
applyToCompany : function(companyName, field) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("applyToCompany", ramCost);
}
updateDynamicRam("applyToCompany", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (!Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["companyExists"])(companyName)) {
workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = companyName;
var res;
switch (field.toLowerCase()) {
case "software":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForSoftwareJob(true);
break;
case "software consultant":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForSoftwareConsultantJob(true);
break;
case "it":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForItJob(true);
break;
case "security engineer":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForSecurityEngineerJob(true);
break;
case "network engineer":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForNetworkEngineerJob(true);
break;
case "business":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForBusinessJob(true);
break;
case "business consultant":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForBusinessConsultantJob(true);
break;
case "security":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForSecurityJob(true);
break;
case "agent":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForAgentJob(true);
break;
case "employee":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForEmployeeJob(true);
break;
case "part-time employee":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForPartTimeEmployeeJob(true);
break;
case "waiter":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForWaiterJob(true);
break;
case "part-time waiter":
res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].applyForPartTimeWaiterJob(true);
break;
default:
workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed");
return false;
}
//The Player object's applyForJob function can return string with special error messages
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(res)) {
workerScript.scriptRef.log(res);
return false;
}
if (res) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {
workerScript.log(`You were offered a new job at ${companyName} as a ${_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].companyPosition}`);
}
} else {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {
workerScript.log(`You failed to get a new job/promotion at ${companyName} in the ${field} field.`);
}
}
return res;
},
getCompanyRep : function(companyName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost / 2;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getCompanyRep", ramCost);
}
updateDynamicRam("getCompanyRep", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"][companyName];
if (company == null || !(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_5__["Company"])) {
workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName);
return -1;
}
return company.playerReputation;
},
getCompanyFavor : function(companyName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getCompanyFavor", ramCost);
}
updateDynamicRam("getCompanyFavor", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"][companyName];
if (company == null || !(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_5__["Company"])) {
workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName);
return -1;
}
return company.favor;
},
getCompanyFavorGain : function(companyName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getCompanyFavorGain", ramCost);
}
updateDynamicRam("getCompanyFavorGain", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return -1;
}
}
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"][companyName];
if (company == null || !(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_5__["Company"])) {
workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavorGain(): " + companyName);
return -1;
}
return company.getFavorGain()[0];
},
checkFactionInvitations : function() {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("checkFactionInvitations", ramCost);
}
updateDynamicRam("checkFactionInvitations", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
//Make a copy of Player.factionInvitations
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations.slice();
},
joinFaction : function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("joinFaction", ramCost);
}
updateDynamicRam("joinFaction", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist.");
return false;
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations.includes(name)) {
workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");
return false;
}
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name];
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_16__[/* joinFaction */ "c"])(fac);
//Update Faction Invitation list to account for joined + banned factions
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations[i] == name || _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations[i]].isBanned) {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factionInvitations.splice(i, 1);
i--;
}
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) {
workerScript.scriptRef.log("Joined the " + name + " faction.");
}
return true;
},
workForFaction : function(name, type) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("workForFaction", ramCost);
}
updateDynamicRam("workForFaction", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
// if the player is in a gang and the target faction is any of the gang faction, fail
if(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].inGang() && _Gang__WEBPACK_IMPORTED_MODULE_13__[/* AllGangs */ "a"][name] !== undefined) {
workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not offer work at the moment.");
return;
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission.");
return;
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist.");
return false;
}
if (!_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].factions.includes(name)) {
workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) {
workerScript.scriptRef.log(txt);
}
}
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name];
//Arrays listing factions that allow each time of work
var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",
"Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma", "KuaiGong International",
"Fulcrum Secret Technologies", "BitRunners", "The Black Hand",
"NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",
"The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"];
var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",
"Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma", "KuaiGong International",
"The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",
"The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"];
var scWkAvailable = ["ECorp", "MegaCorp",
"Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma", "KuaiGong International",
"Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Speakers for the Dead",
"The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"];
switch (type.toLowerCase()) {
case "hacking":
case "hacking contracts":
case "hackingcontracts":
if (!hackAvailable.includes(fac.name)) {
workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startFactionHackWork(fac);
workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name);
return true;
case "field":
case "fieldwork":
case "field work":
if (!fdWkAvailable.includes(fac.name)) {
workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startFactionFieldWork(fac);
workerScript.scriptRef.log("Started carrying out field missions for " + fac.name);
return true;
case "security":
case "securitywork":
case "security work":
if (!scWkAvailable.includes(fac.name)) {
workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startFactionSecurityWork(fac);
workerScript.scriptRef.log("Started serving as security details for " + fac.name);
return true;
default:
workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type);
}
return true;
},
getFactionRep : function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getFactionRep", ramCost);
}
updateDynamicRam("getFactionRep", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return -1;
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist.");
return -1;
}
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].playerReputation;
},
getFactionFavor : function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getFactionFavor", ramCost);
}
updateDynamicRam("getFactionFavor", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return -1;
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist.");
return -1;
}
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].favor;
},
getFactionFavorGain: function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getFactionFavorGain", ramCost);
}
updateDynamicRam("getFactionFavorGain", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return -1;
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavorGain() does not exist.");
return -1;
}
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].getFavorGain()[0];
},
donateToFaction : function(name, amt) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("donateToFaction", ramCost);
}
updateDynamicRam("donateToFaction", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run donateToFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return;
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(name)) {
workerScript.log(`ERROR: Faction specified in donateToFaction() does not exist: ${name}`);
return false;
}
if (typeof amt !== 'number' || amt <= 0) {
workerScript.log(`ERROR: Invalid donation amount specified in donateToFaction(): ${amt}. Must be numeric and positive`);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].money.lt(amt)) {
workerScript.log(`ERROR: You do not have enough money to donate $${amt} to ${name}`);
return false;
}
var repNeededToDonate = Math.round(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].BaseFavorToDonate * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].RepToDonateToFaction);
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].favor < repNeededToDonate) {
workerScript.log(`ERROR: You do not have enough favor to donate to this faction. Have ${_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].favor}, need ${repNeededToDonate}`);
return false;
}
var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].faction_rep_mult;
_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][name].playerReputation += repGain;
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].loseMoney(amt);
if (workerScript.shouldLog("donateToFaction")) {
workerScript.log(`$${amt} donated to ${name} for ${repGain} reputation`);
}
return true;
},
createProgram : function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("createProgram", ramCost);
}
updateDynamicRam("createProgram", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {
workerScript.scriptRef.log(txt);
}
}
name = name.toLowerCase();
let p = null;
for (const key in _CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"]) {
if(_CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"][key].name.toLowerCase() == name) {
p = _CreateProgram__WEBPACK_IMPORTED_MODULE_10__[/* Programs */ "a"][key];
}
}
if (p == null) {
workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].hasProgram(p.name)) {
workerScript.scriptRef.log('ERROR: createProgram() failed because you already have the ' + p.name + ' program');
return false;
}
if (!p.create.req()) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create " + p.name + " (level " + p.create.level + " req)");
return false
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].startCreateProgramWork(p.name, p.create.time, p.create.level);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {
workerScript.scriptRef.log("Began creating program: " + name);
}
return true;
},
commitCrime : function(crimeRoughName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("commitCrime", ramCost);
}
updateDynamicRam("commitCrime", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return;
}
}
if (_Missions__WEBPACK_IMPORTED_MODULE_20__[/* inMission */ "c"]) {
workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) {
workerScript.scriptRef.log(txt);
}
}
//Set Location to slums
switch(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].city) {
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Aevum:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].AevumSlums;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Chongqing:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].ChongqingSlums;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Sector12Slums;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyo:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].NewTokyoSlums;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Ishima:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].IshimaSlums;
break;
case _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].Volhaven:
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_18__["Locations"].VolhavenSlums;
break;
default:
console.log("Invalid Player.city value");
}
const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__[/* findCrime */ "c"])(crimeRoughName.toLowerCase());
if(crime == null) { // couldn't find crime
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid crime passed into commitCrime(): " + crimeRoughName);
}
if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) {
workerScript.scriptRef.log("Attempting to commit crime: "+crime.name+"...");
}
return crime.commit(1, {workerscript: workerScript});
},
getCrimeChance : function(crimeRoughName) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getCrimeChance", ramCost);
}
updateDynamicRam("getCrimeChance", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return;
}
}
const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__[/* findCrime */ "c"])(crimeRoughName.toLowerCase());
if(crime == null) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime);
}
return crime.successRate();
},
getOwnedAugmentations : function(purchased=false) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getOwnedAugmentations", ramCost);
}
updateDynamicRam("getOwnedAugmentations", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return [];
}
}
var res = [];
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].augmentations.length; ++i) {
res.push(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].augmentations[i].name);
}
if (purchased) {
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].queuedAugmentations.length; ++i) {
res.push(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].queuedAugmentations[i].name);
}
}
return res;
},
getOwnedSourceFiles : function() {
let ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getOwnedSourceFiles", ramCost);
}
updateDynamicRam("getOwnedSourceFiles", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getOwnedSourceFiles(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return [];
}
}
let res = [];
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles.length; ++i) {
res.push({n: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].n, lvl: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].sourceFiles[i].lvl});
}
return res;
},
getAugmentationsFromFaction : function(facname) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getAugmentationsFromFaction", ramCost);
}
updateDynamicRam("getAugmentationsFromFaction", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return [];
}
}
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["factionExists"])(facname)) {
workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname);
return [];
}
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][facname];
var res = [];
for (var i = 0; i < fac.augmentations.length; ++i) {
res.push(fac.augmentations[i]);
}
return res;
},
getAugmentationCost : function(name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("getAugmentationCost", ramCost);
}
updateDynamicRam("getAugmentationCost", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (!Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "f"])(name)) {
workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name);
return [-1, -1];
}
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][name];
return [aug.baseRepRequirement, aug.baseCost];
},
purchaseAugmentation : function(faction, name) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseAugmentation", ramCost);
}
updateDynamicRam("purchaseAugmentation", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_15__["Factions"][faction];
if (fac == null || !(fac instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_14__["Faction"])) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction);
return false;
}
if (!fac.augmentations.includes(name)) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation");
return false;
}
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][name];
if (aug == null || !(aug instanceof _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentation */ "a"])) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name);
return false;
}
var isNeuroflux = false;
if (aug.name === _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
isNeuroflux = true;
}
if (!isNeuroflux) {
for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].queuedAugmentations[j].name === aug.name) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);
return false;
}
}
for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].augmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].augmentations[j].name === aug.name) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);
return false;
}
}
}
if (fac.playerReputation < aug.baseRepRequirement) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name);
return false;
}
var res = Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_16__[/* purchaseAugmentation */ "e"])(aug, fac, true);
workerScript.scriptRef.log(res);
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_42__["isString"])(res) && res.startsWith("You purchased")) {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
return true;
} else {
return false;
}
},
installAugmentations : function(cbScript) {
var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptSingularityFnRamMult;}
if (workerScript.checkingRam) {
return updateStaticRam("installAugmentations", ramCost);
}
updateDynamicRam("installAugmentations", ramCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].queuedAugmentations.length === 0) {
workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed");
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* installAugmentations */ "i"])(cbScript);
return true;
},
// Gang API
gang : {
getMemberNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getMemberNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
}
updateDynamicRam("getMemberNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getMemberNames");
try {
const names = [];
for (const member of _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.members) {
names.push(member.name);
}
return names;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getMemberNames", e));
}
},
getGangInformation : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getGangInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("getGangInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getGangInformation");
try {
return {
faction: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.facName,
isHacking: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.isHackingGang,
moneyGainRate: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.moneyGainRate,
power: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getPower(),
respect: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.respect,
respectGainRate: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.respectGainRate,
territory: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getTerritory(),
territoryClashChance: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.territoryClashChance,
territoryWarfareEngaged: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.territoryWarfareEngaged,
wantedLevel: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.wanted,
wantedLevelGainRate: _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.wantedGainRate,
}
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getGangInformation", e));
}
},
getOtherGangInformation : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getOtherGangInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("getOtherGangInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getOtherGangInformation");
try {
return Object.assign(_Gang__WEBPACK_IMPORTED_MODULE_13__[/* AllGangs */ "a"]);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getOtherGangInformation", e));
}
},
getMemberInformation : function(name) {
if (workerScript.checkingRam) {
return updateStaticRam("getMemberInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("getMemberInformation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getMemberInformation");
try {
for (const member of _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.members) {
if (member.name === name) {
return {
agility: member.agi,
agilityEquipMult: member.agi_mult,
agilityAscensionMult: member.agi_asc_mult,
augmentations: member.augmentations.slice(),
charisma: member.cha,
charismaEquipMult: member.cha_mult,
charismaAscensionMult: member.cha_asc_mult,
defense: member.def,
defenseEquipMult: member.def_mult,
defenseAscensionMult: member.def_asc_mult,
dexterity: member.dex,
dexterityEquipMult: member.dex_mult,
dexterityAscensionMult: member.dex_asc_mult,
equipment: member.upgrades.slice(),
hacking: member.hack,
hackingEquipMult: member.hack_mult,
hackingAscensionMult: member.hack_asc_mult,
strength: member.str,
strengthEquipMult: member.str_mult,
strengthAscensionMult: member.str_asc_mult,
task: member.task,
}
}
}
workerScript.log(`Invalid argument passed to gang.getMemberInformation(). No gang member could be found with name ${name}`);
return {}; // Member could not be found
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getMemberInformation", e));
}
},
canRecruitMember : function() {
if (workerScript.checkingRam) {
return updateStaticRam("canRecruitMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
}
updateDynamicRam("canRecruitMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "canRecruitMember");
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.canRecruitMember();
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("canRecruitMember", e));
}
},
recruitMember : function(name) {
if (workerScript.checkingRam) {
return updateStaticRam("recruitMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("recruitMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "recruitMember");
try {
const res = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.recruitMember(name);
if (workerScript.shouldLog("recruitMember")) {
if (res) {
workerScript.log(`Successfully recruited Gang Member ${name}`);
} else {
workerScript.log(`Failed to recruit Gang Member ${name}`);
}
}
return res;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("recruitMember", e));
}
},
getTaskNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getTaskNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
}
updateDynamicRam("getTaskNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getTaskNames");
try {
const tasks = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getAllTaskNames();
tasks.unshift("Unassigned");
return tasks;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getTaskNames", e));
}
},
setMemberTask : function(memberName, taskName) {
if (workerScript.checkingRam) {
return updateStaticRam("setMemberTask", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("setMemberTask", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "setMemberTask");
try {
for (const member of _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.members) {
if (member.name === memberName) {
const res = member.assignToTask(taskName);
if (workerScript.shouldLog("setMemberTask")) {
if (res) {
workerScript.log(`Successfully assigned Gang Member ${memberName} to ${taskName} task`);
} else {
workerScript.log(`Failed to assign Gang Member ${memberName} to ${taskName} task. ${memberName} is now Unassigned`);
}
}
return res;
}
}
workerScript.log(`Invalid argument passed to gang.setMemberTask(). No gang member could be found with name ${memberName}`);
return false;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("setMemberTask", e));
}
},
getEquipmentNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getEquipmentNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
}
updateDynamicRam("getEquipmentNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 4);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getEquipmentNames");
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getAllUpgradeNames();
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getEquipmentNames", e));
}
},
getEquipmentCost : function(equipName) {
if (workerScript.checkingRam) {
return updateStaticRam("getEquipmentCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("getEquipmentCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getEquipmentCost");
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getUpgradeCost(equipName);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getEquipmentCost", e));
}
},
getEquipmentType : function(equipName) {
if (workerScript.checkingRam) {
return updateStaticRam("getEquipmentType", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("getEquipmentType", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getEquipmentType");
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.getUpgradeType(equipName);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getEquipmentType", e));
}
},
purchaseEquipment : function(memberName, equipName) {
if (workerScript.checkingRam) {
return updateStaticRam("purchaseEquipment", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
}
updateDynamicRam("purchaseEquipment", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "purchaseEquipment");
try {
for (const member of _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.members) {
if (member.name === memberName) {
const res = member.buyUpgrade(equipName, _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"], _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang);
if (workerScript.shouldLog("purchaseEquipment")) {
if (res) {
workerScript.log(`Purchased ${equipName} for Gang member ${memberName}`);
} else {
workerScript.log(`Failed to purchase ${equipName} for Gang member ${memberName}`);
}
}
return res;
}
}
workerScript.log(`Invalid argument passed to gang.purchaseEquipment(). No gang member could be found with name ${memberName}`);
return false;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("purchaseEquipment", e));
}
},
ascendMember : function(name) {
if (workerScript.checkingRam) {
return updateStaticRam("ascendMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
}
updateDynamicRam("ascendMember", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "ascendMember");
try {
for (const member of _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.members) {
if (member.name === name) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.ascendMember(member, workerScript);
}
}
workerScript.log(`Invalid argument passed to gang.ascendMember(). No gang member could be found with name ${name}`);
return false;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("ascendMember", e));
}
},
setTerritoryWarfare : function(engage) {
if (workerScript.checkingRam) {
return updateStaticRam("setTerritoryWarfare", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
}
updateDynamicRam("setTerritoryWarfare", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost / 2);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "setTerritoryWarfare");
try {
if (engage) {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.territoryWarfareEngaged = true;
if (workerScript.shouldLog("setTerritoryWarfare")) {
workerScript.log("Engaging in Gang Territory Warfare");
}
} else {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.territoryWarfareEngaged = false;
if (workerScript.shouldLog("setTerritoryWarfare")) {
workerScript.log("Disengaging in Gang Territory Warfare");
}
}
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("setTerritoryWarfare", e));
}
},
getChanceToWinClash : function(otherGang) {
if (workerScript.checkingRam) {
return updateStaticRam("getChanceToWinClash", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
}
updateDynamicRam("getChanceToWinClash", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptGangApiBaseRamCost);
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getChanceToWinClash");
try {
if (_Gang__WEBPACK_IMPORTED_MODULE_13__[/* AllGangs */ "a"][otherGang] == null) {
workerScript.log(`Invalid gang specified in gang.getChanceToWinClash() : ${otherGang}`);
return 0;
}
const playerPower = _Gang__WEBPACK_IMPORTED_MODULE_13__[/* AllGangs */ "a"][_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.facName].power;
const otherPower = _Gang__WEBPACK_IMPORTED_MODULE_13__[/* AllGangs */ "a"][otherGang].power;
return playerPower / (otherPower + playerPower);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getChanceToWinClash", e));
}
},
getBonusTime : function() {
if (workerScript.checkingRam) { return 0; }
_NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* checkGangApiAccess */ "a"](workerScript, "getBonusTime");
try {
return Math.round(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gang.storedCycles / 5);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, _NetscriptGang__WEBPACK_IMPORTED_MODULE_31__[/* unknownGangApiExceptionMessage */ "b"]("getBonusTime", e));
}
},
}, // end gang namespace
// Bladeburner API
bladeburner : {
getContractNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getContractNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getContractNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getOperationNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getOperationNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getOperationNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getBlackOpNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getBlackOpNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getBlackOpNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getGeneralActionNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getGeneralActionNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getGeneralActionNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getSkillNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getSkillNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
startAction : function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.startActionNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.startAction() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "startAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
stopBladeburnerAction : function() {
if (workerScript.checkingRam) {
return updateStaticRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2);
}
updateDynamicRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.resetAction();
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "stopBladeburnerAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getCurrentAction : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getCurrentAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 4);
}
updateDynamicRam("getCurrentAction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 4);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getTypeAndNameFromActionId(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.action);
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCurrentAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getActionTime : function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionTimeNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionTime() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getActionEstimatedSuccessChance : function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionEstimatedSuccessChanceNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionEstimatedSuccessChance() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionEstimatedSuccessChance() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getActionRepGain: function(type="", name="", level) {
if (workerScript.checkingRam) {
return updateStaticRam("getActionRepGain", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionRepGain", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionRepGain");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionAutolevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
var rewardMultiplier;
if (level == null || isNaN(level)) {
rewardMultiplier = Math.pow(actionObj.rewardFac, actionObj.level - 1);
} else {
rewardMultiplier = Math.pow(actionObj.rewardFac, level - 1);
}
return actionObj.rankGain * rewardMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerRank;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionAutolevel", err));
}
},
getActionCountRemaining : function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionCountRemaining() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionCountRemaining() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getActionMaxLevel: function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionMaxLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionMaxLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionMaxLevel");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionMaxLevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
return actionObj.maxLevel;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionMaxLevel", err));
}
},
getActionCurrentLevel: function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionCurrentLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionCurrentLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionCurrentLevel");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionCurrentLevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return -1;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return -1;
}
return actionObj.level;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionCurrentLevel", err));
}
},
getActionAutolevel: function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionAutolevel");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionAutolevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return false;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return false;
}
return actionObj.autoLevel;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionAutolevel", err));
}
},
setActionAutolevel: function(type="", name="", autoLevel=true) {
if (workerScript.checkingRam) {
return updateStaticRam("setActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("setActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "setActionAutolevel");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("setActionAutolevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return;
}
actionObj.autoLevel = autoLevel;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("setActionAutolevel", err));
}
},
setActionLevel: function(type="", name="", level=1) {
if (workerScript.checkingRam) {
return updateStaticRam("setActionLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("setActionLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* checkBladeburnerAccess */ "a"])(workerScript, "setActionLevel");
try {
var errorLogText = Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerActionErrorMessage */ "b"])("setActionLevel", type, name);
const actionId = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log(errorLogText);
return;
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getActionObject(actionId);
if (actionObj == null) {
workerScript.log(errorLogText);
return;
}
if(level > actionObj.maxLevel) {
workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level exceeds max level for given action.`);
return;
}
if(level < 1) {
workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level is below 1.`);
return;
}
actionObj.level = level;
} catch(err) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner__WEBPACK_IMPORTED_MODULE_30__[/* unknownBladeburnerExceptionMessage */ "c"])("setActionLevel", err));
}
},
getRank : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.rank;
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getRank() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getSkillPoints : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.skillPoints;
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillPoints() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getSkillLevel : function(skillName="") {
if (workerScript.checkingRam) {
return updateStaticRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getSkillLevel() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillLevel() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getSkillUpgradeCost : function(skillName="") {
if (workerScript.checkingRam) {
return updateStaticRam("getSkillUpgradeCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getSkillUpgradeCost", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getSkillUpgradeCostNetscriptFn(skillName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getSkillUpgradeCost() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillUpgradeCost() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
upgradeSkill : function(skillName) {
if (workerScript.checkingRam) {
return updateStaticRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.upgradeSkillNetscriptFn(skillName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.upgradeSkill() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "upgradeSkill() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getTeamSize : function(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getTeamSize() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
setTeamSize : function(type="", name="", size) {
if (workerScript.checkingRam) {
return updateStaticRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.setTeamSize() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "setTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getCityEstimatedPopulation : function(cityName) {
if (workerScript.checkingRam) {
return updateStaticRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getCityEstimatedPopulationNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityEstimatedPopulation() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityEstimatedPopulation() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getCityEstimatedCommunities : function(cityName) {
if (workerScript.checkingRam) {
return updateStaticRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getCityEstimatedCommunitiesNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityEstimatedCommunities() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityEstimatedCommunities() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getCityChaos : function(cityName) {
if (workerScript.checkingRam) {
return updateStaticRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.getCityChaosNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityChaos() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityChaos() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getCity : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getCity", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCity", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.city;
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCity() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
switchCity : function(cityName) {
if (workerScript.checkingRam) {
return updateStaticRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.switchCityNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.switchCity() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "switchCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getStamina : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return [_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.stamina, _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.maxStamina];
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getStamina() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
joinBladeburnerFaction : function() {
if (workerScript.checkingRam) {
return updateStaticRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "joinBladeburnerFaction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
joinBladeburnerDivision : function() {
if (workerScript.checkingRam) {
return updateStaticRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if ((_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"]) {
return true; //Already member
} else if (_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].defense >= 100 &&
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].agility >= 100) {
_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner = new _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"]({new:true});
workerScript.log("You have been accepted into the Bladeburner division");
return true;
} else {
workerScript.log("You do not meet the requirements for joining the Bladeburner division");
return false;
}
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "joinBladeburnerDivision() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
},
getBonusTime : function() {
if (workerScript.checkingRam) {return 0;}
if ((_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) {
return Math.round(_Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].bladeburner.storedCycles / 5);
}
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_33__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getBonusTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +
"at the Bladeburner division or because you do not have Source-File 7");
}
}, // End Bladeburner
codingcontract : {
attempt : function(answer, fn, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("attempt", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost);
}
updateDynamicRam("attempt", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost);
const contract = getCodingContract(fn, ip);
if (contract == null) {
workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`);
return false;
}
answer = String(answer);
const serv = safeGetServer(ip, "codingcontract.attempt()");
if (contract.isSolution(answer)) {
const reward = _Player__WEBPACK_IMPORTED_MODULE_21__[/* Player */ "a"].gainCodingContractReward(contract.reward, contract.getDifficulty());
workerScript.log(`Successfully completed Coding Contract ${fn}. Reward: ${reward}`);
serv.removeContract(fn);
return true;
} else {
++contract.tries;
if (contract.tries >= contract.getMaxNumTries()) {
workerScript.log(`Coding Contract ${fn} failed. Contract is now self-destructing`);
serv.removeContract(fn);
} else {
workerScript.log(`Coding Contract ${fn} failed. ${contract.getMaxNumTries() - contract.tries} attempts remaining`);
}
return false;
}
},
getContractType : function(fn, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("getContractType", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
}
updateDynamicRam("getContractType", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
let contract = getCodingContract(fn, ip);
if (contract == null) {
workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`);
return null;
}
return contract.getType();
},
getData : function(fn, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("getData", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
}
updateDynamicRam("getData", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
let contract = getCodingContract(fn, ip);
if (contract == null) {
workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`);
return null;
}
let data = contract.getData();
if (data.constructor === Array) {
// Pass a copy
return data.slice();
} else {
return data;
}
},
getDescription : function(fn, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("getDescription", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
}
updateDynamicRam("getDescription", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
var contract = getCodingContract(fn, ip);
if (contract == null) {
workerScript.log(`ERROR: codingcontract.getDescription() failed because it could find the specified contract ${fn} on server ${ip}`);
return "";
}
return contract.getDescription();
},
getNumTriesRemaining : function(fn, ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("getNumTriesRemaining", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
}
updateDynamicRam("getNumTriesRemaining", _Constants__WEBPACK_IMPORTED_MODULE_9__["CONSTANTS"].ScriptCodingContractBaseRamCost / 2);
var contract = getCodingContract(fn, ip);
if (contract == null) {
workerScript.log(`ERROR: codingcontract.getNumTriesRemaining() failed because it could find the specified contract ${fn} on server ${ip}`);
return -1;
}
return contract.getMaxNumTries() - contract.tries;
},
}
} //End return
} //End NetscriptFunction()
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 42 */
/*!*****************************************!*\
!*** ./utils/helpers/exceptionAlert.js ***!
\*****************************************/
/*! exports provided: exceptionAlert */
/*! exports used: exceptionAlert */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return exceptionAlert; });
/* harmony import */ var _DialogBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../DialogBox */ 9);
function exceptionAlert(e) {
Object(_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("Caught an exception: " + e + "<br><br>" +
"Filename: " + (e.fileName || "UNKNOWN FILE NAME") + "<br><br>" +
"Line Number: " + (e.lineNumber || "UNKNOWN LINE NUMBER") + "<br><br>" +
"This is a bug, please report to game developer with this " +
"message as well as details about how to reproduce the bug.<br><br>" +
"If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " +
"safe doesn't get corrupted");
}
/***/ }),
/* 43 */
/*!**********************!*\
!*** ./src/Alias.js ***!
\**********************/
/*! exports provided: Aliases, GlobalAliases, printAliases, parseAliasDeclaration, removeAlias, substituteAliases, loadAliases, loadGlobalAliases */
/*! exports used: Aliases, GlobalAliases, loadAliases, loadGlobalAliases, parseAliasDeclaration, printAliases, removeAlias, substituteAliases */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Aliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return GlobalAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return printAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return parseAliasDeclaration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return removeAlias; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return substituteAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadGlobalAliases; });
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__);
let Aliases = {};
let GlobalAliases = {};
function loadAliases(saveString) {
if (saveString === "") {
Aliases = {};
} else {
Aliases = JSON.parse(saveString);
}
}
function loadGlobalAliases(saveString) {
if (saveString === "") {
GlobalAliases = {};
} else {
GlobalAliases = JSON.parse(saveString);
}
}
//Print all aliases to terminal
function printAliases() {
for (var name in Aliases) {
if (Aliases.hasOwnProperty(name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]);
}
}
for (var name in GlobalAliases) {
if (GlobalAliases.hasOwnProperty(name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__["post"])("global alias " + name + "=" + GlobalAliases[name]);
}
}
}
//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;
}
function addAlias(name, value) {
if (name in GlobalAliases){
delete GlobalAliases[name];
}
Aliases[name] = value;
}
function addGlobalAlias(name, value) {
if (name in Aliases){
delete Aliases[name];
}
GlobalAliases[name] = value;
}
function getAlias(name) {
if (Aliases.hasOwnProperty(name)) {
return Aliases[name];
}
return null;
}
function getGlobalAlias(name) {
if (GlobalAliases.hasOwnProperty(name)) {
return GlobalAliases[name];
}
return null;
}
function removeAlias(name) {
if (Aliases.hasOwnProperty(name)) {
delete Aliases[name];
return true;
}
if (GlobalAliases.hasOwnProperty(name)) {
delete GlobalAliases[name];
return true;
}
return false;
}
//Returns the original string with any aliases substituted in
//Aliases only applied to "whole words", one level deep
function substituteAliases(origCommand) {
var commandArray = origCommand.split(" ");
if (commandArray.length>0){
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(" ");
}
/***/ }),
/* 44 */
/*!***************************************!*\
!*** ./src/Faction/FactionHelpers.js ***!
\***************************************/
/*! exports provided: getNextNeurofluxLevel, inviteToFaction, joinFaction, displayFactionContent, processPassiveFactionRepGain, purchaseAugmentation */
/*! exports used: displayFactionContent, inviteToFaction, joinFaction, processPassiveFactionRepGain, purchaseAugmentation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export getNextNeurofluxLevel */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return inviteToFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return joinFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayFactionContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return processPassiveFactionRepGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return purchaseAugmentation; });
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Augmentations */ 21);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Constants */ 1);
/* 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 */ 8);
/* harmony import */ var _FactionInfo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FactionInfo */ 104);
/* harmony import */ var _FactionInfo__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_FactionInfo__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Location */ 86);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Missions */ 53);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Player */ 0);
/* harmony import */ var _SettingEnums__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../SettingEnums */ 69);
/* harmony import */ var _SettingEnums__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_SettingEnums__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Settings__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 _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../utils/DialogBox */ 9);
/* harmony import */ var _utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../utils/FactionInvitationBox */ 123);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 2);
/* 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_JSONReviver__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../utils/JSONReviver */ 13);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../utils/YesNoBox */ 17);
function inviteToFaction(faction) {
if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].SuppressFactionInvites) {
faction.alreadyInvited = true;
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].factionInvitations.push(faction.name);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_10__["Page"].Factions)) {
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionsContent();
}
} else {
Object(_utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_13__[/* factionInvitationBoxCreate */ "a"])(faction);
}
}
function joinFaction(faction) {
faction.isMember = true;
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].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[enemy] instanceof Faction) {
Factions[enemy].isBanned = true;
}
}
}
//Displays the HTML content for a specific faction
function displayFactionContent(factionName) {
var faction = Factions[factionName];
if (faction == null) {
throw new Error("Invalid factionName passed into displayFactionContent: " + factionName);
}
var factionInfo = faction.getInfo();
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent);
var elements = [];
//Header and faction info
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h1", {
innerText:factionName
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
innerHTML:"<i>" + factionInfo.infoText + "</i>"
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"---------------",
}));
//Faction reputation and favor
var favorGain = faction.getFavorGain();
if (favorGain.length != 2) {favorGain = 0;}
favorGain = favorGain[0];
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText: "Reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(faction.playerReputation, 4),
tooltip:"You will earn " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(favorGain, 0) +
" faction favor upon resetting after installing an Augmentation"
}))
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"---------------",
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Faction Favor: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(faction.favor, 0),
tooltip:"Faction favor increases the rate at which " +
"you earn reputation for this faction by 1% per favor. Faction favor " +
"is gained whenever you reset after installing an Augmentation. The amount of " +
"favor you gain depends on how much reputation you have with the faction"
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"---------------",
}));
//Faction Work Description Text
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
id:"faction-work-description-text",
innerText:"Perform work/carry out assignments for your faction to help further its cause! By doing so " +
"you will earn reputation for your faction. You will also gain reputation passively over time, " +
"although at a very slow rate. Earning reputation will allow you to purchase Augmentations " +
"through this faction, which are powerful upgrades that enhance your abilities. Note that you cannot " +
"use your terminal or create scripts when you are performing a task!"
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
//Hacking Mission Option
var hackMissionDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-hack-mission-div", class:"faction-work-div",
});
var hackMissionDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
hackMissionDiv.appendChild(hackMissionDivWrapper);
hackMissionDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Hacking Mission",
clickListener:()=>{
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadMissionContent();
var mission = new _Missions__WEBPACK_IMPORTED_MODULE_6__[/* HackingMission */ "a"](faction.playerReputation, faction);
Object(_Missions__WEBPACK_IMPORTED_MODULE_6__[/* setInMission */ "d"])(true, mission); //Sets inMission flag to true
mission.init();
return false;
}
}));
hackMissionDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Attempt a hacking mission for your faction. " +
"A mission is a mini game that, if won, earns you " +
"significant reputation with this faction. (Recommended hacking level: 200+)"
}));
elements.push(hackMissionDiv);
//Hacking Contracts Option
var hackDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-hack-div", class:"faction-work-div",
});
var hackDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
hackDiv.appendChild(hackDivWrapper);
hackDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Hacking Contracts",
clickListener:()=>{
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionHackWork(faction);
return false;
}
}));
hackDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Complete hacking contracts for your faction. " +
"Your effectiveness, which determines how much " +
"reputation you gain for this faction, is based on your hacking skill. " +
"You will gain hacking exp."
}));
elements.push(hackDiv);
//Field Work Option
var fieldWorkDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-fieldwork-div", class:"faction-work-div"
});
var fieldWorkDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
fieldWorkDiv.appendChild(fieldWorkDivWrapper);
fieldWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Field Work",
clickListener:()=>{
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionFieldWork(faction);
return false;
}
}));
fieldWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Carry out field missions for your faction. " +
"Your effectiveness, which determines how much " +
"reputation you gain for this faction, is based on all of your stats. " +
"You will gain exp for all stats."
}));
elements.push(fieldWorkDiv);
//Security Work Option
var securityWorkDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-securitywork-div", class:"faction-work-div"
});
var securityWorkDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
securityWorkDiv.appendChild(securityWorkDivWrapper);
securityWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Security Work",
clickListener:()=>{
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionSecurityWork(faction);
return false;
}
}));
securityWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Serve in a security detail for your faction. " +
"Your effectiveness, which determines how much " +
"reputation you gain for this faction, is based on your combat stats. " +
"You will gain exp for all combat stats."
}));
elements.push(securityWorkDiv);
//Donate for reputation
var donateDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-donate-div", class:"faction-work-div"
});
var donateDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
donateDiv.appendChild(donateDivWrapper);
var donateRepGain = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"This donation will result in 0.000 reputation gain"
});
var donateAmountInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
placeholder:"Donation amount",
inputListener:()=>{
let amt = 0;
if(donateAmountInput.value !== "") {
amt = parseFloat(donateAmountInput.value);
}
if (isNaN(amt)) {
donateRepGain.innerText = "Invalid donate amount entered!";
} else {
var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].faction_rep_mult;
donateRepGain.innerText = "This donation will result in " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(repGain, 3) + " reputation gain";
}
},
});
donateDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Donate Money",
clickListener:()=>{
var amt = parseFloat(donateAmountInput.value);
if (isNaN(amt) || amt < 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("Invalid amount entered!");
} else if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].money.lt(amt)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You cannot afford to donate this much money!");
} else {
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].loseMoney(amt);
var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].faction_rep_mult;
faction.playerReputation += repGain;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You just donated " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__[/* numeralWrapper */ "a"].format(amt, "$0.000a") + " to " +
faction.name + " to gain " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(repGain, 3) + " reputation");
displayFactionContent(factionName);
}
}
}));
donateDivWrapper.appendChild(donateAmountInput);
donateDivWrapper.appendChild(donateRepGain);
elements.push(donateDiv);
//Purchase Augmentations
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("pre", {
innerHTML: "<br>As your reputation with this faction rises, you will " +
"unlock Augmentations, which you can purchase to enhance " +
"your abilities.<br><br>"
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Purchase Augmentations",
clickListener:()=>{
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].hideAllContent();
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.style.display = "block";
displayFactionAugmentations(factionName);
return false;
}
}));
//Gang (BitNode-2)
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].bitNodeN == 2 && (factionName == "Slum Snakes" || factionName == "Tetrads" ||
factionName == "The Syndicate" || factionName == "The Dark Army" || factionName == "Speakers for the Dead" ||
factionName == "NiteSec" || factionName == "The Black Hand")) {
//Set everything else to invisible
hackMissionDiv.style.display = "none";
hackDiv.style.display = "none";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
donateDiv.style.display = "none";
//Create the 'Manage Gang' button
var gangDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {
id:"faction-gang-div", class:"faction-work-div", display:"inline"
});
var gangDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {class:"faction-work-div-wrapper"});
gangDiv.appendChild(gangDivWrapper);
gangDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", innerText:"Manage Gang",
clickListener: () => {
if (!_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].inGang()) {
// Determine whether this is a hacking gang
let hacking = false;
if (factionName === "NiteSec" || factionName === "The Black Hand") { hacking = true; }
// Configure Yes/No buttons for the pop-up
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Create Gang";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", () => {
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startGang(factionName, hacking);
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent();
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxClose */ "a"])();
});
noBtn.addEventListener("click", () => {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxClose */ "a"])();
});
// Pop-up text
let gangTypeText = "";
if (hacking) {
gangTypeText = "This is a HACKING gang. Members in this gang will have different tasks than COMBAT gangs. " +
"Compared to combat gangs, progression with hacking gangs is more straightforward as territory warfare " +
"is not as important.<br><br>";
} else {
gangTypeText = "This is a COMBAT gang. Members in this gang will have different tasks than HACKING gangs. " +
"Compared to hacking gangs, progression with combat gangs can be more difficult as territory management " +
"is more important. However, well-managed combat gangs can progress faster than hacking ones.<br><br>";
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxCreate */ "b"])(`Would you like to create a new Gang with ${factionName}?<br><br>` +
"Note that this will prevent you from creating a Gang with any other Faction until " +
"this BitNode is destroyed.<br><br>" +
gangTypeText +
"Other than hacking vs combat, there are NO differences between the Factions you can " +
"create a Gang with, and each of these Factions have all Augmentations available.");
} else {
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent();
}
}
}));
gangDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
innerText:"Create and manage a gang for this Faction. " +
"Gangs will earn you money and faction reputation."
}));
//Manage Gang button goes before Faction work stuff
elements.splice(7, 1, gangDiv);
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].inGang() && _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].gang.facName != factionName) {
//If the player has a gang but its not for this faction
gangDiv.style.display = "none";
}
//Display all elements
for (var i = 0; i < elements.length; ++i) {
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]);
}
return;
}
if (!faction.isMember) {
throw new Error("Not a member of this faction, cannot display faction information");
}
donateDiv.style.display = faction.favor >= Math.floor(_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].BaseFavorToDonate * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].RepToDonateToFaction) ? "inline" : "none";
hackMissionDiv.style.display = factionInfo.offerHackingMission ? "inline": "none";
hackDiv.style.display = factionInfo.offerHackingWork ? "inline" : "none";
fieldWorkDiv.style.display = factionInfo.offerFieldWork ? "inline" : "none";
securityWorkDiv.style.display = factionInfo.offerSecurityWork ? "inline" : "none";
//Display all elements
for (var i = 0; i < elements.length; ++i) {
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]);
}
}
function displayFactionAugmentations(factionName) {
var faction = Factions[factionName];
if (faction == null) {
throw new Error("Could not find faction " + factionName + " in displayFactionAugmentations");
}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent);
var elements = [];
//Back button
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
innerText:"Back", class:"a-link-button",
clickListener:()=>{
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionContent();
displayFactionContent(factionName);
return false;
}
}));
//Header text
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("h1", {innerText:"Faction Augmentations"}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
id:"faction-augmentations-page-desc",
innerHTML:"Lists all Augmentations that are available to purchase from " + factionName + "<br><br>" +
"Augmentations are powerful upgrades that will enhance your abilities."
}));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("br"));
//Augmentations List
var augmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("ul");
//Sort buttons
const sortByCostBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
innerText:"Sort by Cost", class:"a-link-button",
clickListener:()=>{
_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].PurchaseAugmentationsOrder = _SettingEnums__WEBPACK_IMPORTED_MODULE_8__["PurchaseAugmentationsOrderSetting"].Cost;
var augs = faction.augmentations.slice();
augs.sort((augName1, augName2)=>{
var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName2];
if (aug1 == null || aug2 == null) {
throw new Error("Invalid Augmentation Names");
}
return aug1.baseCost - aug2.baseCost;
});
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(augmentationsList);
createFactionAugmentationDisplayElements(augmentationsList, augs, faction);
}
});
const sortByRepBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
innerText:"Sort by Reputation", class:"a-link-button",
clickListener:()=>{
_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].PurchaseAugmentationsOrder = _SettingEnums__WEBPACK_IMPORTED_MODULE_8__["PurchaseAugmentationsOrderSetting"].Reputation;
var augs = faction.augmentations.slice();
augs.sort((augName1, augName2)=>{
var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName2];
if (aug1 == null || aug2 == null) {
throw new Error("Invalid Augmentation Names");
}
return aug1.baseRepRequirement - aug2.baseRepRequirement;
});
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(augmentationsList);
createFactionAugmentationDisplayElements(augmentationsList, augs, faction);
}
});
const defaultSortBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
innerText:"Sort by Default Order", class:"a-link-button",
clickListener:()=>{
_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].PurchaseAugmentationsOrder = _SettingEnums__WEBPACK_IMPORTED_MODULE_8__["PurchaseAugmentationsOrderSetting"].Default;
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_14__["removeChildrenFromElement"])(augmentationsList);
createFactionAugmentationDisplayElements(augmentationsList, faction.augmentations, faction);
}
});
elements.push(sortByCostBtn);
elements.push(sortByRepBtn);
elements.push(defaultSortBtn);
switch(_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].PurchaseAugmentationsOrder) {
case _SettingEnums__WEBPACK_IMPORTED_MODULE_8__["PurchaseAugmentationsOrderSetting"].Cost:
sortByCostBtn.click();
break;
case _SettingEnums__WEBPACK_IMPORTED_MODULE_8__["PurchaseAugmentationsOrderSetting"].Reputation:
sortByRepBtn.click();
break;
default:
defaultSortBtn.click();
break;
}
elements.push(augmentationsList);
for (var i = 0; i < elements.length; ++i) {
_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.appendChild(elements[i]);
}
}
//Takes in an array of Augmentation Names, constructs DOM elements
//to list them on the faction page, and appends them to the given
//DOM element
// @augmentationsList DOM List to append Aug DOM elements to
// @augs Array of Aug names
// @faction Faction for which to display Augmentations
function createFactionAugmentationDisplayElements(augmentationsList, augs, faction) {
const factionInfo = faction.getInfo();
for (var i = 0; i < augs.length; ++i) {
(function () {
var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augs[i]];
if (aug == null) {
throw new Error("Invalid Augmentation when trying to create Augmentation display Elements");
}
var owned = false;
for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations[j].name == aug.name) {
owned = true;
break;
}
}
for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[j].name == aug.name) {
owned = true;
break;
}
}
var item = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("li");
var span = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("span", {display:"inline-block"});
var aDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("div", {tooltip:aug.info});
var aElem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
innerText:aug.name, display:"inline",
clickListener:()=>{
if (!_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].SuppressBuyAugmentationConfirmation) {
purchaseAugmentationBoxCreate(aug, faction);
} else {
purchaseAugmentation(aug, faction);
}
return false;
}
});
if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
aElem.innerText += " - Level " + (getNextNeurofluxLevel());
}
var pElem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
display:"inline",
})
var req = aug.baseRepRequirement * factionInfo.augmentationRepRequirementMult;
var hasPrereqs = hasAugmentationPrereqs(aug);
if (!hasPrereqs) {
aElem.setAttribute("class", "a-link-button-inactive");
pElem.innerHTML = "LOCKED (Requires " + aug.prereqs.join(",") + " as prerequisite(s))";
pElem.style.color = "red";
} else if (aug.name != _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor && (aug.owned || owned)) {
aElem.setAttribute("class", "a-link-button-inactive");
pElem.innerHTML = "ALREADY OWNED";
} else if (faction.playerReputation >= req) {
aElem.setAttribute("class", "a-link-button");
pElem.innerHTML = "UNLOCKED - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__[/* numeralWrapper */ "a"].format(aug.baseCost * factionInfo.augmentationPriceMult, "$0.000a");
} else {
aElem.setAttribute("class", "a-link-button-inactive");
pElem.innerHTML = "LOCKED (Requires " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(req, 1) + " faction reputation) - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_11__[/* numeralWrapper */ "a"].format(aug.baseCost * factionInfo.augmentationPriceMult, "$0.000a");
pElem.style.color = "red";
}
aDiv.appendChild(aElem);
span.appendChild(aDiv);
span.appendChild(pElem);
item.appendChild(span);
augmentationsList.appendChild(item);
}()); //Immediate invocation closure
}
}
function purchaseAugmentationBoxCreate(aug, fac) {
const factionInfo = fac.getInfo();
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Purchase";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
purchaseAugmentation(aug, fac);
});
noBtn.addEventListener("click", function() {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxClose */ "a"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxCreate */ "b"])("<h2>" + aug.name + "</h2><br>" +
aug.info + "<br><br>" +
"<br>Would you like to purchase the " + aug.name + " Augmentation for $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(aug.baseCost * factionInfo.augmentationPriceMult, 2) + "?");
}
//Returns a boolean indicating whether the player has the prerequisites for the
//specified Augmentation
function hasAugmentationPrereqs(aug) {
var hasPrereqs = true;
if (aug.prereqs && aug.prereqs.length > 0) {
for (var i = 0; i < aug.prereqs.length; ++i) {
var prereqAug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][aug.prereqs[i]];
if (prereqAug == null) {
console.log("ERROR: Invalid prereq Augmentation: " + aug.prereqs[i]);
continue;
}
if (prereqAug.owned === false) {
hasPrereqs = false;
//Check if the aug is purchased
for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].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_12__["dialogBoxCreate"])(txt);}
} else if (aug.baseCost !== 0 && _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].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_12__["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_12__["dialogBoxCreate"])(txt);
} else if (aug.baseCost === 0 || _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].firstAugPurchased === false) {
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].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 _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* PlayerOwnedAugmentation */ "d"](aug.name);
if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
queuedAugmentation.level = getNextNeurofluxLevel();
}
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.push(queuedAugmentation);
_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].loseMoney((aug.baseCost * factionInfo.augmentationPriceMult));
//If you just purchased Neuroflux Governor, recalculate the cost
if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
var nextLevel = getNextNeurofluxLevel();
--nextLevel;
var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
aug.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationRepCost;
aug.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationMoneyCost;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length-1; ++i) {
aug.baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier;
}
}
for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"]) {
if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"].hasOwnProperty(name)) {
_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][name].baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier;
}
}
if (sing) {
return "You purchased " + aug.name;
} else {
if(!_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].SuppressBuyAugmentationConfirmation){
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["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.");
}
}
displayFactionAugmentations(fac.name);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["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_18__[/* yesNoBoxClose */ "a"])();
}
function getNextNeurofluxLevel() {
// Get current Neuroflux level based on Player's augmentations
let currLevel = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[i].name === _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[i].level;
}
}
// Account for purchased but uninstalled Augmentations
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations[i].name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) {
++currLevel;
}
}
return currLevel + 1;
}
function processPassiveFactionRepGain(numCycles) {
var numTimesGain = (numCycles / 600) * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].faction_rep_mult;
for (var name in Factions) {
if (Factions.hasOwnProperty(name)) {
var faction = 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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionPassiveRepGain);}
}
}
}
/***/ }),
/* 45 */
/*!**********************!*\
!*** ./src/Fconf.js ***!
\**********************/
/*! exports provided: FconfSettings, createFconf, parseFconfSettings, loadFconf */
/*! exports used: FconfSettings, createFconf, loadFconf, parseFconfSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FconfSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createFconf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return parseFconfSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadFconf; });
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn */ 46);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
var 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,
}
var FconfComments = {
ENABLE_BASH_HOTKEYS: "Improved Bash emulation mode. Setting this to 1 enables several\n" +
"new Terminal shortcuts and features that more closely resemble\n" +
"a real Bash-style shell. Note that when this mode is enabled,\n" +
"the default browser shortcuts are overriden by the new Bash\n" +
"shortcuts.\n\n" +
"To see a full list of the Terminal shortcuts that this enables, see:\n" +
"http://bitburner.readthedocs.io/en/latest/shortcuts.html",
ENABLE_TIMESTAMPS: "Terminal commands and log entries will be timestamped. The timestamp\n" +
"will have the format: M/D h:m",
MAIN_MENU_STYLE: "Customize the main navigation menu on the left-hand side. Current options:\n\n" +
"default, classic, compact",
THEME_BACKGROUND_COLOR: "Sets the background color for not only the Terminal, but also for\n" +
"most of the game's UI.\n\n" +
"The color must be specified as a pound sign (#) followed by a \n" +
"3-digit or 6-digit hex color code (e.g. #123456). Default color: #000000",
THEME_FONT_COLOR: "Sets the font color for not only the Terminal, but also for\n" +
"most of the game's UI.\n\n" +
"The color must be specified as a pound sign (#) followed by a \n" +
"3-digit or 6-digit hex color code (e.g. #123456). Default color: #66ff33",
THEME_HIGHLIGHT_COLOR: "Sets the highlight color for not only the Terminal, but also for \n" +
"most of the game's UI.\n\n" +
"The color must be specified as a pound sign (#) followed by a \n" +
"3-digit or 6-digit hex color code (e.g. #123456). Default color: #ffffff",
THEME_PROMPT_COLOR: "Sets the prompt color in the Terminal\n\n" +
"The color must be specified as a pound sign (#) followed by a \n" +
"3-digit or 6-digit hex color code (e.g. #123456). Default color: #f92672",
WRAP_INPUT: "Wrap Terminal Input. If this is enabled, then when a Terminal command is\n" +
"too long and overflows, then it will wrap to the next line instead of\n" +
"side-scrolling\n\n" +
"Note that after you enable/disable this, you'll have to run a command\n" +
"before its effect takes place.",
}
const MainMenuStyleOptions = ["default", "classic", "compact"];
//Parse Fconf settings from the config text
//Throws an exception if parsing fails
function parseFconfSettings(config) {
var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"])(config, {sourceType:"module"});
var queue = [];
queue.push(ast);
while (queue.length != 0) {
var exp = queue.shift();
switch (exp.type) {
case "BlockStatement":
case "Program":
for (var i = 0; i < exp.body.length; ++i) {
if (exp.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
queue.push(exp.body[i]);
}
}
break;
case "AssignmentExpression":
var setting, value;
if (exp.left != null && exp.left.name != null) {
setting = exp.left.name;
} else {
break;
}
if (exp.right != null && exp.right.raw != null) {
value = exp.right.raw;
} else {
break;
}
parseFconfSetting(setting, value);
break;
default:
break;
}
for (var prop in exp) {
if (exp.hasOwnProperty(prop)) {
if (exp[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
queue.push(exp[prop]);
}
}
}
}
setTheme();
setMainMenuStyle();
}
function parseFconfSetting(setting, value) {
setting = String(setting);
value = String(value);
if (setting == null || value == null || FconfSettings[setting] == null) {
console.log("WARNING: Invalid .fconf setting: " + setting);
return;
}
function sanitizeString(value) {
value = value.toLowerCase();
if (value.startsWith('"')) { value = value.slice(1); }
if (value.endsWith('"')) { value = value.slice(0, -1); }
return value;
}
switch(setting) {
case "ENABLE_BASH_HOTKEYS":
case "ENABLE_TIMESTAMPS":
case "WRAP_INPUT":
// Need to convert entered value to boolean/strings accordingly
var value = value.toLowerCase();
if (value === "1" || value === "true" || value === "y") {
value = true;
} else {
value = false;
}
FconfSettings[setting] = value;
break;
case "MAIN_MENU_STYLE":
var value = sanitizeString(value);
if (MainMenuStyleOptions.includes(value)) {
FconfSettings[setting] = value;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(`Invalid option specified for ${setting}. Options: ${MainMenuStyleOptions.toString()}`);
}
break;
case "THEME_BACKGROUND_COLOR":
case "THEME_FONT_COLOR":
case "THEME_HIGHLIGHT_COLOR":
case "THEME_PROMPT_COLOR":
var value = sanitizeString(value);
if ((/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value))) {
FconfSettings[setting] = value;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(`Invalid color specified for ${setting}. Must be a hex color code preceded by a pound (#)`);
}
break;
default:
break;
}
}
//Create the .fconf file text from the settings
function createFconf() {
var res = "";
for (var setting in FconfSettings) {
if (FconfSettings.hasOwnProperty(setting)) {
//Setting comments (description)
var comment = FconfComments[setting];
if (comment == null) {continue;}
var comment = comment.split("\n");
for (var i = 0; i < comment.length; ++i) {
res += ("//" + comment[i] + "\n");
}
var value = 0;
if (FconfSettings[setting] === true) {
value = "1";
} else if (FconfSettings[setting] === false) {
value = "0";
} else {
value = '"' + String(FconfSettings[setting]) + '"';
}
res += (`${setting} = ${value}\n\n`);
}
}
return res;
}
function loadFconf(saveString) {
let tempFconfSettings = JSON.parse(saveString);
for (var setting in tempFconfSettings) {
if (tempFconfSettings.hasOwnProperty(setting)) {
FconfSettings[setting] = tempFconfSettings[setting];
}
}
// Initialize themes/styles after loading
setTheme();
setMainMenuStyle();
}
function setTheme() {
if (FconfSettings.THEME_HIGHLIGHT_COLOR == null ||
FconfSettings.THEME_FONT_COLOR == null ||
FconfSettings.THEME_BACKGROUND_COLOR == null ||
FconfSettings.THEME_PROMPT_COLOR == null) {
console.log("ERROR: Cannot find Theme Settings");
return;
}
if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_HIGHLIGHT_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_FONT_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_BACKGROUND_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_PROMPT_COLOR)) {
document.body.style.setProperty('--my-highlight-color', FconfSettings.THEME_HIGHLIGHT_COLOR);
document.body.style.setProperty('--my-font-color', FconfSettings.THEME_FONT_COLOR);
document.body.style.setProperty('--my-background-color', FconfSettings.THEME_BACKGROUND_COLOR);
document.body.style.setProperty('--my-prompt-color', FconfSettings.THEME_PROMPT_COLOR);
}
}
function setMainMenuStyle() {
const mainMenu = document.getElementById("mainmenu");
const hackingMenuHdr = document.getElementById("hacking-menu-header");
const characterMenuHdr = document.getElementById("character-menu-header");
const worldMenuHdr = document.getElementById("world-menu-header");
const helpMenuHdr = document.getElementById("help-menu-header");
function removeAllAccordionHeaderClasses() {
hackingMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic");
characterMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic");
worldMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic");
helpMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic");
}
function addClassToAllAccordionHeaders(clsName) {
hackingMenuHdr.classList.add(clsName);
characterMenuHdr.classList.add(clsName);
worldMenuHdr.classList.add(clsName);
helpMenuHdr.classList.add(clsName);
}
if (FconfSettings["MAIN_MENU_STYLE"] === "default") {
removeAllAccordionHeaderClasses();
mainMenu.classList.remove("classic");
mainMenu.classList.remove("compact");
addClassToAllAccordionHeaders("mainmenu-accordion-header");
} else if (FconfSettings["MAIN_MENU_STYLE"] === "classic") {
removeAllAccordionHeaderClasses();
mainMenu.classList.remove("compact");
mainMenu.classList.add("classic");
addClassToAllAccordionHeaders("mainmenu-accordion-header-classic");
} else if (FconfSettings["MAIN_MENU_STYLE"] === "compact") {
removeAllAccordionHeaderClasses();
mainMenu.classList.remove("classic");
mainMenu.classList.add("compact");
addClassToAllAccordionHeaders("mainmenu-accordion-header-compact");
} else {
return;
}
// Click each header twice to reset lol
hackingMenuHdr.click(); hackingMenuHdr.click();
characterMenuHdr.click(); characterMenuHdr.click();
worldMenuHdr.click(); worldMenuHdr.click();
helpMenuHdr.click(); helpMenuHdr.click();
}
/***/ }),
/* 46 */
/*!************************!*\
!*** ./utils/acorn.js ***!
\************************/
/*! no static exports found */
/*! exports used: Node, parse */
/***/ (function(module, exports, __webpack_require__) {
/*
acorn.js
https://github.com/ternjs/acorn
Copyright (C) 2012-2017 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global, factory) {
true ? factory(exports) :
undefined;
}(this, (function (exports) { 'use strict';
// Reserved word lists for various dialects of the language
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
}
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"
var keywords = {
5: ecma5AndLessKeywords,
6: ecma5AndLessKeywords + " const class extends export import super"
}
// ## Character categories
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
// Generated by `bin/generate-identifier-regex.js`.
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range. They were
// generated by bin/generate-identifier-regex.js
// eslint-disable-next-line comma-spacing
var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541]
// eslint-disable-next-line comma-spacing
var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
var pos = 0x10000
for (var i = 0; i < set.length; i += 2) {
pos += set[i]
if (pos > code) return false
pos += set[i + 1]
if (pos >= code) return true
}
}
// Test whether a given character code starts an identifier.
function isIdentifierStart(code, astral) {
if (code < 65) return code === 36
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36
if (code < 58) return true
if (code < 65) return false
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
var TokenType = function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label
this.keyword = conf.keyword
this.beforeExpr = !!conf.beforeExpr
this.startsExpr = !!conf.startsExpr
this.isLoop = !!conf.isLoop
this.isAssign = !!conf.isAssign
this.prefix = !!conf.prefix
this.postfix = !!conf.postfix
this.binop = conf.binop || null
this.updateContext = null
};
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true};
var startsExpr = {startsExpr: true};
// Map keyword names to token types.
var keywordTypes = {}
// Succinct definitions of keyword token types
function kw(name, options) {
if ( options === void 0 ) options = {};
options.keyword = name
return keywordTypes[name] = new TokenType(name, options)
}
var tt = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=", 6),
relational: binop("</>", 7),
bitShift: binop("<</>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", {beforeExpr: true}),
// Keyword token types.
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {isLoop: true, beforeExpr: true}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", {isLoop: true}),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", {isLoop: true}),
_with: kw("with"),
_new: kw("new", {beforeExpr: true, startsExpr: true}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class"),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import"),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {beforeExpr: true, binop: 7}),
_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
}
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/
var lineBreakG = new RegExp(lineBreak.source, "g")
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
// Checks if an object has a property.
function has(obj, propName) {
return hasOwnProperty.call(obj, propName)
}
var isArray = Array.isArray || (function (obj) { return (
toString.call(obj) === "[object Array]"
); })
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = function Position(line, col) {
this.line = line
this.column = col
};
Position.prototype.offset = function offset (n) {
return new Position(this.line, this.column + n)
};
var SourceLocation = function SourceLocation(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
};
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
var match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
var defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
// for strict mode, the set of reserved words, and support for
// new syntax features. The default is 7.
ecmaVersion: 7,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {}
}
// Interpret and default an options object
function getOptions(opts) {
var options = {}
for (var opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (options.ecmaVersion >= 2015)
options.ecmaVersion -= 2009
if (options.allowReserved == null)
options.allowReserved = options.ecmaVersion < 5
if (isArray(options.onToken)) {
var tokens = options.onToken
options.onToken = function (token) { return tokens.push(token); }
}
if (isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start: start,
end: end
}
if (options.locations)
comment.loc = new SourceLocation(this, startLoc, endLoc)
if (options.ranges)
comment.range = [start, end]
array.push(comment)
}
}
// Registered plugins
var plugins = {}
function keywordRegexp(words) {
return new RegExp("^(" + words.replace(/ /g, "|") + ")$")
}
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options)
this.sourceFile = options.sourceFile
this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])
var reserved = ""
if (!options.allowReserved) {
for (var v = options.ecmaVersion;; v--)
if (reserved = reservedWords[v]) break
if (options.sourceType == "module") reserved += " await"
}
this.reservedWords = keywordRegexp(reserved)
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict
this.reservedWordsStrict = keywordRegexp(reservedStrict)
this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind)
this.input = String(input)
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false
// Load plugins
this.loadPlugins(options.plugins)
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
} else {
this.pos = this.lineStart = 0
this.curLine = 1
}
// Properties of the current token:
// Its type
this.type = tt.eof
// For tokens that include more information than their type, the value
this.value = null
// Its start and end offset
this.start = this.end = this.pos
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition()
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null
this.lastTokStart = this.lastTokEnd = this.pos
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext()
this.exprAllowed = true
// Figure out if it's a module code.
this.inModule = options.sourceType === "module"
this.strict = this.inModule || this.strictDirective(this.pos)
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1
// Flags to track whether we are in a function, a generator, an async function.
this.inFunction = this.inGenerator = this.inAsync = false
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = 0
// Labels in scope.
this.labels = []
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
this.skipLineComment(2)
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = []
this.enterFunctionScope()
};
// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
Parser.prototype.extend = function extend (name, f) {
this[name] = f(this[name])
};
Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
var this$1 = this;
for (var name in pluginConfigs) {
var plugin = plugins[name]
if (!plugin) throw new Error("Plugin '" + name + "' not found")
plugin(this$1, pluginConfigs[name])
}
};
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode()
this.nextToken()
return this.parseTopLevel(node)
};
var pp = Parser.prototype
// ## Parser utilities
var literal = /^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/
pp.strictDirective = function(start) {
var this$1 = this;
for (;;) {
skipWhiteSpace.lastIndex = start
start += skipWhiteSpace.exec(this$1.input)[0].length
var match = literal.exec(this$1.input.slice(start))
if (!match) return false
if ((match[1] || match[2]) == "use strict") return true
start += match[0].length
}
}
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next()
return true
} else {
return false
}
}
// Tests whether parsed token is a contextual keyword.
pp.isContextual = function(name) {
return this.type === tt.name && this.value === name
}
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
return this.value === name && this.eat(tt.name)
}
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) this.unexpected()
}
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === tt.eof ||
this.type === tt.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
return true
}
}
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
}
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type == tokType) {
if (this.options.onTrailingComma)
this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
if (!notNext)
this.next()
return true
}
}
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp.expect = function(type) {
this.eat(type) || this.unexpected()
}
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token")
}
var DestructuringErrors = function DestructuringErrors() {
this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = -1
};
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) return
if (refDestructuringErrors.trailingComma > -1)
this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element")
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind
if (parens > -1) this.raiseRecoverable(parens, "Parenthesized pattern")
}
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1
if (!andThrow) return pos >= 0
if (pos > -1) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns")
}
pp.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
this.raise(this.yieldPos, "Yield expression cannot be a default value")
if (this.awaitPos)
this.raise(this.awaitPos, "Await expression cannot be a default value")
}
pp.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
return this.isSimpleAssignTarget(expr.expression)
return expr.type === "Identifier" || expr.type === "MemberExpression"
}
var pp$1 = Parser.prototype
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$1.parseTopLevel = function(node) {
var this$1 = this;
var exports = {}
if (!node.body) node.body = []
while (this.type !== tt.eof) {
var stmt = this$1.parseStatement(true, true, exports)
node.body.push(stmt)
}
this.next()
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType
}
return this.finishNode(node, "Program")
}
var loopLabel = {kind: "loop"};
var switchLabel = {kind: "switch"};
pp$1.isLet = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
if (nextCh === 91 || nextCh == 123) return true // '{' and '['
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1
while (isIdentifierChar(this.input.charCodeAt(pos), true)) ++pos
var ident = this.input.slice(next, pos)
if (!this.isKeyword(ident)) return true
}
return false
}
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$1.isAsyncFunction = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async")
return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$1.parseStatement = function(declaration, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind
if (this.isLet()) {
starttype = tt._var
kind = "let"
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case tt._debugger: return this.parseDebuggerStatement(node)
case tt._do: return this.parseDoStatement(node)
case tt._for: return this.parseForStatement(node)
case tt._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
return this.parseFunctionStatement(node, false)
case tt._class:
if (!declaration) this.unexpected()
return this.parseClass(node, true)
case tt._if: return this.parseIfStatement(node)
case tt._return: return this.parseReturnStatement(node)
case tt._switch: return this.parseSwitchStatement(node)
case tt._throw: return this.parseThrowStatement(node)
case tt._try: return this.parseTryStatement(node)
case tt._const: case tt._var:
kind = kind || this.value
if (!declaration && kind != "var") this.unexpected()
return this.parseVarStatement(node, kind)
case tt._while: return this.parseWhileStatement(node)
case tt._with: return this.parseWithStatement(node)
case tt.braceL: return this.parseBlock()
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
if (!this.inModule)
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction() && declaration) {
this.next()
return this.parseFunctionStatement(node, true)
}
var maybeName = this.value, expr = this.parseExpression()
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
return this.parseLabeledStatement(node, maybeName, expr)
else return this.parseExpressionStatement(node, expr)
}
}
pp$1.parseBreakContinueStatement = function(node, keyword) {
var this$1 = this;
var isBreak = keyword == "break"
this.next()
if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
else if (this.type !== tt.name) this.unexpected()
else {
node.label = this.parseIdent()
this.semicolon()
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0
for (; i < this.labels.length; ++i) {
var lab = this$1.labels[i]
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break
if (node.label && isBreak) break
}
}
if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}
pp$1.parseDebuggerStatement = function(node) {
this.next()
this.semicolon()
return this.finishNode(node, "DebuggerStatement")
}
pp$1.parseDoStatement = function(node) {
this.next()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
this.eat(tt.semi)
else
this.semicolon()
return this.finishNode(node, "DoWhileStatement")
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp$1.parseForStatement = function(node) {
this.next()
this.labels.push(loopLabel)
this.enterLexicalScope()
this.expect(tt.parenL)
if (this.type === tt.semi) return this.parseFor(node, null)
var isLet = this.isLet()
if (this.type === tt._var || this.type === tt._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value
this.next()
this.parseVar(init$1, true, kind)
this.finishNode(init$1, "VariableDeclaration")
if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
!(kind !== "var" && init$1.declarations[0].init))
return this.parseForIn(node, init$1)
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors
var init = this.parseExpression(true, refDestructuringErrors)
if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.toAssignable(init)
this.checkLVal(init)
this.checkPatternErrors(refDestructuringErrors, true)
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true)
}
return this.parseFor(node, init)
}
pp$1.parseFunctionStatement = function(node, isAsync) {
this.next()
return this.parseFunction(node, true, false, isAsync)
}
pp$1.isFunction = function() {
return this.type === tt._function || this.isAsyncFunction()
}
pp$1.parseIfStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement(!this.strict && this.isFunction())
node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null
return this.finishNode(node, "IfStatement")
}
pp$1.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
this.raise(this.start, "'return' outside of function")
this.next()
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
else { node.argument = this.parseExpression(); this.semicolon() }
return this.finishNode(node, "ReturnStatement")
}
pp$1.parseSwitchStatement = function(node) {
var this$1 = this;
this.next()
node.discriminant = this.parseParenExpression()
node.cases = []
this.expect(tt.braceL)
this.labels.push(switchLabel)
this.enterLexicalScope()
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur
for (var sawDefault = false; this.type != tt.braceR;) {
if (this$1.type === tt._case || this$1.type === tt._default) {
var isCase = this$1.type === tt._case
if (cur) this$1.finishNode(cur, "SwitchCase")
node.cases.push(cur = this$1.startNode())
cur.consequent = []
this$1.next()
if (isCase) {
cur.test = this$1.parseExpression()
} else {
if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses")
sawDefault = true
cur.test = null
}
this$1.expect(tt.colon)
} else {
if (!cur) this$1.unexpected()
cur.consequent.push(this$1.parseStatement(true))
}
}
this.exitLexicalScope()
if (cur) this.finishNode(cur, "SwitchCase")
this.next() // Closing brace
this.labels.pop()
return this.finishNode(node, "SwitchStatement")
}
pp$1.parseThrowStatement = function(node) {
this.next()
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
this.raise(this.lastTokEnd, "Illegal newline after throw")
node.argument = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ThrowStatement")
}
// Reused empty array added for node fields that are always empty.
var empty = []
pp$1.parseTryStatement = function(node) {
this.next()
node.block = this.parseBlock()
node.handler = null
if (this.type === tt._catch) {
var clause = this.startNode()
this.next()
this.expect(tt.parenL)
clause.param = this.parseBindingAtom()
this.enterLexicalScope()
this.checkLVal(clause.param, "let")
this.expect(tt.parenR)
clause.body = this.parseBlock(false)
this.exitLexicalScope()
node.handler = this.finishNode(clause, "CatchClause")
}
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
if (!node.handler && !node.finalizer)
this.raise(node.start, "Missing catch or finally clause")
return this.finishNode(node, "TryStatement")
}
pp$1.parseVarStatement = function(node, kind) {
this.next()
this.parseVar(node, false, kind)
this.semicolon()
return this.finishNode(node, "VariableDeclaration")
}
pp$1.parseWhileStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "WhileStatement")
}
pp$1.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode")
this.next()
node.object = this.parseParenExpression()
node.body = this.parseStatement(false)
return this.finishNode(node, "WithStatement")
}
pp$1.parseEmptyStatement = function(node) {
this.next()
return this.finishNode(node, "EmptyStatement")
}
pp$1.parseLabeledStatement = function(node, maybeName, expr) {
var this$1 = this;
for (var i = 0; i < this.labels.length; ++i)
if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared")
var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) {
var label = this$1.labels[i$1]
if (label.statementStart == node.start) {
label.statementStart = this$1.start
label.kind = kind
} else break
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
node.body = this.parseStatement(true)
if (node.body.type == "ClassDeclaration" ||
node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
this.raiseRecoverable(node.body.start, "Invalid labeled declaration")
this.labels.pop()
node.label = expr
return this.finishNode(node, "LabeledStatement")
}
pp$1.parseExpressionStatement = function(node, expr) {
node.expression = expr
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp$1.parseBlock = function(createNewLexicalScope) {
var this$1 = this;
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
var node = this.startNode()
node.body = []
this.expect(tt.braceL)
if (createNewLexicalScope) {
this.enterLexicalScope()
}
while (!this.eat(tt.braceR)) {
var stmt = this$1.parseStatement(true)
node.body.push(stmt)
}
if (createNewLexicalScope) {
this.exitLexicalScope()
}
return this.finishNode(node, "BlockStatement")
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp$1.parseFor = function(node, init) {
node.init = init
this.expect(tt.semi)
node.test = this.type === tt.semi ? null : this.parseExpression()
this.expect(tt.semi)
node.update = this.type === tt.parenR ? null : this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "ForStatement")
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp$1.parseForIn = function(node, init) {
var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
this.next()
node.left = init
node.right = this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, type)
}
// Parse a list of variable declarations.
pp$1.parseVar = function(node, isFor, kind) {
var this$1 = this;
node.declarations = []
node.kind = kind
for (;;) {
var decl = this$1.startNode()
this$1.parseVarId(decl, kind)
if (this$1.eat(tt.eq)) {
decl.init = this$1.parseMaybeAssign(isFor)
} else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
this$1.unexpected()
} else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) {
this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value")
} else {
decl.init = null
}
node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"))
if (!this$1.eat(tt.comma)) break
}
return node
}
pp$1.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom(kind)
this.checkLVal(decl.id, kind, false)
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node)
if (this.options.ecmaVersion >= 6 && !isAsync)
node.generator = this.eat(tt.star)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
if (isStatement) {
node.id = isStatement === "nullableID" && this.type != tt.name ? null : this.parseIdent()
if (node.id) {
this.checkLVal(node.id, "var")
}
}
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
if (!isStatement)
node.id = this.type == tt.name ? this.parseIdent() : null
this.parseFunctionParams(node)
this.parseFunctionBody(node, allowExpressionBody)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
}
pp$1.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true)
this.checkYieldAwaitInDefaultParams()
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
var this$1 = this;
this.next()
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
var classBody = this.startNode()
var hadConstructor = false
classBody.body = []
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (this$1.eat(tt.semi)) continue
var method = this$1.startNode()
var isGenerator = this$1.eat(tt.star)
var isAsync = false
var isMaybeStatic = this$1.type === tt.name && this$1.value === "static"
this$1.parsePropertyName(method)
method.static = isMaybeStatic && this$1.type !== tt.parenL
if (method.static) {
if (isGenerator) this$1.unexpected()
isGenerator = this$1.eat(tt.star)
this$1.parsePropertyName(method)
}
if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL &&
!this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(method)
}
method.kind = "method"
var isGetSet = false
if (!method.computed) {
var key = method.key;
if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true
method.kind = key.name
key = this$1.parsePropertyName(method)
}
if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class")
if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier")
if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator")
if (isAsync) this$1.raise(key.start, "Constructor can't be an async method")
method.kind = "constructor"
hadConstructor = true
}
}
this$1.parseClassMethod(classBody, method, isGenerator, isAsync)
if (isGetSet) {
var paramCount = method.kind === "get" ? 0 : 1
if (method.value.params.length !== paramCount) {
var start = method.value.start
if (method.kind === "get")
this$1.raiseRecoverable(start, "getter should have no params")
else
this$1.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (method.kind === "set" && method.value.params[0].type === "RestElement")
this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params")
}
}
}
node.body = this.finishNode(classBody, "ClassBody")
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}
pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync)
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
pp$1.parseClassId = function(node, isStatement) {
node.id = this.type === tt.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null
}
pp$1.parseClassSuper = function(node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
}
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
var this$1 = this;
this.next()
// export * from '...'
if (this.eat(tt.star)) {
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.semicolon()
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(tt._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart)
var isAsync
if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode()
this.next()
if (isAsync) this.next()
node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync)
} else if (this.type === tt._class) {
var cNode = this.startNode()
node.declaration = this.parseClass(cNode, "nullableID")
} else {
node.declaration = this.parseMaybeAssign()
this.semicolon()
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(true)
if (node.declaration.type === "VariableDeclaration")
this.checkVariableExport(exports, node.declaration.declarations)
else
this.checkExport(exports, node.declaration.id.name, node.declaration.id.start)
node.specifiers = []
node.source = null
} else { // export { x, y as z } [from '...']
node.declaration = null
node.specifiers = this.parseExportSpecifiers(exports)
if (this.eatContextual("from")) {
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
} else {
// check for keywords used as local names
for (var i = 0; i < node.specifiers.length; i++) {
if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) {
this$1.unexpected(node.specifiers[i].local.start)
}
}
node.source = null
}
this.semicolon()
}
return this.finishNode(node, "ExportNamedDeclaration")
}
pp$1.checkExport = function(exports, name, pos) {
if (!exports) return
if (has(exports, name))
this.raiseRecoverable(pos, "Duplicate export '" + name + "'")
exports[name] = true
}
pp$1.checkPatternExport = function(exports, pat) {
var this$1 = this;
var type = pat.type
if (type == "Identifier")
this.checkExport(exports, pat.name, pat.start)
else if (type == "ObjectPattern")
for (var i = 0; i < pat.properties.length; ++i)
this$1.checkPatternExport(exports, pat.properties[i].value)
else if (type == "ArrayPattern")
for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) {
var elt = pat.elements[i$1]
if (elt) this$1.checkPatternExport(exports, elt)
}
else if (type == "AssignmentPattern")
this.checkPatternExport(exports, pat.left)
else if (type == "ParenthesizedExpression")
this.checkPatternExport(exports, pat.expression)
}
pp$1.checkVariableExport = function(exports, decls) {
var this$1 = this;
if (!exports) return
for (var i = 0; i < decls.length; i++)
this$1.checkPatternExport(exports, decls[i].id)
}
pp$1.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
}
// Parses a comma-separated list of module exports.
pp$1.parseExportSpecifiers = function(exports) {
var this$1 = this;
var nodes = [], first = true
// export { x, y as z } [from '...']
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node = this$1.startNode()
node.local = this$1.parseIdent(true)
node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local
this$1.checkExport(exports, node.exported.name, node.exported.start)
nodes.push(this$1.finishNode(node, "ExportSpecifier"))
}
return nodes
}
// Parses import declaration.
pp$1.parseImport = function(node) {
this.next()
// import '...'
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
} else {
node.specifiers = this.parseImportSpecifiers()
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
}
this.semicolon()
return this.finishNode(node, "ImportDeclaration")
}
// Parses a comma-separated list of module imports.
pp$1.parseImportSpecifiers = function() {
var this$1 = this;
var nodes = [], first = true
if (this.type === tt.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode()
node.local = this.parseIdent()
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
if (!this.eat(tt.comma)) return nodes
}
if (this.type === tt.star) {
var node$1 = this.startNode()
this.next()
this.expectContextual("as")
node$1.local = this.parseIdent()
this.checkLVal(node$1.local, "let")
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"))
return nodes
}
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node$2 = this$1.startNode()
node$2.imported = this$1.parseIdent(true)
if (this$1.eatContextual("as")) {
node$2.local = this$1.parseIdent()
} else {
node$2.local = node$2.imported
if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start)
if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved")
}
this$1.checkLVal(node$2.local, "let")
nodes.push(this$1.finishNode(node$2, "ImportSpecifier"))
}
return nodes
}
var pp$2 = Parser.prototype
// Convert existing expression atom to assignable pattern
// if possible.
pp$2.toAssignable = function(node, isBinding) {
var this$1 = this;
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
this.raise(node.start, "Can not use 'await' as identifier inside an async function")
break
case "ObjectPattern":
case "ArrayPattern":
break
case "ObjectExpression":
node.type = "ObjectPattern"
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i]
if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter")
this$1.toAssignable(prop.value, isBinding)
}
break
case "ArrayExpression":
node.type = "ArrayPattern"
this.toAssignableList(node.elements, isBinding)
break
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern"
delete node.operator
this.toAssignable(node.left, isBinding)
// falls through to AssignmentPattern
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
break
}
case "AssignmentPattern":
break
case "ParenthesizedExpression":
node.expression = this.toAssignable(node.expression, isBinding)
break
case "MemberExpression":
if (!isBinding) break
default:
this.raise(node.start, "Assigning to rvalue")
}
}
return node
}
// Convert list of expression atoms to binding list.
pp$2.toAssignableList = function(exprList, isBinding) {
var this$1 = this;
var end = exprList.length
if (end) {
var last = exprList[end - 1]
if (last && last.type == "RestElement") {
--end
} else if (last && last.type == "SpreadElement") {
last.type = "RestElement"
var arg = last.argument
this.toAssignable(arg, isBinding)
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern")
this.unexpected(arg.start)
--end
}
if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
this.unexpected(last.argument.start)
}
for (var i = 0; i < end; i++) {
var elt = exprList[i]
if (elt) this$1.toAssignable(elt, isBinding)
}
return exprList
}
// Parses spread element.
pp$2.parseSpread = function(refDestructuringErrors) {
var node = this.startNode()
this.next()
node.argument = this.parseMaybeAssign(false, refDestructuringErrors)
return this.finishNode(node, "SpreadElement")
}
pp$2.parseRest = function(allowNonIdent) {
var node = this.startNode()
this.next()
// RestElement inside of a function parameter must be an identifier
if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected()
else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected()
return this.finishNode(node, "RestElement")
}
// Parses lvalue (assignable) atom.
pp$2.parseBindingAtom = function() {
if (this.options.ecmaVersion < 6) return this.parseIdent()
switch (this.type) {
case tt.name:
return this.parseIdent()
case tt.bracketL:
var node = this.startNode()
this.next()
node.elements = this.parseBindingList(tt.bracketR, true, true)
return this.finishNode(node, "ArrayPattern")
case tt.braceL:
return this.parseObj(true)
default:
this.unexpected()
}
}
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (first) first = false
else this$1.expect(tt.comma)
if (allowEmpty && this$1.type === tt.comma) {
elts.push(null)
} else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
break
} else if (this$1.type === tt.ellipsis) {
var rest = this$1.parseRest(allowNonIdent)
this$1.parseBindingListItem(rest)
elts.push(rest)
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
this$1.expect(close)
break
} else {
var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc)
this$1.parseBindingListItem(elem)
elts.push(elem)
}
}
return elts
}
pp$2.parseBindingListItem = function(param) {
return param
}
// Parses assignment pattern around given atom if possible.
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom()
if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.right = this.parseMaybeAssign()
return this.finishNode(node, "AssignmentPattern")
}
// Verify that a node is an lval — something that can be assigned
// to.
// bindingType can be either:
// 'var' indicating that the lval creates a 'var' binding
// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
var this$1 = this;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
if (checkClashes) {
if (has(checkClashes, expr.name))
this.raiseRecoverable(expr.start, "Argument name clash")
checkClashes[expr.name] = true
}
if (bindingType && bindingType !== "none") {
if (
bindingType === "var" && !this.canDeclareVarName(expr.name) ||
bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
) {
this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"))
}
if (bindingType === "var") {
this.declareVarName(expr.name)
} else {
this.declareLexicalName(expr.name)
}
}
break
case "MemberExpression":
if (bindingType) this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression")
break
case "ObjectPattern":
for (var i = 0; i < expr.properties.length; i++)
this$1.checkLVal(expr.properties[i].value, bindingType, checkClashes)
break
case "ArrayPattern":
for (var i$1 = 0; i$1 < expr.elements.length; i$1++) {
var elem = expr.elements[i$1]
if (elem) this$1.checkLVal(elem, bindingType, checkClashes)
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, bindingType, checkClashes)
break
case "RestElement":
this.checkLVal(expr.argument, bindingType, checkClashes)
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, bindingType, checkClashes)
break
default:
this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue")
}
}
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
var pp$3 = Parser.prototype
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp$3.checkPropClash = function(prop, propHash) {
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
return
var key = prop.key;
var name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
propHash.proto = true
}
return
}
name = "$" + name
var other = propHash[name]
if (other) {
var redefinition
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set
} else {
redefinition = other.init || other[kind]
}
if (redefinition)
this.raiseRecoverable(key.start, "Redefinition of property")
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
}
}
other[kind] = true
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
if (this.type === tt.comma) {
var node = this.startNodeAt(startPos, startLoc)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.inGenerator && this.isContextual("yield")) return this.parseYield()
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign
oldTrailingComma = refDestructuringErrors.trailingComma
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
} else {
refDestructuringErrors = new DestructuringErrors
ownDestructuringErrors = true
}
var startPos = this.start, startLoc = this.startLoc
if (this.type == tt.parenL || this.type == tt.name)
this.potentialArrowAt = this.start
var left = this.parseMaybeConditional(noIn, refDestructuringErrors)
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
if (this.type.isAssign) {
this.checkPatternErrors(refDestructuringErrors, true)
if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
var node = this.startNodeAt(startPos, startLoc)
node.operator = this.value
node.left = this.type === tt.eq ? this.toAssignable(left) : left
refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
}
if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
return left
}
// Parse a ternary conditional (`?:`) operator.
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprOps(noIn, refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
if (this.eat(tt.question)) {
var node = this.startNodeAt(startPos, startLoc)
node.test = expr
node.consequent = this.parseMaybeAssign()
this.expect(tt.colon)
node.alternate = this.parseMaybeAssign(noIn)
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeUnary(refDestructuringErrors, false)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
var prec = this.type.binop
if (prec != null && (!noIn || this.type !== tt._in)) {
if (prec > minPrec) {
var logical = this.type === tt.logicalOR || this.type === tt.logicalAND
var op = this.value
this.next()
var startPos = this.start, startLoc = this.startLoc
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
}
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.operator = op
node.right = right
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
}
// Parse unary operators, both prefix and postfix.
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, expr
if (this.inAsync && this.isContextual("await")) {
expr = this.parseAwait(refDestructuringErrors)
sawUnary = true
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === tt.incDec
node.operator = this.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(null, true)
this.checkExpressionErrors(refDestructuringErrors, true)
if (update) this.checkLVal(node.argument)
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
else sawUnary = true
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else {
expr = this.parseExprSubscripts(refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.operator = this$1.value
node$1.prefix = false
node$1.argument = expr
this$1.checkLVal(expr)
this$1.next()
expr = this$1.finishNode(node$1, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar))
return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
else
return expr
}
// Parse call, dot, and `[]`-subscript expressions.
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprAtom(refDestructuringErrors)
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
var result = this.parseSubscripts(expr, startPos, startLoc)
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
}
return result
}
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
var this$1 = this;
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd == base.end && !this.canInsertSemicolon()
for (var computed;;) {
if ((computed = this$1.eat(tt.bracketL)) || this$1.eat(tt.dot)) {
var node = this$1.startNodeAt(startPos, startLoc)
node.object = base
node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true)
node.computed = !!computed
if (computed) this$1.expect(tt.bracketR)
base = this$1.finishNode(node, "MemberExpression")
} else if (!noCalls && this$1.eat(tt.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos
this$1.yieldPos = 0
this$1.awaitPos = 0
var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors)
if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) {
this$1.checkPatternErrors(refDestructuringErrors, false)
this$1.checkYieldAwaitInDefaultParams()
this$1.yieldPos = oldYieldPos
this$1.awaitPos = oldAwaitPos
return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
}
this$1.checkExpressionErrors(refDestructuringErrors, true)
this$1.yieldPos = oldYieldPos || this$1.yieldPos
this$1.awaitPos = oldAwaitPos || this$1.awaitPos
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.callee = base
node$1.arguments = exprList
base = this$1.finishNode(node$1, "CallExpression")
} else if (this$1.type === tt.backQuote) {
var node$2 = this$1.startNodeAt(startPos, startLoc)
node$2.tag = base
node$2.quasi = this$1.parseTemplate()
base = this$1.finishNode(node$2, "TaggedTemplateExpression")
} else {
return base
}
}
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$3.parseExprAtom = function(refDestructuringErrors) {
var node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._super:
if (!this.inFunction)
this.raise(this.start, "'super' outside of function or class")
case tt._this:
var type = this.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
var startPos = this.start, startLoc = this.startLoc
var id = this.parseIdent(this.type !== tt.name)
if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true)
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) {
id = this.parseIdent()
if (this.canInsertSemicolon() || !this.eat(tt.arrow))
this.unexpected()
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case tt.regexp:
var value = this.value
node = this.parseLiteral(value.value)
node.regex = {pattern: value.pattern, flags: value.flags}
return node
case tt.num: case tt.string:
return this.parseLiteral(this.value)
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.type === tt._null ? null : this.type === tt._true
node.raw = this.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
refDestructuringErrors.parenthesizedAssign = start
if (refDestructuringErrors.parenthesizedBind < 0)
refDestructuringErrors.parenthesizedBind = start
}
return expr
case tt.bracketL:
node = this.startNode()
this.next()
node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj(false, refDestructuringErrors)
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._class:
return this.parseClass(this.startNode(), false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
this.unexpected()
}
}
pp$3.parseLiteral = function(value) {
var node = this.startNode()
node.value = value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "Literal")
}
pp$3.parseParenExpression = function() {
this.expect(tt.parenL)
var val = this.parseExpression()
this.expect(tt.parenR)
return val
}
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
if (this.options.ecmaVersion >= 6) {
this.next()
var innerStartPos = this.start, innerStartLoc = this.startLoc
var exprList = [], first = true, lastIsComma = false
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart
this.yieldPos = 0
this.awaitPos = 0
while (this.type !== tt.parenR) {
first ? first = false : this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) {
lastIsComma = true
break
} else if (this$1.type === tt.ellipsis) {
spreadStart = this$1.start
exprList.push(this$1.parseParenItem(this$1.parseRest()))
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
break
} else {
if (this$1.type === tt.parenL && !innerParenStart) {
innerParenStart = this$1.start
}
exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem))
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc
this.expect(tt.parenR)
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
if (innerParenStart) this.unexpected(innerParenStart)
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
if (spreadStart) this.unexpected(spreadStart)
this.checkExpressionErrors(refDestructuringErrors, true)
this.yieldPos = oldYieldPos || this.yieldPos
this.awaitPos = oldAwaitPos || this.awaitPos
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc)
val.expressions = exprList
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
} else {
val = exprList[0]
}
} else {
val = this.parseParenExpression()
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc)
par.expression = val
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
}
pp$3.parseParenItem = function(item) {
return item
}
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty$1 = []
pp$3.parseNew = function() {
var node = this.startNode()
var meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
if (node.property.name !== "target")
this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
if (!this.inFunction)
this.raiseRecoverable(node.start, "new.target can only be used in functions")
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
else node.arguments = empty$1
return this.finishNode(node, "NewExpression")
}
// Parse template expression.
pp$3.parseTemplateElement = function() {
var elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
}
this.next()
elem.tail = this.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
pp$3.parseTemplate = function() {
var this$1 = this;
var node = this.startNode()
this.next()
node.expressions = []
var curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this$1.expect(tt.dollarBraceL)
node.expressions.push(this$1.parseExpression())
this$1.expect(tt.braceR)
node.quasis.push(curElt = this$1.parseTemplateElement())
}
this.next()
return this.finishNode(node, "TemplateLiteral")
}
// Parse an object literal or binding pattern.
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
var this$1 = this;
var node = this.startNode(), first = true, propHash = {}
node.properties = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc
if (this$1.options.ecmaVersion >= 6) {
prop.method = false
prop.shorthand = false
if (isPattern || refDestructuringErrors) {
startPos = this$1.start
startLoc = this$1.startLoc
}
if (!isPattern)
isGenerator = this$1.eat(tt.star)
}
this$1.parsePropertyName(prop)
if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed &&
prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL &&
this$1.type !== tt.colon && !this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(prop, refDestructuringErrors)
} else {
isAsync = false
}
this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors)
this$1.checkPropClash(prop, propHash)
node.properties.push(this$1.finishNode(prop, "Property"))
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
if ((isGenerator || isAsync) && this.type === tt.colon)
this.unexpected()
if (this.eat(tt.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
prop.kind = "init"
} else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
if (isPattern) this.unexpected()
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator, isAsync)
} else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type != tt.comma && this.type != tt.braceR)) {
if (isGenerator || isAsync || isPattern) this.unexpected()
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
var paramCount = prop.kind === "get" ? 0 : 1
if (prop.value.params.length !== paramCount) {
var start = prop.value.start
if (prop.kind === "get")
this.raiseRecoverable(start, "getter should have no params")
else
this.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (this.keywords.test(prop.key.name) ||
(this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) ||
(this.inGenerator && prop.key.name == "yield") ||
(this.inAsync && prop.key.name == "await"))
this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property")
prop.kind = "init"
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else if (this.type === tt.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
refDestructuringErrors.shorthandAssign = this.start
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else {
prop.value = prop.key
}
prop.shorthand = true
} else this.unexpected()
}
pp$3.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return prop.key
} else {
prop.computed = false
}
}
return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
}
// Initialize empty function node.
pp$3.initFunction = function(node) {
node.id = null
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
if (this.options.ecmaVersion >= 8)
node.async = false
}
// Parse object or class method.
pp$3.parseMethod = function(isGenerator, isAsync) {
var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.initFunction(node)
if (this.options.ecmaVersion >= 6)
node.generator = isGenerator
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
this.checkYieldAwaitInDefaultParams()
this.parseFunctionBody(node, false)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "FunctionExpression")
}
// Parse arrow function expression with given parameters.
pp$3.parseArrowExpression = function(node, params, isAsync) {
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.enterFunctionScope()
this.initFunction(node)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = false
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
node.params = this.toAssignableList(params, true)
this.parseFunctionBody(node, true)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "ArrowFunctionExpression")
}
// Parse function body and check parameters.
pp$3.parseFunctionBody = function(node, isArrowFunction) {
var isExpression = isArrowFunction && this.type !== tt.braceL
var oldStrict = this.strict, useStrict = false
if (isExpression) {
node.body = this.parseMaybeAssign()
node.expression = true
this.checkParams(node, false)
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end)
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list")
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels
this.labels = []
if (useStrict) this.strict = true
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params))
node.body = this.parseBlock(false)
node.expression = false
this.labels = oldLabels
}
this.exitFunctionScope()
if (this.strict && node.id) {
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
this.checkLVal(node.id, "none")
}
this.strict = oldStrict
}
pp$3.isSimpleParamList = function(params) {
for (var i = 0; i < params.length; i++)
if (params[i].type !== "Identifier") return false
return true
}
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp$3.checkParams = function(node, allowDuplicates) {
var this$1 = this;
var nameHash = {}
for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], "var", allowDuplicates ? null : nameHash)
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (!first) {
this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(close)) break
} else first = false
var elt
if (allowEmpty && this$1.type === tt.comma)
elt = null
else if (this$1.type === tt.ellipsis) {
elt = this$1.parseSpread(refDestructuringErrors)
if (refDestructuringErrors && this$1.type === tt.comma && refDestructuringErrors.trailingComma < 0)
refDestructuringErrors.trailingComma = this$1.start
} else {
elt = this$1.parseMaybeAssign(false, refDestructuringErrors)
}
elts.push(elt)
}
return elts
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp$3.parseIdent = function(liberal) {
var node = this.startNode()
if (liberal && this.options.allowReserved == "never") liberal = false
if (this.type === tt.name) {
if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) &&
(this.options.ecmaVersion >= 6 ||
this.input.slice(this.start, this.end).indexOf("\\") == -1))
this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved")
if (this.inGenerator && this.value === "yield")
this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator")
if (this.inAsync && this.value === "await")
this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function")
node.name = this.value
} else if (liberal && this.type.keyword) {
node.name = this.type.keyword
} else {
this.unexpected()
}
this.next()
return this.finishNode(node, "Identifier")
}
// Parses yield expression inside generator.
pp$3.parseYield = function() {
if (!this.yieldPos) this.yieldPos = this.start
var node = this.startNode()
this.next()
if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
pp$3.parseAwait = function() {
if (!this.awaitPos) this.awaitPos = this.start
var node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(null, true)
return this.finishNode(node, "AwaitExpression")
}
var pp$4 = Parser.prototype
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos)
message += " (" + loc.line + ":" + loc.column + ")"
var err = new SyntaxError(message)
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
throw err
}
pp$4.raiseRecoverable = pp$4.raise
pp$4.curPosition = function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
}
var pp$5 = Parser.prototype
// Object.assign polyfill
var assign = Object.assign || function(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
for (var i = 0; i < sources.length; i++) {
var source = sources[i]
for (var key in source) {
if (has(source, key)) {
target[key] = source[key]
}
}
}
return target
}
// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
pp$5.enterFunctionScope = function() {
// var: a hash of var-declared names in the current lexical scope
// lexical: a hash of lexically-declared names in the current lexical scope
// childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
// parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}})
}
pp$5.exitFunctionScope = function() {
this.scopeStack.pop()
}
pp$5.enterLexicalScope = function() {
var parentScope = this.scopeStack[this.scopeStack.length - 1]
var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}}
this.scopeStack.push(childScope)
assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical)
}
pp$5.exitLexicalScope = function() {
var childScope = this.scopeStack.pop()
var parentScope = this.scopeStack[this.scopeStack.length - 1]
assign(parentScope.childVar, childScope.var, childScope.childVar)
}
/**
* A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
* in the current lexical scope or any of the parent lexical scopes in this function.
*/
pp$5.canDeclareVarName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
}
/**
* A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
* in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
* any child lexical scopes in this function.
*/
pp$5.canDeclareLexicalName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
}
pp$5.declareVarName = function(name) {
this.scopeStack[this.scopeStack.length - 1].var[name] = true
}
pp$5.declareLexicalName = function(name) {
this.scopeStack[this.scopeStack.length - 1].lexical[name] = true
}
var Node = function Node(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
};
// Start an AST node, attaching a start offset.
var pp$6 = Parser.prototype
pp$6.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp$6.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp$6.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp$6.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token
this.isExpr = !!isExpr
this.preserveSpace = !!preserveSpace
this.override = override
this.generator = !!generator
};
var types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
}
var pp$7 = Parser.prototype
pp$7.initialContext = function() {
return [types.b_stat]
}
pp$7.braceIsBlock = function(prevType) {
if (prevType === tt.colon) {
var parent = this.curContext()
if (parent === types.b_stat || parent === types.b_expr)
return !parent.isExpr
}
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR || prevType == tt.arrow)
return true
if (prevType == tt.braceL)
return this.curContext() === types.b_stat
return !this.exprAllowed
}
pp$7.inGeneratorContext = function() {
var this$1 = this;
for (var i = this.context.length - 1; i >= 0; i--)
if (this$1.context[i].generator) return true
return false
}
pp$7.updateContext = function(prevType) {
var update, type = this.type
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false
else if (update = type.updateContext)
update.call(this, prevType)
else
this.exprAllowed = type.beforeExpr
}
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true
return
}
var out = this.context.pop(), cur
if (out === types.b_stat && (cur = this.curContext()) && cur.token === "function") {
this.context.pop()
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
}
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr)
this.exprAllowed = true
}
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl)
this.exprAllowed = true
}
tt.parenL.updateContext = function(prevType) {
var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while
this.context.push(statementParens ? types.p_stat : types.p_expr)
this.exprAllowed = true
}
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
}
tt._function.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else &&
!((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat))
this.context.push(types.f_expr)
this.exprAllowed = false
}
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop()
else
this.context.push(types.q_tmpl)
this.exprAllowed = false
}
tt.star.updateContext = function(prevType) {
if (prevType == tt._function) {
if (this.curContext() === types.f_expr)
this.context[this.context.length - 1] = types.f_expr_gen
else
this.context.push(types.f_gen)
}
this.exprAllowed = true
}
tt.name.updateContext = function(prevType) {
var allowed = false
if (this.options.ecmaVersion >= 6) {
if (this.value == "of" && !this.exprAllowed ||
this.value == "yield" && this.inGeneratorContext())
allowed = true
}
this.exprAllowed = allowed
}
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
var Token = function Token(p) {
this.type = p.type
this.value = p.value
this.start = p.start
this.end = p.end
if (p.options.locations)
this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
if (p.options.ranges)
this.range = [p.start, p.end]
};
// ## Tokenizer
var pp$8 = Parser.prototype
// Are we running under Rhino?
var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
// Move to the next token
pp$8.next = function() {
if (this.options.onToken)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end
this.lastTokStart = this.start
this.lastTokEndLoc = this.endLoc
this.lastTokStartLoc = this.startLoc
this.nextToken()
}
pp$8.getToken = function() {
this.next()
return new Token(this)
}
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
pp$8[Symbol.iterator] = function() {
var this$1 = this;
return {
next: function () {
var token = this$1.getToken()
return {
done: token.type === tt.eof,
value: token
}
}
}
}
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp$8.curContext = function() {
return this.context[this.context.length - 1]
}
// Read a single token, updating the parser object's token-related
// properties.
pp$8.nextToken = function() {
var curContext = this.curContext()
if (!curContext || !curContext.preserveSpace) this.skipSpace()
this.start = this.pos
if (this.options.locations) this.startLoc = this.curPosition()
if (this.pos >= this.input.length) return this.finishToken(tt.eof)
if (curContext.override) return curContext.override(this)
else this.readToken(this.fullCharCodeAtPos())
}
pp$8.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
return this.readWord()
return this.getTokenFromCode(code)
}
pp$8.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos)
if (code <= 0xd7ff || code >= 0xe000) return code
var next = this.input.charCodeAt(this.pos + 1)
return (code << 10) + next - 0x35fdc00
}
pp$8.skipBlockComment = function() {
var this$1 = this;
var startLoc = this.options.onComment && this.curPosition()
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + 2
if (this.options.locations) {
lineBreakG.lastIndex = start
var match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this$1.curLine
this$1.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
}
pp$8.skipLineComment = function(startSkip) {
var this$1 = this;
var start = this.pos
var startLoc = this.options.onComment && this.curPosition()
var ch = this.input.charCodeAt(this.pos += startSkip)
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this$1.pos
ch = this$1.input.charCodeAt(this$1.pos)
}
if (this.options.onComment)
this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition())
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp$8.skipSpace = function() {
var this$1 = this;
loop: while (this.pos < this.input.length) {
var ch = this$1.input.charCodeAt(this$1.pos)
switch (ch) {
case 32: case 160: // ' '
++this$1.pos
break
case 13:
if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
++this$1.pos
}
case 10: case 8232: case 8233:
++this$1.pos
if (this$1.options.locations) {
++this$1.curLine
this$1.lineStart = this$1.pos
}
break
case 47: // '/'
switch (this$1.input.charCodeAt(this$1.pos + 1)) {
case 42: // '*'
this$1.skipBlockComment()
break
case 47:
this$1.skipLineComment(2)
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this$1.pos
} else {
break loop
}
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp$8.finishToken = function(type, val) {
this.end = this.pos
if (this.options.locations) this.endLoc = this.curPosition()
var prevType = this.type
this.type = type
this.value = val
this.updateContext(prevType)
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$8.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1)
if (next >= 48 && next <= 57) return this.readNumber(true)
var next2 = this.input.charCodeAt(this.pos + 2)
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3
return this.finishToken(tt.ellipsis)
} else {
++this.pos
return this.finishToken(tt.dot)
}
}
pp$8.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1)
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.slash, 1)
}
pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
var tokentype = code === 42 ? tt.star : tt.modulo
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && next === 42) {
++size
tokentype = tt.starstar
next = this.input.charCodeAt(this.pos + 2)
}
if (next === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tokentype, size)
}
pp$8.readToken_pipe_amp = function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
}
pp$8.readToken_caret = function() { // '^'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.bitwiseXOR, 1)
}
pp$8.readToken_plus_min = function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3)
this.skipSpace()
return this.nextToken()
}
return this.finishOp(tt.incDec, 2)
}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.plusMin, 1)
}
pp$8.readToken_lt_gt = function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tt.bitShift, size)
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
return this.nextToken()
}
if (next === 61) size = 2
return this.finishOp(tt.relational, size)
}
pp$8.readToken_eq_excl = function(code) { // '=!'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2)
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2
return this.finishToken(tt.arrow)
}
return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1)
}
pp$8.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(tt.parenL)
case 41: ++this.pos; return this.finishToken(tt.parenR)
case 59: ++this.pos; return this.finishToken(tt.semi)
case 44: ++this.pos; return this.finishToken(tt.comma)
case 91: ++this.pos; return this.finishToken(tt.bracketL)
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58: ++this.pos; return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 96: // '`'
if (this.options.ecmaVersion < 6) break
++this.pos
return this.finishToken(tt.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 120 || next === 88) return this.readRadixNumber(16) // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) return this.readRadixNumber(8) // '0o', '0O' - octal number
if (next === 98 || next === 66) return this.readRadixNumber(2) // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(tt.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
}
pp$8.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size)
this.pos += size
return this.finishToken(type, str)
}
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
function tryCreateRegexp(src, flags, throwErrorAt, parser) {
try {
return new RegExp(src, flags)
} catch (e) {
if (throwErrorAt !== undefined) {
if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message)
throw e
}
}
}
var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u")
pp$8.readRegexp = function() {
var this$1 = this;
var escaped, inClass, start = this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(start, "Unterminated regular expression")
var ch = this$1.input.charAt(this$1.pos)
if (lineBreak.test(ch)) this$1.raise(start, "Unterminated regular expression")
if (!escaped) {
if (ch === "[") inClass = true
else if (ch === "]" && inClass) inClass = false
else if (ch === "/" && !inClass) break
escaped = ch === "\\"
} else escaped = false
++this$1.pos
}
var content = this.input.slice(start, this.pos)
++this.pos
// Need to use `readWord1` because '\uXXXX' sequences are allowed
// here (don't ask).
var mods = this.readWord1()
var tmp = content, tmpFlags = ""
if (mods) {
var validFlags = /^[gim]*$/
if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag")
if (mods.indexOf("u") >= 0) {
if (regexpUnicodeSupport) {
tmpFlags = "u"
} else {
// Replace each astral symbol and every Unicode escape sequence that
// possibly represents an astral symbol or a paired surrogate with a
// single ASCII symbol to avoid throwing on regular expressions that
// are only valid in combination with the `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
code = Number("0x" + code)
if (code > 0x10FFFF) this$1.raise(start + offset + 3, "Code point out of bounds")
return "x"
})
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
tmpFlags = tmpFlags.replace("u", "")
}
}
}
// Detect invalid regular expressions.
var value = null
// Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino
if (!isRhino) {
tryCreateRegexp(tmp, tmpFlags, start, this)
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
value = tryCreateRegexp(content, mods)
}
return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value})
}
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp$8.readInt = function(radix, len) {
var this$1 = this;
var start = this.pos, total = 0
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
var code = this$1.input.charCodeAt(this$1.pos), val
if (code >= 97) val = code - 97 + 10 // a
else if (code >= 65) val = code - 65 + 10 // A
else if (code >= 48 && code <= 57) val = code - 48 // 0-9
else val = Infinity
if (val >= radix) break
++this$1.pos
total = total * radix + val
}
if (this.pos === start || len != null && this.pos - start !== len) return null
return total
}
pp$8.readRadixNumber = function(radix) {
this.pos += 2 // 0x
var val = this.readInt(radix)
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix)
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
return this.finishToken(tt.num, val)
}
// Read an integer, octal integer, or floating-point number.
pp$8.readNumber = function(startsWithDot) {
var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48
if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number")
if (octal && this.pos == start + 1) octal = false
var next = this.input.charCodeAt(this.pos)
if (next === 46 && !octal) { // '.'
++this.pos
this.readInt(10)
isFloat = true
next = this.input.charCodeAt(this.pos)
}
if ((next === 69 || next === 101) && !octal) { // 'eE'
next = this.input.charCodeAt(++this.pos)
if (next === 43 || next === 45) ++this.pos // '+-'
if (this.readInt(10) === null) this.raise(start, "Invalid number")
isFloat = true
}
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
var str = this.input.slice(start, this.pos), val
if (isFloat) val = parseFloat(str)
else if (!octal || str.length === 1) val = parseInt(str, 10)
else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number")
else val = parseInt(str, 8)
return this.finishToken(tt.num, val)
}
// Read a string value, interpreting backslash-escapes.
pp$8.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected()
var codePos = ++this.pos
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos)
++this.pos
if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds")
} else {
code = this.readHexChar(4)
}
return code
}
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) return String.fromCharCode(code)
code -= 0x10000
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
pp$8.readString = function(quote) {
var this$1 = this;
var out = "", chunkStart = ++this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(this$1.start, "Unterminated string constant")
var ch = this$1.input.charCodeAt(this$1.pos)
if (ch === quote) break
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos)
out += this$1.readEscapedChar(false)
chunkStart = this$1.pos
} else {
if (isNewLine(ch)) this$1.raise(this$1.start, "Unterminated string constant")
++this$1.pos
}
}
out += this.input.slice(chunkStart, this.pos++)
return this.finishToken(tt.string, out)
}
// Reads template string tokens.
pp$8.readTmplToken = function() {
var this$1 = this;
var out = "", chunkStart = this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(this$1.start, "Unterminated template")
var ch = this$1.input.charCodeAt(this$1.pos)
if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
if (this$1.pos === this$1.start && this$1.type === tt.template) {
if (ch === 36) {
this$1.pos += 2
return this$1.finishToken(tt.dollarBraceL)
} else {
++this$1.pos
return this$1.finishToken(tt.backQuote)
}
}
out += this$1.input.slice(chunkStart, this$1.pos)
return this$1.finishToken(tt.template, out)
}
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos)
out += this$1.readEscapedChar(true)
chunkStart = this$1.pos
} else if (isNewLine(ch)) {
out += this$1.input.slice(chunkStart, this$1.pos)
++this$1.pos
switch (ch) {
case 13:
if (this$1.input.charCodeAt(this$1.pos) === 10) ++this$1.pos
case 10:
out += "\n"
break
default:
out += String.fromCharCode(ch)
break
}
if (this$1.options.locations) {
++this$1.curLine
this$1.lineStart = this$1.pos
}
chunkStart = this$1.pos
} else {
++this$1.pos
}
}
}
// Used to read escaped characters
pp$8.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos)
++this.pos
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]
var octal = parseInt(octalStr, 8)
if (octal > 255) {
octalStr = octalStr.slice(0, -1)
octal = parseInt(octalStr, 8)
}
if (octalStr !== "0" && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode")
}
this.pos += octalStr.length - 1
return String.fromCharCode(octal)
}
return String.fromCharCode(ch)
}
}
// Used to read character escape sequences ('\x', '\u', '\U').
pp$8.readHexChar = function(len) {
var codePos = this.pos
var n = this.readInt(16, len)
if (n === null) this.raise(codePos, "Bad character escape sequence")
return n
}
// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp$8.readWord1 = function() {
var this$1 = this;
this.containsEsc = false
var word = "", first = true, chunkStart = this.pos
var astral = this.options.ecmaVersion >= 6
while (this.pos < this.input.length) {
var ch = this$1.fullCharCodeAtPos()
if (isIdentifierChar(ch, astral)) {
this$1.pos += ch <= 0xffff ? 1 : 2
} else if (ch === 92) { // "\"
this$1.containsEsc = true
word += this$1.input.slice(chunkStart, this$1.pos)
var escStart = this$1.pos
if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
this$1.raise(this$1.pos, "Expecting Unicode escape sequence \\uXXXX")
++this$1.pos
var esc = this$1.readCodePoint()
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
this$1.raise(escStart, "Invalid Unicode escape")
word += codePointToString(esc)
chunkStart = this$1.pos
} else {
break
}
first = false
}
return word + this.input.slice(chunkStart, this.pos)
}
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp$8.readWord = function() {
var word = this.readWord1()
var type = tt.name
if (this.keywords.test(word)) {
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword " + word)
type = keywordTypes[word]
}
return this.finishToken(type, word)
}
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/ternjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/ternjs/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
var version = "5.0.3"
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
function parse(input, options) {
return new Parser(options, input).parse()
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) {
var p = new Parser(options, input, pos)
p.nextToken()
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return new Parser(options, input)
}
// This is a terrible kludge to support the existing, pre-ES6
// interface where the loose parser module retroactively adds exports
// to this module.
// eslint-disable-line camelcase
function addLooseExports(parse, Parser, plugins) {
exports.parse_dammit = parse // eslint-disable-line camelcase
exports.LooseParser = Parser
exports.pluginsLoose = plugins
}
exports.version = version;
exports.parse = parse;
exports.parseExpressionAt = parseExpressionAt;
exports.tokenizer = tokenizer;
exports.addLooseExports = addLooseExports;
exports.Parser = Parser;
exports.plugins = plugins;
exports.defaultOptions = defaultOptions;
exports.Position = Position;
exports.SourceLocation = SourceLocation;
exports.getLineInfo = getLineInfo;
exports.Node = Node;
exports.TokenType = TokenType;
exports.tokTypes = tt;
exports.keywordTypes = keywordTypes;
exports.TokContext = TokContext;
exports.tokContexts = types;
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierStart = isIdentifierStart;
exports.Token = Token;
exports.isNewLine = isNewLine;
exports.lineBreak = lineBreak;
exports.lineBreakG = lineBreakG;
exports.nonASCIIwhitespace = nonASCIIwhitespace;
Object.defineProperty(exports, '__esModule', { value: true });
})));
/***/ }),
/* 47 */
/*!************************!*\
!*** ./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 _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server */ 11);
/**
* 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 */ "a"].hacking_skill) + (intFactor * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].intelligence);
const skillChance = (skillMult - server.requiredHackingSkill) / skillMult;
const chance = skillChance * difficultyMult * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].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 */ "a"].hacking_exp_mult * diffFactor);
return expGain * _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 */ "a"].hacking_skill - (server.requiredHackingSkill - 1)) / _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill;
const percentMoneyHacked = difficultyMult * skillMult * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_money_mult / balanceFactor;
if (percentMoneyHacked < 0) { return 0; }
if (percentMoneyHacked > 1) { return 1; }
return percentMoneyHacked * _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 */ "a"].hacking_skill;}
if (int == null) {int = _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].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 */ "a"].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);
}
/***/ }),
/* 48 */
/*!*********************!*\
!*** ./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 */ 122);
/* 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 */ 121);
/* 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 */ 8);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction/Faction */ 54);
/* 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 */ 15);
/* 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 */ 44);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/uiHelpers/createAccordionElement */ 73);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* 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 */ 67);
/* 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 */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
/*
Also 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_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].Gang) && event.altKey) {
if (UIElems.gangMemberFilter != null && UIElems.gangMemberFilter === document.activeElement) {return;}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__["KEY"]["1"]) {
if(UIElems.gangTerritorySubpage.style.display === "block") {
UIElems.managementButton.click();
}
} else if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__["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;
}
}
});
let 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_8__["Reviver"]);
}
/**
* @param facName - Name of corresponding faction
* @param hacking - Boolean indicating whether or not its a hacking gang
*/
function Gang(facName, hacking=false) {
this.facName = facName;
this.members = []; //Array of GangMembers
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_15__[/* exceptionAlert */ "a"])(`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_7__["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);
} 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 (var i = 0; i < GangNames.length; ++i) {
const others = GangNames.filter((e) => {
return e !== i;
});
const other = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_16__["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
} 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
} 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_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["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_7__["dialogBoxCreate"])(`${memberObj.name} was killed in a gang clash! You lost ${lostRespect} respect`);
}
// Update UI
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["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_7__["dialogBoxCreate"])([`You ascended ${memberObj.name}!`,
"",
`Your gang lost ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.respect, "0.000a")} respect`,
"",
`${memberObj.name} gained the following stat multipliers for ascending:`,
`Hacking: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.hack, "0.000%")}`,
`Strength: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.str, "0.000%")}`,
`Defense: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.def, "0.000%")}`,
`Dexterity: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.dex, "0.000%")}`,
`Agility: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.agi, "0.000%")}`,
`Charisma: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(res.cha, "0.000%")}`].join("<br>"));
} else {
workerScript.log(`Ascended Gang member ${memberObj.name}`);
}
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].Gang)) {
this.displayGangMemberList();
}
return res;
} catch(e) {
if (workerScript == null) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_15__[/* exceptionAlert */ "a"])(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_8__["Generic_toJSON"])("Gang", this);
}
Gang.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Gang, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Gang = Gang;
/*** Gang Member object ***/
function GangMember(name) {
this.name = name;
this.task = "Unassigned"; //GangMemberTask object
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 only
}
//Same formula for 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_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["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_8__["Generic_toJSON"])("GangMember", this);
}
GangMember.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(GangMember, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["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_8__["Generic_toJSON"])("GangMemberTask", this);
}
GangMemberTask.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(GangMemberTask, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["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("<br>");
}
//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_8__["Generic_toJSON"])("GangMemberUpgrade", this);
}
GangMemberUpgrade.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(GangMemberUpgrade, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["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_11__["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_11__["createElement"])("p", {
innerText: "Discount: -" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].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_12__["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_11__["createElement"])("div", {
border:"1px solid white",
});
var header = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", {
innerText: this.name + " (" + this.task + ")"
});
container.appendChild(header);
var text = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", {
fontSize:"14px", display: "inline-block", width:"20%",
innerText:
"Hack: " + this.hack + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.hack_mult * this.hack_asc_mult, 2) + ")\n" +
"Str: " + this.str + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.str_mult * this.str_asc_mult, 2) + ")\n" +
"Def: " + this.def + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.def_mult * this.def_asc_mult, 2) + ")\n" +
"Dex: " + this.dex + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.dex_mult * this.dex_asc_mult, 2) + ")\n" +
"Agi: " + this.agi + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.agi_mult * this.agi_asc_mult, 2) + ")\n" +
"Cha: " + this.cha + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["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_11__["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_11__["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_11__["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_11__["createElement"])("div", {width: "20%", display: "inline-block"});
const armorDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {width: "20%", display: "inline-block"});
const vehicleDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {width: "20%", display: "inline-block"});
const rootkitDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {width: "20%", display: "inline-block"});
const augDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {width: "20%", display: "inline-block"});
// Add a title/labe for each column
weaponDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h2", {innerText: "Weapons"}));
armorDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h2", {innerText: "Armor"}));
vehicleDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h2", {innerText: "Vehicles"}));
rootkitDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h2", {innerText: "Rootkits"}));
augDiv.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_6__[/* numeralWrapper */ "a"].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_11__["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_11__["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_11__["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 */ "a"])(facName);
return false;
}
}));
//Buttons to switch between panels
UIElems.managementButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_11__["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_11__["createElement"])("p", {width:"70%",
innerHTML:
"This page is used to manage your gang members and get an overview of your " +
"gang's stats.<br><br>" +
"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. <br><br>" +
"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.<br><br>" +
"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_11__["createElement"])("p", {id:"gang-info", width:"70%"});
UIElems.gangManagementSubpage.appendChild(UIElems.gangInfo);
UIElems.gangRecruitMemberButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["createElement"])("p", {
innerText:"Please enter a name for your new Gang member:",
});
const br = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br");
const nameInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", {
onkeyup: (e) => {
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__["KEY"].ENTER) { yesBtn.click(); }
},
placeholder: "Name must be unique",
type: "text",
});
yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", {
class: "std-button",
clickListener: () => {
let name = nameInput.value;
if (name === "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You must enter a name for your Gang member!");
return false;
}
if (!this.canRecruitMember()) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["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_7__["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_11__["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_12__["createPopup"])(popupId, [txt, br, nameInput, yesBtn, noBtn]);
}
});
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_11__["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_11__["createElement"])("br", {}));
UIElems.gangExpandAllButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_11__["createElement"])("input", {
type:"text", placeholder:"Filter gang members", margin:"5px", padding:"5px",
onkeyup:()=>{
this.displayGangMemberList();
}
});
UIElems.gangManageEquipmentButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_11__["createElement"])("div", {
id:"gang-territory-subpage", display:"none"
});
//Info text for territory page
UIElems.gangTerritoryDescText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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.<br><br>" +
"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<br><br>" +
"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.<br><br>" +
"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.<br><br>"
});
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryDescText);
// Checkbox for Engaging in Territory Warfare
UIElems.gangTerritoryWarfareCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_11__["createElement"])("br"));
UIElems.gangTerritoryWarfareClashChance = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", {display: "inline-block"});
UIElems.gangTerritorySubpage.appendChild(UIElems.gangTerritoryWarfareClashChance);
UIElems.gangTerritorySubpage.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {
class: "help-tip",
display: "inline-block",
innerText: "?",
clickListener: () => {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["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_11__["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_11__["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_11__["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_11__["createElement"])("br"));
var territoryBorder = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("fieldset", {
display:"block",
margin: "6px",
width:"50%",
});
UIElems.gangTerritoryInfoText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_6__[/* numeralWrapper */ "a"].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_6__[/* numeralWrapper */ "a"].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_14__["formatNumber"])(0, 2);
} else if (territory >= 100) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(100, 2);
} else {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(territory, 2);
}
if (gangname === this.facName) {
let newHTML = `<b><u>${gangname}</u></b><br>Power: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(gangTerritoryInfo.power, 6)}<br>`;
newHTML += `Territory: ${displayNumber}%<br><br>`;
UIElems.gangTerritoryInfoText.innerHTML += newHTML;
} else {
const clashVictoryChance = playerPower / (gangTerritoryInfo.power + playerPower);
let newHTML = `<u>${gangname}</u><br>Power: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(gangTerritoryInfo.power, 6)}<br>`;
newHTML += `Territory: ${displayNumber}%<br>`;
newHTML += `Chance to win clash with this gang: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(clashVictoryChance, "0.000%")}<br><br>`;
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_11__["createElement"])("p", { // Respect
display: "inline-block",
innerText: "Respect: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.respect, 6) +
" (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["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_11__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { // Wanted level
display: "inline-block",
innerText: "Wanted Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(this.wanted, 6) +
" (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["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_11__["createElement"])("br"));
var wantedPenalty = this.getWantedPenalty();
wantedPenalty = (1 - wantedPenalty) * 100;
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { // Wanted Level multiplier
display: "inline-block",
innerText: `Wanted Level Penalty: -${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["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_11__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { // Money gain rate
display: "inline-block",
innerText: `Money gain rate: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(5 * this.moneyGainRate, "$0.000a")} / sec`,
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_14__["formatNumber"])(0, 2);
} else if (territoryMult >= 100) {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(100, 2);
} else {
displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(territoryMult, 2);
}
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { // Territory multiplier
display: "inline-block",
innerText: `Territory: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(displayNumber, 3)}%`,
tooltip: "The percentage of total territory your Gang controls"
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br"));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { // Faction reputation
display:"inline-block",
innerText:"Faction reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(rep, 3)
}));
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br"));
const CyclesPerSecond = 1000 / _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed;
UIElems.gangInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_14__["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_10__["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_11__["createElement"])("div", {
class: "gang-member-info-div",
id: name + "gang-member-stats",
tooltipsmall: [`Hk: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_mult * memberObj.hack_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_asc_mult, "0,0.00")} Asc)`,
`St: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_mult * memberObj.str_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_asc_mult, "0,0.00")} Asc)`,
`Df: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_mult * memberObj.def_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_asc_mult, "0,0.00")} Asc)`,
`Dx: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_mult * memberObj.dex_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_asc_mult, "0,0.00")} Asc)`,
`Ag: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_mult * memberObj.agi_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_asc_mult, "0,0.00")} Asc)`,
`Ch: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_mult * memberObj.cha_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_asc_mult, "0,0.00")} Asc)`].join("<br>"),
});
UIElems.gangMemberPanels[name]["statsDiv"] = statsDiv;
const statsP = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", {
display: "inline",
id: name + "gang-member-stats-text",
});
const brElement = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br");
const ascendButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_6__[/* numeralWrapper */ "a"].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_6__[/* numeralWrapper */ "a"].format(ascendBenefits.hack, "0.00%")}`,
`Strength: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(ascendBenefits.str, "0.00%")}`,
`Defense: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(ascendBenefits.def, "0.00%")}`,
`Dexterity: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(ascendBenefits.dex, "0.00%")}`,
`Agility: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(ascendBenefits.agi, "0.00%")}`,
`Charisma: +${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(ascendBenefits.cha, "0.00%")}`].join("\n"),
});
const confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_11__["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_12__["createPopup"])(popupId, [txt, confirmBtn, cancelBtn]);
}
});
const ascendHelpTip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {
class: "help-tip",
clickListener: () => {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(["Ascending a Gang Member resets the member's progress and stats in exchange",
"for a permanent boost to their stat multipliers.",
"<br><br>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.",
"<br><br>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_11__["createElement"])("div", {
class:"gang-member-info-div",
id: name + "gang-member-task",
});
const taskSelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["createElement"])("select", {
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_11__["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_11__["createElement"])("div", {
class:"gang-member-info-div",
id: name + "gang-member-task-desc",
});
var taskDescP = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_11__["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_14__["formatNumber"])(memberObj.hack, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_exp, '(0.00a)')} exp)`,
`Strength: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.str, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_exp, '(0.00a)')} exp)`,
`Defense: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.def, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_exp, '(0.00a)')} exp)`,
`Dexterity: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.dex, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_exp, '(0.00a)')} exp)`,
`Agility: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.agi, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_exp, '(0.00a)')} exp)`,
`Charisma: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.cha, 0)} (${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].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_6__[/* numeralWrapper */ "a"].format(memberObj.hack_mult * memberObj.hack_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.hack_asc_mult, "0,0.00")} Asc)`,
`St: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_mult * memberObj.str_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.str_asc_mult, "0,0.00")} Asc)`,
`Df: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_mult * memberObj.def_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.def_asc_mult, "0,0.00")} Asc)`,
`Dx: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_mult * memberObj.dex_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.dex_asc_mult, "0,0.00")} Asc)`,
`Ag: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_mult * memberObj.agi_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.agi_asc_mult, "0,0.00")} Asc)`,
`Ch: x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_mult * memberObj.cha_asc_mult, "0,0.00")}(x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_mult, "0,0.00")} Eq, x${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(memberObj.cha_asc_mult, "0,0.00")} Asc)`].join("<br>");
}
}
// 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_14__["formatNumber"])(5*memberObj.calculateMoneyGain(this), 2)} / sec`,
`Respect: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(5*memberObj.calculateRespectGain(this), 6)} / sec`,
`Wanted Level: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(5*memberObj.calculateWantedLevelGain(this), 6)} / sec`,
`Total Respect Earned: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(memberObj.earnedRespect, 6)}`].join("<br>");
}
// 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 */ 62)))
/***/ }),
/* 49 */
/*!*************************!*\
!*** ./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 _Alias__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias */ 43);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CodingContracts */ 40);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _DarkWeb__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./DarkWeb */ 76);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Fconf */ 45);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Hacking */ 47);
/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./HelpText */ 96);
/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_HelpText__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./InteractiveTutorial */ 33);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Literature */ 78);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Message */ 38);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./RedPill */ 55);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./TextFile */ 60);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 61);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 52);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 83);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/LogBox */ 75);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! autosize */ 140);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(autosize__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! jszip */ 139);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! file-saver */ 138);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_33__);
function postNetburnerText() {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bitburner v" + _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].Version);
}
//Defines key commands in terminal
$(document).keydown(function(event) {
//Terminal
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["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_23__["KEY"].ENTER) {
event.preventDefault(); //Prevent newline from being entered in Script Editor
var command = terminalInput.value;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(
"<span class='prompt'>[" +
(_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].ENABLE_TIMESTAMPS ? Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_27__["getTimestamp"])() + " " : "") +
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname +
" ~]&gt;</span> " + command
);
if (command.length > 0) {
Terminal.resetTerminalInput(); //Clear input first
const commands = command.split(";");
for(let i = 0; i < commands.length; i++) {
if(commands[i].match(/^\s*$/)) { continue; }
Terminal.executeCommand(commands[i]);
}
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].C && event.ctrlKey) {
if (_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"]._actionInProgress) {
//Cancel action
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Cancelling...");
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"]._actionInProgress = false;
Terminal.finishAction(true);
} else if (_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS) {
//Dont prevent default so it still copies
Terminal.resetTerminalInput(); //Clear Terminal
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["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_23__["KEY"].UPARROW ||
(_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].P && event.ctrlKey)) {
if (_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].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;
setTimeout(function(){terminalInput.selectionStart = terminalInput.selectionEnd = 10000; }, 0);
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].DOWNARROW ||
(_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].M && event.ctrlKey)) {
if (_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].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_23__["KEY"].TAB) {
event.preventDefault();
//Autocomplete
if (terminalInput == null) {return;}
var 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, ' ');
var commandArray = input.split(" ");
var index = commandArray.length - 2;
if (index < -1) {index = 0;}
var allPos = determineAllPossibilitiesForTabCompletion(input, index);
if (allPos.length == 0) {return;}
var arg = "";
var 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(" ");
}
tabCompletion(command, arg, allPos);
terminalInput.focus();
}
//Extra Bash Emulation Hotkeys, must be enabled through .fconf
if (_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS) {
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].A && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("home");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].E && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("end");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].B && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("prevchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].B && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("prevword");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].F && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("nextchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].F && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("nextword");
}
if ((event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].H || event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["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_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Terminal)) {
$('.terminal-input').focus();
}
});
$(document).keydown(function(e) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["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_21__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_21__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_23__["KEY"].CTRL) {
terminalCtrlPressed = false;
}
if (e.shiftKey) {
shiftKeyPressed = false;
}
}
})
//Implements a tab completion feature for terminal
// command - Terminal command except for the last incomplete argument
// arg - Incomplete argument string that the function will try to complete, or will display
// a series of possible options for
// allPossibilities - Array of strings containing all possibilities that the
// string can complete to
// index - index of argument that is being "tab completed". By default is 0, the first argument
function tabCompletion(command, arg, allPossibilities, index=0) {
if (!(allPossibilities.constructor === Array)) {return;}
if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["containsAllStrings"])(allPossibilities)) {return;}
//if (!command.startsWith("./")) {
//command = command.toLowerCase();
//}
//Remove all options in allPossibilities that do not match the current string
//that we are attempting to autocomplete
if (arg == "") {
for (var i = allPossibilities.length-1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(command.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
} else {
for (var i = allPossibilities.length-1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(arg.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
}
var val = "";
if (allPossibilities.length == 0) {
return;
} else if (allPossibilities.length == 1) {
if (arg == "") {
//Autocomplete command
val = allPossibilities[0] + " ";
} else {
val = command + " " + allPossibilities[0];
}
const textBox = document.getElementById("terminal-input-text-box");
const oldValue = textBox.value;
const semiColonIndex = oldValue.lastIndexOf(";");
if(semiColonIndex === -1) {
// no ; replace the whole thing.
textBox.value = val;
} else {
// replace just after the last semicolon
textBox.value = textBox.value.slice(0, semiColonIndex+1)+" "+val;
}
document.getElementById("terminal-input-text-box").focus();
} else {
var longestStartSubstr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["longestCommonStart"])(allPossibilities);
//If the longest common starting substring of remaining possibilities is the same
//as whatevers already in terminal, just list all possible options. Otherwise,
//change the input in the terminal to the longest common starting substr
var allOptionsStr = "";
for (var i = 0; i < allPossibilities.length; ++i) {
allOptionsStr += allPossibilities[i];
allOptionsStr += " ";
}
if (arg == "") {
if (longestStartSubstr == command) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("> " + command);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(allOptionsStr);
} else {
document.getElementById("terminal-input-text-box").value = longestStartSubstr;
document.getElementById("terminal-input-text-box").focus();
}
} else {
if (longestStartSubstr == arg) {
//List all possible options
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("> " + command + " " + arg);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(allOptionsStr);
} else {
document.getElementById("terminal-input-text-box").value = command + " " + longestStartSubstr;
document.getElementById("terminal-input-text-box").focus();
}
}
}
}
function determineAllPossibilitiesForTabCompletion(input, index=0) {
var allPos = [];
allPos = allPos.concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* GlobalAliases */ "b"]));
var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
input = input.toLowerCase();
//If the command starts with './' and the index == -1, then the user
//has input ./partialexecutablename so autocomplete the script or program
//Put './' in front of each script/executable
if (input.startsWith("./") && index == -1) {
//All programs and scripts
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push("./" + currServ.scripts[i].filename);
}
//Programs are on home computer
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getHomeComputer();
for(var i = 0; i < homeComputer.programs.length; ++i) {
allPos.push("./" + homeComputer.programs[i]);
}
return allPos;
}
//Autocomplete the command
if (index == -1) {
return ["alias", "analyze", "cat", "check", "clear", "cls", "connect", "download", "free",
"hack", "help", "home", "hostname", "ifconfig", "kill", "killall",
"ls", "lscpu", "mem", "nano", "ps", "rm", "run", "scan", "scan-analyze",
"scp", "sudov", "tail", "theme", "top"].concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* Aliases */ "a"])).concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* GlobalAliases */ "b"]));
}
if (input.startsWith ("buy ")) {
let options = [];
for(const i in _DarkWeb__WEBPACK_IMPORTED_MODULE_4__[/* DarkWebItems */ "a"]) {
const item = _DarkWeb__WEBPACK_IMPORTED_MODULE_4__[/* DarkWebItems */ "a"][i]
options.push(item.program);
}
return options.concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* GlobalAliases */ "b"]));
}
if (input.startsWith("scp ") && index == 1) {
for (var iphostname in _Server__WEBPACK_IMPORTED_MODULE_16__[/* AllServers */ "b"]) {
if (_Server__WEBPACK_IMPORTED_MODULE_16__[/* AllServers */ "b"].hasOwnProperty(iphostname)) {
allPos.push(_Server__WEBPACK_IMPORTED_MODULE_16__[/* AllServers */ "b"][iphostname].ip);
allPos.push(_Server__WEBPACK_IMPORTED_MODULE_16__[/* AllServers */ "b"][iphostname].hostname);
}
}
}
if (input.startsWith("scp ") && index == 0) {
//All Scripts and lit files
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"])) {
allPos.push(currServ.messages[i]);
}
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
}
if (input.startsWith("connect ") || input.startsWith("telnet ")) {
//All network connections
for (var i = 0; i < currServ.serversOnNetwork.length; ++i) {
var serv = _Server__WEBPACK_IMPORTED_MODULE_16__[/* AllServers */ "b"][currServ.serversOnNetwork[i]];
if (serv == null) {continue;}
allPos.push(serv.ip); //IP
allPos.push(serv.hostname); //Hostname
}
return allPos;
}
if (input.startsWith("kill ") || input.startsWith("tail ") ||
input.startsWith("mem ") || input.startsWith("check ")) {
//All Scripts
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
return allPos;
}
if (input.startsWith("nano ")) {
//Scripts and text files and .fconf
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
allPos.push(".fconf");
return allPos;
}
if (input.startsWith("rm ")) {
for (let i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (let i = 0; i < currServ.programs.length; ++i) {
allPos.push(currServ.programs[i]);
}
for (let i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_25__["isString"])(currServ.messages[i]) &&
currServ.messages[i].endsWith(".lit")) {
allPos.push(currServ.messages[i]);
}
}
for (let i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
for (let i = 0; i < currServ.contracts.length; ++i) {
allPos.push(currServ.contracts[i].fn);
}
return allPos;
}
if (input.startsWith("run ")) {
//All programs, scripts, and contracts
for (let i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
//Programs are on home computer
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getHomeComputer();
for (let i = 0; i < homeComputer.programs.length; ++i) {
allPos.push(homeComputer.programs[i]);
}
for (let i = 0; i < currServ.contracts.length; ++i) {
allPos.push(currServ.contracts[i].fn);
}
return allPos;
}
if (input.startsWith("cat ")) {
for (var i = 0; i < currServ.messages.length; ++i) {
if (currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) {
allPos.push(currServ.messages[i].filename);
} else {
allPos.push(currServ.messages[i]);
}
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
return allPos;
}
if (input.startsWith("download ")) {
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
}
return allPos;
}
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,
contractOpen: false, //True if a Coding Contract prompt is opened
resetTerminalInput: function() {
if (_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].WRAP_INPUT) {
document.getElementById("terminal-input-td").innerHTML =
"<div id='terminal-input-header' class='prompt'>[" + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname + " ~]" + "$ </div>" +
'<textarea type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
//Auto re-size the line element as it wraps
autosize__WEBPACK_IMPORTED_MODULE_31___default()(document.getElementById("terminal-input-text-box"));
} else {
document.getElementById("terminal-input-td").innerHTML =
"<div id='terminal-input-header' class='prompt'>[" + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname + " ~]" + "$ </div>" +
'<input type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
}
var hdr = document.getElementById("terminal-input-header");
hdr.style.display = "inline";
},
modifyInput: function(mod) {
try {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput == null) {return;}
terminalInput.focus();
var inputLength = terminalInput.value.length;
var start = terminalInput.selectionStart;
var end = terminalInput.selectionEnd;
var inputText = terminalInput.value;
switch(mod.toLowerCase()) {
case "backspace":
if (start > 0 && start <= inputLength+1) {
terminalInput.value = inputText.substr(0, start-1) + inputText.substr(start);
}
break;
case "deletewordbefore": //Delete rest of word before the cursor
for (var delStart = start-1; delStart > 0; --delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, delStart) + inputText.substr(start);
return;
}
}
break;
case "deletewordafter": //Delete rest of word after the cursor
for (var delStart = start+1; delStart <= text.length+1; ++delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, start) + inputText.substr(delStart);
return;
}
}
break;
case "clearafter": //Deletes everything after cursor
break;
case "clearbefore:": //Deleetes everything before cursor
break;
}
} catch(e) {
console.log("Exception in Terminal.modifyInput: " + e);
}
},
moveTextCursor: function(loc) {
try {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput == null) {return;}
terminalInput.focus();
var inputLength = terminalInput.value.length;
var start = terminalInput.selectionStart;
var end = terminalInput.selectionEnd;
switch(loc.toLowerCase()) {
case "home":
terminalInput.setSelectionRange(0,0);
break;
case "end":
terminalInput.setSelectionRange(inputLength, inputLength);
break;
case "prevchar":
if (start > 0) {terminalInput.setSelectionRange(start-1, start-1);}
break;
case "prevword":
for (var i = start-2; i >= 0; --i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i+1, i+1);
return;
}
}
terminalInput.setSelectionRange(0, 0);
break;
case "nextchar":
terminalInput.setSelectionRange(start+1, start+1);
break;
case "nextword":
for (var i = start+1; i <= inputLength; ++i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i, i);
return;
}
}
terminalInput.setSelectionRange(inputLength, inputLength);
break;
default:
console.log("WARNING: Invalid loc argument in Terminal.moveTextCursor()");
break;
}
} catch(e) {
console.log("Exception in Terminal.moveTextCursor: " + e);
}
},
startHack: function() {
Terminal.hackFlag = true;
//Hacking through Terminal should be faster than hacking through a script
Terminal.actionTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingTime */ "d"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer()) / 4;
Terminal.startAction();
},
startAnalyze: function() {
Terminal.analyzeFlag = true;
Terminal.actionTime = 1;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Analyzing system...");
Terminal.startAction();
},
startAction: function() {
Terminal.actionStarted = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["hackProgressPost"])("Time left:");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["hackProgressBarPost"])("[");
//Disable terminal
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
},
finishAction: function(cancelled = false) {
if (Terminal.hackFlag) {
Terminal.finishHack(cancelled);
} else if (Terminal.analyzeFlag) {
Terminal.finishAnalyze(cancelled);
}
},
//Complete the hack/analyze command
finishHack: function(cancelled = false) {
if (cancelled == false) {
var server = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
//Calculate whether hack was successful
var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingChance */ "b"])(server);
var rand = Math.random();
console.log("Hack success chance: " + hackChance + ", rand: " + rand);
var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingExpGain */ "c"])(server);
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerNames */ "b"].WorldDaemon] &&
_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerNames */ "b"].WorldDaemon] == server.ip) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].bitNodeN == null) {
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].bitNodeN = 1;
}
Object(_RedPill__WEBPACK_IMPORTED_MODULE_14__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].bitNodeN);
return;
}
server.manuallyHacked = true;
var moneyGained = Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculatePercentMoneyHacked */ "e"])(server);
moneyGained = Math.floor(server.moneyAvailable * moneyGained);
if (moneyGained <= 0) {moneyGained = 0;} //Safety check
server.moneyAvailable -= moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].gainMoney(moneyGained);
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].gainHackingExp(expGainedOnSuccess)
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].gainIntelligenceExp(expGainedOnSuccess / _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].IntelligenceTerminalHackBaseExpGain);
server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].ServerFortifyAmount);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Hack successful! Gained " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(moneyGained, '($0,0.00)') + " and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(expGainedOnSuccess, '0.0000') + " hacking EXP");
} else { //Failure
//Player only gains 25% exp for failure? TODO Can change this later to balance
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].gainHackingExp(expGainedOnFailure)
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Failed to hack " + server.hostname + ". Gained " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(expGainedOnFailure, '0.0000') + " hacking EXP");
}
}
//Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
Terminal.resetTerminalInput();
$('input[class=terminal-input]').prop('disabled', false);
Terminal.hackFlag = false;
},
finishAnalyze: function(cancelled = false) {
if (cancelled == false) {
let currServ = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(currServ.hostname + ": ");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Organization name: " + currServ.organizationName);
var rootAccess = "";
if (currServ.hasAdminRights) {rootAccess = "YES";}
else {rootAccess = "NO";}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Root Access: " + rootAccess);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Required hacking skill: " + currServ.requiredHackingSkill);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Server security level: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(currServ.hackDifficulty, '0.000a'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Chance to hack: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingChance */ "b"])(currServ), '0.00%'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Time to hack: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingTime */ "d"])(currServ), '0.000') + " seconds");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Total money available on server: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(currServ.moneyAvailable, '$0,0.00'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Required number of open ports for NUKE: " + currServ.numOpenPortsRequired);
if (currServ.sshPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SSH port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SSH port: Closed")
}
if (currServ.ftpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("FTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("FTP port: Closed")
}
if (currServ.smtpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SMTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SMTP port: Closed")
}
if (currServ.httpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("HTTP port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("HTTP port: Closed")
}
if (currServ.sqlPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SQL port: Open")
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SQL port: Closed")
}
}
Terminal.analyzeFlag = false;
//Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
Terminal.resetTerminalInput();
$('input[class=terminal-input]').prop('disabled', false);
},
executeCommand : function(command) {
command = command.trim();
//Replace all extra whitespace in command with a single space
command = command.replace(/\s\s+/g, ' ');
//Terminal history
if (Terminal.commandHistory[Terminal.commandHistory.length-1] != command) {
Terminal.commandHistory.push(command);
if (Terminal.commandHistory.length > 50) {
Terminal.commandHistory.splice(0, 1);
}
}
Terminal.commandHistoryIndex = Terminal.commandHistory.length;
//Process any aliases
command = Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* substituteAliases */ "h"])(command);
//Allow usage of ./
if (command.startsWith("./")) {
command = "run " + command.slice(2);
}
//Only split the first space
var commandArray = command.split(" ");
if (commandArray.length > 1) {
commandArray = [commandArray.shift(), commandArray.join(" ")];
}
if (commandArray.length == 0) {return;}
/****************** Interactive Tutorial Terminal Commands ******************/
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* ITutorial */ "a"].isRunning) {
var foodnstuffServ = Object(_Server__WEBPACK_IMPORTED_MODULE_16__[/* GetServerByHostname */ "c"])("foodnstuff");
if (foodnstuffServ == null) {throw new Error("Could not get foodnstuff server"); return;}
switch(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* ITutorial */ "a"].currStep) {
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalHelp:
if (commandArray[0] == "help") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(_HelpText__WEBPACK_IMPORTED_MODULE_8__["TerminalHelpText"]);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalLs:
if (commandArray[0] == "ls") {
Terminal.executeListCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalScan:
if (commandArray[0] == "scan") {
Terminal.executeScanCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalScanAnalyze1:
if (commandArray.length == 1 && commandArray[0] == "scan-analyze") {
Terminal.executeScanAnalyzeCommand(1);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalScanAnalyze2:
if (commandArray.length == 2 && commandArray[0] == "scan-analyze" &&
commandArray[1] == "2") {
Terminal.executeScanAnalyzeCommand(2);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalConnect:
if (commandArray.length == 2) {
if ((commandArray[0] == "connect") &&
(commandArray[1] == "foodnstuff" || commandArray[1] == foodnstuffServ.ip)) {
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].currentServer = foodnstuffServ.ip;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Connected to foodnstuff");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Wrong command! Try again!"); return;}
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalAnalyze:
if (commandArray[0] == "analyze") {
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of analyze command. Usage: analyze"); return;
}
Terminal.startAnalyze();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalNuke:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "NUKE.exe") {
foodnstuffServ.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("NUKE successful! Gained root access to foodnstuff");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalManualHack:
if (commandArray.length == 1 && commandArray[0] == "hack") {
Terminal.startHack();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalCreateScript:
if (commandArray.length == 2 &&
commandArray[0] == "nano" && commandArray[1] == "foodnstuff.script") {
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadScriptEditorContent("foodnstuff.script", "");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalFree:
if (commandArray.length == 1 && commandArray[0] == "free") {
Terminal.executeFreeCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].TerminalRunScript:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "foodnstuff.script") {
Terminal.runScript("foodnstuff.script");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialSteps */ "d"].ActiveScriptsToTerminal:
if (commandArray.length == 2 &&
commandArray[0] == "tail" && commandArray[1] == "foodnstuff.script") {
//Check that the script exists on this machine
var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* findRunningScript */ "d"])("foodnstuff.script", [], _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer());
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_28__[/* logBoxCreate */ "a"])(runningScript);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_9__[/* iTutorialNextStep */ "b"])();
} else {Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Bad command. Please follow the tutorial");}
break;
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Please follow the tutorial, or click 'Exit Tutorial' if you'd like to skip it");
return;
}
return;
}
/****************** END INTERACTIVE TUTORIAL ******************/
/* Command parser */
var s = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
switch (commandArray[0].toLowerCase()) {
case "alias":
if (commandArray.length == 1) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* printAliases */ "f"])();
return;
}
if (commandArray.length == 2) {
if (commandArray[1].startsWith("-g ")) {
var alias = commandArray[1].substring(3);
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* parseAliasDeclaration */ "e"])(alias, true)) {
return;
}
} else {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* parseAliasDeclaration */ "e"])(commandArray[1])) {
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]');
break;
case "analyze":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of analyze command. Usage: analyze"); return;
}
Terminal.startAnalyze();
break;
case "buy":
if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerIps */ "a"].hasOwnProperty("Darkweb Server")) {
Object(_DarkWeb__WEBPACK_IMPORTED_MODULE_4__[/* executeDarkwebTerminalCommand */ "c"])(commandArray);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You need to be able to connect to the Dark Web to use the buy command. (Maybe there's a TOR router you can buy somewhere)");
}
break;
case "cat":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of cat command. Usage: cat [file]"); return;
}
var filename = commandArray[1];
if (!filename.endsWith(".msg") && !filename.endsWith(".lit") && !filename.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: Only .msg, .txt, and .lit files are viewable with cat (filename must end with .msg, .txt, or .lit)"); return;
}
for (var i = 0; i < s.messages.length; ++i) {
if (filename.endsWith(".lit") && s.messages[i] == filename) {
Object(_Literature__WEBPACK_IMPORTED_MODULE_10__[/* showLiterature */ "b"])(s.messages[i]);
return;
} else if (filename.endsWith(".msg") && s.messages[i].filename == filename) {
Object(_Message__WEBPACK_IMPORTED_MODULE_11__[/* showMessage */ "f"])(s.messages[i]);
return;
}
}
for (var i = 0; i < s.textFiles.length; ++i) {
if (s.textFiles[i].fn === filename) {
s.textFiles[i].show();
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No such file " + filename);
break;
case "check":
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...");
} else {
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
//Can only tail script files
if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(scriptName) == false) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: tail can only be called on .script files (filename must end with .script)"); return;
}
//Check that the script exists on this machine
var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* findRunningScript */ "d"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No such script exists");
return;
}
runningScript.displayLog();
}
break;
case "clear":
case "cls":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of clear/cls command. Usage: clear/cls"); return;
}
$("#terminal tr:not(:last)").remove();
postNetburnerText();
break;
case "connect":
//Disconnect from current server in terminal and connect to new one
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of connect command. Usage: connect [ip/hostname]");
return;
}
var ip = commandArray[1];
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().serversOnNetwork.length; i++) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i).ip == ip || _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i).hostname == ip) {
Terminal.connectToServer(ip);
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Host not found");
break;
case "download":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of download command. Usage: download [text file]");
return;
}
var fn = commandArray[1];
if (fn === "*" || fn === "*.script" || fn === "*.txt") {
//Download all scripts as a zip
var zip = new jszip__WEBPACK_IMPORTED_MODULE_32__();
if (fn === "*" || fn === "*.script") {
for (var i = 0; i < s.scripts.length; ++i) {
var file = new Blob([s.scripts[i].code], {type:"text/plain"});
zip.file(s.scripts[i].filename + ".js", file);
}
}
if (fn === "*" || fn === "*.txt") {
for (var i = 0; i < s.textFiles.length; ++i) {
var file = new Blob([s.textFiles[i].text], {type:"text/plain"});
zip.file(s.textFiles[i].fn, file);
}
}
var filename;
switch (fn) {
case "*.script":
filename = "bitburnerScripts.zip"; break;
case "*.txt":
filename = "bitburnerTexts.zip"; break;
default:
filename = "bitburnerFiles.zip"; break;
}
zip.generateAsync({type:"blob"}).then(function(content) {
file_saver__WEBPACK_IMPORTED_MODULE_33__["saveAs"](content, filename);
});
return;
} else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(fn)) {
//Download a single script
for (var i = 0; i < s.scripts.length; ++i) {
if (s.scripts[i].filename === fn) {
return s.scripts[i].download();
}
}
} else if (fn.endsWith(".txt")) {
//Download a single text file
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_19__["getTextFile"])(fn, s);
if (txtFile !== null) {
return txtFile.download();
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: " + fn + " does not exist");
break;
case "expr":
if (commandArray.length <= 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of expr command. Usage: expr [math expression]");
return;
}
const expr = commandArray.slice(1).join("");
// Sanitize the math expression
const sanitizedExpr = expr.replace(/s+/g, '').replace(/[^-()\d/*+.]/g, '');
let result;
try {
result = eval(sanitizedExpr);
} catch(e) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`Could not evaluate expression: ${sanitizedExpr}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(result);
break;
case "free":
Terminal.executeFreeCommand(commandArray);
break;
case "hack":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of hack command. Usage: hack"); return;
}
//Hack the current PC (usually for money)
//You can't hack your home pc or servers you purchased
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().purchasedByPlayer) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hasAdminRights == false ) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You do not have admin rights for this machine! Cannot hack");
} else if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hacking_skill) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else {
Terminal.startHack();
}
break;
case "help":
if (commandArray.length != 1 && commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of help command. Usage: help"); return;
}
if (commandArray.length == 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(_HelpText__WEBPACK_IMPORTED_MODULE_8__["TerminalHelpText"]);
} else {
var cmd = commandArray[1];
var txt = _HelpText__WEBPACK_IMPORTED_MODULE_8__["HelpTexts"][cmd];
if (txt == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No help topics match '" + cmd + "'");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(txt);
}
break;
case "home":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of home command. Usage: home"); return;
}
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].currentServer = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getHomeComputer().ip;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Connected to home");
Terminal.resetTerminalInput();
break;
case "hostname":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of hostname command. Usage: hostname"); return;
}
//Print the hostname of current system
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname);
break;
case "ifconfig":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of ifconfig command. Usage: ifconfig"); return;
}
//Print the IP address of the current system
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().ip);
break;
case "kill":
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]..."); return;
}
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* findRunningScript */ "d"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("No such script is running. Nothing to kill");
return;
}
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_12__[/* killWorkerScript */ "d"])(runningScript, s.ip);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Killing " + scriptName + ". May take up to a few minutes for the scripts to die...");
break;
case "killall":
for (var i = s.runningScripts.length-1; i >= 0; --i) {
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_12__[/* killWorkerScript */ "d"])(s.runningScripts[i], s.ip);
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Killing all running scripts. May take up to a few minutes for the scripts to die...");
break;
case "ls":
Terminal.executeListCommand(commandArray);
break;
case "lscpu":
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().cpuCores + " Core(s)");
break;
case "mem":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]"); return;
}
var scriptName = commandArray[1];
var numThreads = 1;
if (scriptName.indexOf(" -t ") != -1) {
var results = scriptName.split(" ");
if (results.length != 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid use of run command. Usage: mem [script] [-t] [number threads]");
return;
}
numThreads = Math.round(Number(results[2]));
if (isNaN(numThreads) || numThreads < 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid number of threads specified. Number of threads must be greater than 1");
return;
}
scriptName = results[0];
}
var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
for (var i = 0; i < currServ.scripts.length; ++i) {
if (scriptName == currServ.scripts[i].filename) {
var scriptBaseRamUsage = currServ.scripts[i].ramUsage;
var ramUsage = scriptBaseRamUsage * numThreads;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This script requires " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(ramUsage, '0.00') + " GB of RAM to run for " + numThreads + " thread(s)");
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERR: No such script exists!");
break;
case "nano":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of nano command. Usage: nano [scriptname]"); return;
}
var filename = commandArray[1];
if (filename === ".fconf") {
var text = Object(_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* createFconf */ "b"])();
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadScriptEditorContent(filename, text);
return;
} else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(filename)) {
for (var i = 0; i < s.scripts.length; i++) {
if (filename == s.scripts[i].filename) {
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadScriptEditorContent(filename, s.scripts[i].code);
return;
}
}
} else if (filename.endsWith(".txt")) {
for (var i = 0; i < s.textFiles.length; ++i) {
if (filename === s.textFiles[i].fn) {
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadScriptEditorContent(filename, s.textFiles[i].text);
return;
}
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: Invalid file. Only scripts (.script, .ns, .js), text files (.txt), or .fconf can be edited with nano"); return;
}
_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadScriptEditorContent(filename);
break;
case "ps":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of ps command. Usage: ps"); return;
}
for (var i = 0; i < s.runningScripts.length; i++) {
var rsObj = s.runningScripts[i];
var res = rsObj.filename;
for (var j = 0; j < rsObj.args.length; ++j) {
res += (" " + rsObj.args[j].toString());
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(res);
}
break;
case "rm":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments. Usage: rm [program/script]"); return;
}
//Check programs
var delTarget = commandArray[1];
if (delTarget.includes(".exe")) {
for (var i = 0; i < s.programs.length; ++i) {
if (s.programs[i] == delTarget) {
s.programs.splice(i, 1);
return;
}
}
} else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(delTarget)) {
for (var i = 0; i < s.scripts.length; ++i) {
if (s.scripts[i].filename == delTarget) {
//Check that the script isnt currently running
for (var j = 0; j < s.runningScripts.length; ++j) {
if (s.runningScripts[j].filename == delTarget) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Cannot delete a script that is currently running!");
return;
}
}
s.scripts.splice(i, 1);
return;
}
}
} else if (delTarget.endsWith(".lit")) {
for (var i = 0; i < s.messages.length; ++i) {
var f = s.messages[i];
if (!(f instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_25__["isString"])(f) && f === delTarget) {
s.messages.splice(i, 1);
return;
}
}
} else if (delTarget.endsWith(".txt")) {
for (var i = 0; i < s.textFiles.length; ++i) {
if (s.textFiles[i].fn === delTarget) {
s.textFiles.splice(i, 1);
return;
}
}
} else if (delTarget.endsWith(".cct")) {
for (var i = 0; i < s.contracts.length; ++i) {
if (s.contracts[i].fn === delTarget) {
s.contracts.splice(i, 1);
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No such file exists");
break;
case "run":
//Run a program or a script
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]...");
} else {
var executableName = commandArray[1];
//Secret Music player!
if (executableName === "musicplayer") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])('<iframe src="https://open.spotify.com/embed/user/danielyxie/playlist/1ORnnL6YNvXOracUaUV2kh" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>', false);
return;
}
//Check if its a script or just a program/executable
//Dont use isScriptFilename here because `executableName` includes the args too
if (executableName.includes(".script") || executableName.includes(".js") || executableName.includes(".ns")) {
Terminal.runScript(executableName);
} else if (executableName.endsWith(".cct")) {
Terminal.runContract(executableName);
} else {
Terminal.runProgram(executableName);
}
}
break;
case "scan":
Terminal.executeScanCommand(commandArray);
break;
case "scan-analyze":
if (commandArray.length == 1) {
Terminal.executeScanAnalyzeCommand(1);
} else if (commandArray.length == 2) {
var all = false;
if (commandArray[1].endsWith("-a")) {
all = true;
commandArray[1] = commandArray[1].replace("-a", "");
}
var depth;
if (commandArray[1].length === 0) {
depth = 1;
} else {
depth = Number(commandArray[1]);
}
if (isNaN(depth) || depth < 0) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of scan-analyze command. depth argument must be positive numeric");
return;
}
if (depth > 3 && !_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].DeepscanV1.name) &&
!_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You cannot scan-analyze with that high of a depth. Maximum depth is 3");
return;
} else if (depth > 5 && !_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You cannot scan-analyze with that high of a depth. Maximum depth is 5");
return;
} else if (depth > 10) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You cannot scan-analyze with that high of a depth. Maximum depth is 10");
return;
}
Terminal.executeScanAnalyzeCommand(depth, all);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]");
}
break;
/* eslint-disable no-case-declarations */
case "scp":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
var args = commandArray[1].split(" ");
if (args.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
var scriptname = args[0];
if (!scriptname.endsWith(".lit") && !Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(scriptname) &&
!scriptname.endsWith(".txt")){
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: scp only works for .script, .txt, and .lit files");
return;
}
var destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_16__[/* getServer */ "e"])(args[1]);
if (destServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid destination. " + args[1] + " not found");
return;
}
var ip = destServer.ip;
var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
//Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) && currServ.messages[i] == scriptname) {
found = true;
break;
}
}
if (!found) {return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: no such file exists!");}
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(scriptname + " copied over to " + destServer.hostname);
return; //Already exists
}
}
destServer.messages.push(scriptname);
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(scriptname + " copied over to " + destServer.hostname);
}
//Scp for txt files
if (scriptname.endsWith(".txt")) {
var found = false, txtFile;
for (var i = 0; i < currServ.textFiles.length; ++i) {
if (currServ.textFiles[i].fn === scriptname) {
found = true;
txtFile = currServ.textFiles[i];
break;
}
}
if (!found) {return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: no such file exists!");}
let tRes = destServer.writeToTextFile(txtFile.fn, txtFile.text);
if (!tRes.success) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: scp failed");
}
if (tRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwriten`);
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
}
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
}
//Get the current script
var sourceScript = null;
for (var i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
sourceScript = currServ.scripts[i];
break;
}
}
if (sourceScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: scp() failed. No such script exists");
return;
}
let sRes = destServer.writeToScriptFile(scriptname, sourceScript.code);
if (!sRes.success) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`Error: scp failed`);
}
if (sRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwritten`);
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
break;
/* eslint-enable no-case-declarations */
case "sudov":
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments. Usage: sudov"); return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You have ROOT access to this machine");
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You do NOT have root access to this machine");
}
break;
case "tail":
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]...");
} else {
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
//Can only tail script files
if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(scriptName) == false) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: tail can only be called on .script files (filename must end with .script)"); return;
}
//Check that the script exists on this machine
var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* findRunningScript */ "d"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Error: No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_28__[/* logBoxCreate */ "a"])(runningScript);
}
break;
case "theme":
//todo support theme saving
var args = commandArray[1] ? commandArray[1].split(" ") : [];
if (args.length != 1 && args.length != 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect number of arguments.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Usage: theme [default|muted|solarized] | #[background color hex] #[text color hex] #[highlight color hex]");
} else if(args.length == 1){
var themeName = args[0];
if (themeName == "default"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#000000");
document.body.style.setProperty('--my-prompt-color', "#f92672");
} else if (themeName == "muted"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#252527");
} else if (themeName == "solarized"){
document.body.style.setProperty('--my-highlight-color',"#6c71c4");
document.body.style.setProperty('--my-font-color',"#839496");
document.body.style.setProperty('--my-background-color',"#002b36");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Theme not found");
}
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_PROMPT_COLOR = document.body.style.getPropertyValue("--my-prompt-color");
} else {
var inputBackgroundHex = args[0];
var inputTextHex = args[1];
var inputHighlightHex = args[2];
if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputBackgroundHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputTextHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputHighlightHex)){
document.body.style.setProperty('--my-highlight-color',inputHighlightHex);
document.body.style.setProperty('--my-font-color',inputTextHex);
document.body.style.setProperty('--my-background-color',inputBackgroundHex);
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf__WEBPACK_IMPORTED_MODULE_6__[/* FconfSettings */ "a"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid Hex Input for theme");
}
}
break;
case "top":
if(commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of top command. Usage: top"); return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Script Threads RAM Usage");
var currRunningScripts = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().runningScripts;
//Iterate through scripts on current server
for(var i = 0; i < currRunningScripts.length; i++) {
var script = currRunningScripts[i];
//Calculate name padding
var numSpacesScript = 32 - script.filename.length; //26 -> width of name column
if (numSpacesScript < 0) {numSpacesScript = 0;}
var spacesScript = Array(numSpacesScript+1).join(" ");
//Calculate thread padding
var numSpacesThread = 16 - (script.threads + "").length; //16 -> width of thread column
var spacesThread = Array(numSpacesThread+1).join(" ");
//Calculate and transform RAM usage
ramUsage = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(script.scriptRef.ramUsage * script.threads, '0.00') + " GB";
var entry = [script.filename, spacesScript, script.threads, spacesThread, ramUsage];
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(entry.join(""));
}
break;
case "unalias":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])('Incorrect usage of unalias name. Usage: unalias "[alias]"');
return;
} else if (!(commandArray[1].startsWith('"') && commandArray[1].endsWith('"'))) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])('Incorrect usage of unalias name. Usage: unalias "[alias]"');
} else {
var alias = commandArray[1].slice(1, -1);
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* removeAlias */ "g"])(alias)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Removed alias " + alias);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("No such alias exists");
}
}
break;
/* eslint-disable no-case-declarations */
case "wget":
if (commandArray.length !== 2) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of wget command. Usage: wget [url] [target file]");
}
var args = commandArray[1].split(" ");
if (args.length !== 2) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of wget command. Usage: wget [url] [target file]");
}
let url = args[0];
let target = args[1];
if (!Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(target) && !target.endsWith(".txt")) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`wget failed: Invalid target file. Target file must be script or text file`);
}
$.get(url, function(data) {
let res;
if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* isScriptFilename */ "e"])(target)) {
res = s.writeToScriptFile(target, data);
} else {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("wget failed");
}
if (res.overwritten) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`wget successfully retrieved content and overwrote ${target}`);
}
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`wget successfully retrieved content to new file ${target}`);
}, 'text').fail(function(e) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("wget failed: " + JSON.stringify(e));
})
break;
/* eslint-enable no-case-declarations */
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Command not found");
}
},
connectToServer: function(ip) {
console.log("Connect to server called");
var serv = Object(_Server__WEBPACK_IMPORTED_MODULE_16__[/* getServer */ "e"])(ip);
if (serv == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid server. Connection failed.");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].currentServer = serv.ip;
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Connected to " + serv.hostname);
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname == "darkweb") {
Object(_DarkWeb__WEBPACK_IMPORTED_MODULE_4__[/* checkIfConnectedToDarkweb */ "b"])(); //Posts a 'help' message if connecting to dark web
}
Terminal.resetTerminalInput();
},
executeListCommand: function(commandArray) {
if (commandArray.length != 1 && commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return;
}
//grep
var filter = null;
if (commandArray.length == 2) {
if (commandArray[1].startsWith("| grep ")) {
var pattern = commandArray[1].replace("| grep ", "");
if (pattern != " ") {
filter = pattern;
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return;
}
}
//Display all programs and scripts
var allFiles = [];
//Get all of the programs and scripts on the machine into one temporary array
var s = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
for (var i = 0; i < s.programs.length; i++) {
if (filter) {
if (s.programs[i].includes(filter)) {
allFiles.push(s.programs[i]);
}
} else {
allFiles.push(s.programs[i]);
}
}
for (var i = 0; i < s.scripts.length; i++) {
if (filter) {
if (s.scripts[i].filename.includes(filter)) {
allFiles.push(s.scripts[i].filename);
}
} else {
allFiles.push(s.scripts[i].filename);
}
}
for (var i = 0; i < s.messages.length; i++) {
if (filter) {
if (s.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) {
if (s.messages[i].filename.includes(filter)) {
allFiles.push(s.messages[i].filename);
}
} else if (s.messages[i].includes(filter)) {
allFiles.push(s.messages[i]);
}
} else {
if (s.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_11__[/* Message */ "a"]) {
allFiles.push(s.messages[i].filename);
} else {
allFiles.push(s.messages[i]);
}
}
}
for (var i = 0; i < s.textFiles.length; ++i) {
if (filter) {
if (s.textFiles[i].fn.includes(filter)) {
allFiles.push(s.textFiles[i].fn);
}
} else {
allFiles.push(s.textFiles[i].fn);
}
}
for (var i = 0; i < s.contracts.length; ++i) {
if (filter) {
if (s.contracts[i].fn.includes(filter)) {
allFiles.push(s.contracts[i].fn);
}
} else {
allFiles.push(s.contracts[i].fn);
}
}
//Sort the files alphabetically then print each
allFiles.sort();
for (var i = 0; i < allFiles.length; i++) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(allFiles[i]);
}
},
executeScanCommand: function(commandArray) {
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of netstat/scan command. Usage: netstat/scan"); return;
}
//Displays available network connections using TCP
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Hostname IP Root Access");
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().serversOnNetwork.length; i++) {
//Add hostname
var entry = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i);
if (entry == null) {continue;}
entry = entry.hostname;
//Calculate padding and add IP
var numSpaces = 21 - entry.length;
var spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i).ip;
//Calculate padding and add root access info
var hasRoot;
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i).hasAdminRights) {
hasRoot = 'Y';
} else {
hasRoot = 'N';
}
numSpaces = 21 - _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().getServerOnNetwork(i).ip.length;
spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += hasRoot;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(entry);
}
},
executeScanAnalyzeCommand: function(depth=1, all=false) {
//We'll use the AllServersMap as a visited() array
//TODO Using array as stack for now, can make more efficient
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(" ");
var visited = new _Script__WEBPACK_IMPORTED_MODULE_15__[/* AllServersMap */ "a"]();
var stack = [];
var depthQueue = [0];
var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
stack.push(currServ);
while(stack.length != 0) {
var s = stack.pop();
var d = depthQueue.pop();
if (!all && s.purchasedByPlayer && s.hostname != "home") {
continue; //Purchased server
} else if (visited[s.ip] || d > depth) {
continue; //Already visited or out-of-depth
} else {
visited[s.ip] = 1;
}
for (var i = s.serversOnNetwork.length-1; i >= 0; --i) {
stack.push(s.getServerOnNetwork(i));
depthQueue.push(d+1);
}
if (d == 0) {continue;} //Don't print current server
var titleDashes = Array((d-1) * 4 + 1).join("-");
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].AutoLink.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("<strong>" + titleDashes + "> <a class='scan-analyze-link'>" + s.hostname + "</a></strong>", false);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("<strong>" + titleDashes + ">" + s.hostname + "</strong>");
}
var dashes = titleDashes + "--";
//var dashes = Array(d * 2 + 1).join("-");
var c = "NO";
if (s.hasAdminRights) {c = "YES";}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(dashes + "Root Access: " + c + ", Required hacking skill: " + s.requiredHackingSkill);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(dashes + "Number of open ports required to NUKE: " + s.numOpenPortsRequired);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(dashes + "RAM: " + s.maxRam);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(" ");
}
var links = document.getElementsByClassName("scan-analyze-link");
for (var i = 0; i < links.length; ++i) {
(function() {
var hostname = links[i].innerHTML.toString();
links[i].onclick = function() {
if (Terminal.analyzeFlag || Terminal.hackFlag) {return;}
Terminal.connectToServer(hostname);
}
}());//Immediate invocation
}
},
executeFreeCommand: function(commandArray) {
if (commandArray.length != 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Incorrect usage of free command. Usage: free"); return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Total: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().maxRam, '0.00') + " GB");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Used: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().ramUsed, '0.00') + " GB");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Available: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().maxRam - _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().ramUsed, '0.00') + " GB");
},
//First called when the "run [program]" command is called. Checks to see if you
//have the executable and, if you do, calls the executeProgram() function
runProgram: function(programName) {
//Check if you have the program on your computer. If you do, execute it, otherwise
//display an error message
var splitArgs = programName.split(" ");
var name = " ";
if (splitArgs.length > 1) {
name = splitArgs[0];
} else {
name = programName;
}
if (_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hasProgram(name)) {
Terminal.executeProgram(programName);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)");
},
//Contains the implementations of all possible programs
executeProgram: function(programName) {
var s = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
var splitArgs = programName.split(" ");
if (splitArgs.length > 1) {
programName = splitArgs[0];
}
// TODO: refactor this/these out of Terminal. This logic could reside closer to the Programs themselves.
/**
* @typedef {function (server=, args=)} ProgramHandler
* @param {Server} server The current server the program is being executed against
* @param {string[]} args The command line arguments passed in to the program
* @returns {void}
*/
/**
* @type {Object.<string, ProgramHandler}
*/
const programHandlers = {};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].NukeProgram.name] = (server) => {
if (server.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("You already have root access to this computer. There is no reason to run NUKE.exe");
return;
}
if (server.openPortCount >= _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().numOpenPortsRequired) {
server.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("NUKE successful! Gained root access to " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer().hostname);
// TODO: Make this take time rather than be instant
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("NUKE unsuccessful. Not enough ports have been opened");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].BruteSSHProgram.name] = (server) => {
if (server.sshPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SSH Port (22) is already open!");
return;
}
server.sshPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Opened SSH Port(22)!")
server.openPortCount++;
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].FTPCrackProgram.name] = (server) => {
if (server.ftpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("FTP Port (21) is already open!");
return;
}
server.ftpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Opened FTP Port (21)!");
server.openPortCount++;
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].RelaySMTPProgram.name] = (server) => {
if (server.smtpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SMTP Port (25) is already open!");
return;
}
server.smtpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Opened SMTP Port (25)!");
server.openPortCount++;
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].HTTPWormProgram.name] = (server) => {
if (server.httpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("HTTP Port (80) is already open!");
return;
}
server.httpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Opened HTTP Port (80)!");
server.openPortCount++;
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].SQLInjectProgram.name] = (server) => {
if (server.sqlPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("SQL Port (1433) is already open!");
return;
}
server.sqlPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Opened SQL Port (1433)!");
server.openPortCount++;
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].ServerProfiler.name] = (server, args) => {
if (args.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Must pass a server hostname or IP as an argument for ServerProfiler.exe");
return;
}
const targetServer = Object(_Server__WEBPACK_IMPORTED_MODULE_16__[/* getServer */ "e"])(args[1]);
if (targetServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid server IP/hostname");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(targetServer.hostname + ":");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Server base security level: " + targetServer.baseDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Server current security level: " + targetServer.hackDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Server growth rate: " + targetServer.serverGrowth);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Netscript hack() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateHackingTime */ "d"])(targetServer), '0.0') + "s");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Netscript grow() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateGrowTime */ "a"])(targetServer), '0.0') + "s");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Netscript weaken() execution time: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(Object(_Hacking__WEBPACK_IMPORTED_MODULE_7__[/* calculateWeakenTime */ "f"])(targetServer), '0.0') + "s");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].AutoLink.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("When using scan-analyze, click on a server's hostname to connect to it.");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].DeepscanV1.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5.");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].DeepscanV2.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10.");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].Flight.name] = () => {
const fulfilled = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].augmentations.length >= 30 &&
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].money.gt(1e11) &&
((_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hacking_skill >= 2500)||
(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].strength >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].defense >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].dexterity >= 1500 &&
_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].agility >= 1500));
if(!fulfilled) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Augmentations: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].augmentations.length + " / 30");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Money: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].money.toNumber(), '($0.000a)') + " / " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_22__[/* numeralWrapper */ "a"].format(1e11, '($0.000a)'));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("One path below must be fulfilled...");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("----------HACKING PATH----------");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Hacking skill: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].hacking_skill + " / 2500");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("----------COMBAT PATH----------");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Strength: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].strength + " / 1500");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Defense: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].defense + " / 1500");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Dexterity: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].dexterity + " / 1500");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Agility: " + _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].agility + " / 1500");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("We will contact you.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("-- Daedalus --");
};
programHandlers[_CreateProgram__WEBPACK_IMPORTED_MODULE_3__[/* Programs */ "a"].BitFlume.name] = () => {
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__[/* yesNoBoxGetYesButton */ "d"])();
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Travel to BitNode Nexus";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_14__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].bitNodeN, true);
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__[/* yesNoBoxClose */ "a"])();
});
noBtn.addEventListener("click", function() {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__[/* yesNoBoxClose */ "a"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_29__[/* yesNoBoxCreate */ "b"])("WARNING: USING THIS PROGRAM WILL CAUSE YOU TO LOSE ALL OF YOUR PROGRESS ON THE CURRENT BITNODE.<br><br>" +
"Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " +
"and select a new one.");
};
if (!programHandlers.hasOwnProperty(programName)){
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid executable. Cannot be run");
return;
}
programHandlers[programName](s, splitArgs);
},
runScript: function(scriptName) {
var server = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
var numThreads = 1;
var args = [];
var results = scriptName.split(" ");
if (results.length <= 0) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This is a bug. Please contact developer");
}
scriptName = results[0];
if (results.length > 1) {
if (results.length >= 3 && results[1] == "-t") {
numThreads = Math.round(Number(results[2]));
if (isNaN(numThreads) || numThreads < 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Invalid number of threads specified. Number of threads must be greater than 0");
return;
}
for (var i = 3; i < results.length; ++i) {
var arg = results[i];
//Forced string
if ((arg.startsWith("'") && arg.endsWith("'")) ||
(arg.startsWith('"') && arg.endsWith('"'))) {
args.push(arg.slice(1, -1));
continue;
}
//Number
var tempNum = Number(arg);
if (!isNaN(tempNum)) {
args.push(tempNum);
continue;
}
//Otherwise string
args.push(arg);
}
} else {
for (var i = 1; i < results.length; ++i) {
var arg = results[i];
//Forced string
if ((arg.startsWith("'") && arg.endsWith("'")) ||
(arg.startsWith('"') && arg.endsWith('"'))) {
args.push(arg.slice(1, -1));
continue;
}
//Number
var tempNum = Number(arg);
if (!isNaN(tempNum)) {
args.push(tempNum);
continue;
}
//Otherwise string
args.push(arg);
}
}
}
//Check if this script is already running
if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__[/* findRunningScript */ "d"])(scriptName, args, server) != null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: This script is already running. Cannot run multiple instances");
return;
}
//Check if the script exists and if it does run it
for (var i = 0; i < server.scripts.length; i++) {
if (server.scripts[i].filename == scriptName) {
//Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage * numThreads;
var ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Need root access to run script");
return;
} else if (ramUsage > ramAvailable){
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("This machine does not have enough RAM to run this script with " +
numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
return;
} else {
//Able to run script
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Running script with " + numThreads + " thread(s) and args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_26__["arrayToString"])(args) + ".");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("May take a few seconds to start up the process...");
var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_15__[/* RunningScript */ "b"](script, args);
runningScriptObj.threads = numThreads;
server.runningScripts.push(runningScriptObj);
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_12__[/* addWorkerScript */ "c"])(runningScriptObj, server);
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: No such script");
},
runContract: async function(contractName) {
// There's already an opened contract
if (Terminal.contractOpen) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: There's already a Coding Contract in Progress");
}
const serv = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].getCurrentServer();
const contract = serv.getContract(contractName);
if (contract == null) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("ERROR: No such contract");
}
Terminal.contractOpen = true;
const res = await contract.prompt();
switch (res) {
case _CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContractResult"].Success:
var reward = _Player__WEBPACK_IMPORTED_MODULE_13__[/* Player */ "a"].gainCodingContractReward(contract.reward, contract.getDifficulty());
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`Contract SUCCESS - ${reward}`);
serv.removeContract(contract);
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContractResult"].Failure:
++contract.tries;
if (contract.tries >= contract.getMaxNumTries()) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Contract <p style='color:red;display:inline'>FAILED</p> - Contract is now self-destructing");
serv.removeContract(contract);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])(`Contract <p style='color:red;display:inline'>FAILED</p> - ${contract.getMaxNumTries() - contract.tries} tries remaining`);
}
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContractResult"].Cancelled:
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_30__["post"])("Contract cancelled");
break;
}
Terminal.contractOpen = false;
console.log(Terminal.contractOpen);
},
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 50 */
/*!*************************************!*\
!*** ./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 */ 29);
/* 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. This is either" +
" because you are not currently employed at the Bladeburner division" +
" or because you do not have Source-File 7";
const hasAccess = _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_1__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bitNodeN === 7 || _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].sourceFiles.some(a=>{return a.n === 7}));
if(!hasAccess) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_2__[/* makeRuntimeRejectMsg */ "d"])(workerScript, accessDenied);
}
}
/***/ }),
/* 51 */
/*!*******************************************!*\
!*** ./utils/uiHelpers/getElementById.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns a reference to the first object with the specified value of the ID or NAME attribute,
* throwing an error if it is unable to find it.
* @param elementId The HTML ID to retrieve the element by.
* @throws {Error} When the 'elementId' cannot be found.
*/
function getElementById(elementId) {
const el = document.getElementById(elementId);
if (el === null) {
throw new Error(`Unable to find element with id '${elementId}'`);
}
return el;
}
exports.getElementById = getElementById;
/***/ }),
/* 52 */
/*!****************************************!*\
!*** ./utils/helpers/arrayToString.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: arrayToString */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns the input array as a comma separated string.
*/
function arrayToString(a) {
return `[${a.join(", ")}]`;
}
exports.arrayToString = arrayToString;
/***/ }),
/* 53 */
/*!*************************!*\
!*** ./src/Missions.js ***!
\*************************/
/*! exports provided: HackingMission, inMission, setInMission, currMission */
/*! exports used: HackingMission, currMission, inMission, setInMission */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HackingMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return inMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return setInMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return currMission; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* 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_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 61);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jsplumb */ 228);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_10__);
let inMission = false; //Flag to denote whether a mission is running
let currMission = null;
function setInMission(bool, mission) {
inMission = bool;
if (bool) {
currMission = mission;
} else {
currMission = null;
}
}
//Keyboard shortcuts
$(document).keydown(function(e) {
if (inMission && currMission && currMission.selectedNode.length != 0) {
switch (e.keyCode) {
case 65: //a for Attack
currMission.actionButtons[0].click();
break;
case 83: //s for Scan
currMission.actionButtons[1].click();
break;
case 87: //w for Weaken
currMission.actionButtons[2].click();
break;
case 70: //f for Fortify
currMission.actionButtons[3].click();
break;
case 82: //r for Overflow
currMission.actionButtons[4].click();
break;
case 68: //d for Detach connection
currMission.actionButtons[5].click();
break;
default:
break;
}
}
});
let NodeTypes = {
Core: "CPU Core Node", //All actions available
Firewall: "Firewall Node", //No actions available
Database: "Database Node", //No actions available
Spam: "Spam Node", //No actions Available
Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow
Shield: "Shield Node" //Can Fortify
}
let NodeActions = {
Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def
Scan: "Scanning", //-Def for target, affected by attack and hacking level
Weaken: "Weakening", //-Attack for target, affected by attack and hacking level
Fortify: "Fortifying", //+Defense for Node, affected by hacking level
Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level
}
function Node(type, stats) {
this.type = type;
this.atk = stats.atk ? stats.atk : 0;
this.def = stats.def ? stats.def : 0;
this.hp = stats.hp ? stats.hp : 0;
this.maxhp = this.hp;
this.plyrCtrl = false;
this.enmyCtrl = false;
this.pos = [0, 0]; //x, y
this.el = null; //Holds the Node's DOM element
this.action = null;
this.targetedCount = 0; //Count of how many connections this node is the target of
//Holds the JsPlumb Connection object for this Node,
//where this Node is the Source (since each Node
//can only have 1 outgoing Connection)
this.conn = null;
}
Node.prototype.setPosition = function(x, y) {
this.pos = [x, y];
}
Node.prototype.setControlledByPlayer = function() {
this.plyrCtrl = true;
this.enmyCtrl = false;
if (this.el) {
this.el.classList.remove("hack-mission-enemy-node");
this.el.classList.add("hack-mission-player-node");
}
}
Node.prototype.setControlledByEnemy = function() {
this.plyrCtrl = false;
this.enmyCtrl = true;
if (this.el) {
this.el.classList.remove("hack-mission-player-node");
this.el.classList.add("hack-mission-enemy-node");
}
}
//Sets this node to be the active node
Node.prototype.select = function(actionButtons) {
if (this.enmyCtrl) {return;}
this.el.classList.add("hack-mission-player-node-active");
//Make all buttons inactive
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button");
actionButtons[i].classList.add("a-link-button-inactive");
}
switch(this.type) {
case NodeTypes.Core:
//All buttons active
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button-inactive");
actionButtons[i].classList.add("a-link-button");
}
break;
case NodeTypes.Transfer:
actionButtons[1].classList.remove("a-link-button-inactive");
actionButtons[1].classList.add("a-link-button");
actionButtons[2].classList.remove("a-link-button-inactive");
actionButtons[2].classList.add("a-link-button");
actionButtons[3].classList.remove("a-link-button-inactive");
actionButtons[3].classList.add("a-link-button");
actionButtons[4].classList.remove("a-link-button-inactive");
actionButtons[4].classList.add("a-link-button");
actionButtons[5].classList.remove("a-link-button-inactive");
actionButtons[5].classList.add("a-link-button");
break;
case NodeTypes.Shield:
case NodeTypes.Firewall:
actionButtons[3].classList.remove("a-link-button-inactive");
actionButtons[3].classList.add("a-link-button");
break;
default:
break;
}
}
Node.prototype.deselect = function(actionButtons) {
this.el.classList.remove("hack-mission-player-node-active");
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button");
actionButtons[i].classList.add("a-link-button-inactive");
}
}
Node.prototype.untarget = function() {
if (this.targetedCount === 0) {
console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count");
return;
}
--this.targetedCount;
}
//Hacking mission instance
//Takes in the reputation of the Faction for which the mission is
//being conducted
function HackingMission(rep, fac) {
this.faction = fac;
this.started = false;
this.time = 180000; //5 minutes to start, milliseconds
this.playerCores = [];
this.playerNodes = []; //Non-core nodes
this.playerAtk = 0;
this.playerDef = 0;
this.enemyCores = [];
this.enemyDatabases = [];
this.enemyNodes = []; //Non-core nodes
this.enemyAtk = 0;
this.enemyDef = 0;
this.miscNodes = [];
this.selectedNode = []; //Which of the player's nodes are currently selected
this.actionButtons = []; //DOM buttons for actions
this.availablePositions = [];
for (var r = 0; r < 8; ++r) {
for (var c = 0; c < 8; ++c) {
this.availablePositions.push([r, c]);
}
}
this.map = [];
for (var i = 0; i < 8; ++i) {
this.map.push([null, null, null, null, null, null, null, null]);
}
this.jsplumbinstance = null;
this.difficulty = rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1;
console.log("difficulty: " + this.difficulty);
this.reward = 250 + (rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion);
}
HackingMission.prototype.init = function() {
//Create Header DOM
this.createPageDom();
//Create player starting nodes
var home = _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].getHomeComputer()
for (var i = 0; i < home.cpuCores; ++i) {
var stats = {
atk: (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill / 7.5) + 30,
def: (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill / 20),
hp: (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill / 4),
};
this.playerCores.push(new Node(NodeTypes.Core, stats));
this.playerCores[i].setControlledByPlayer();
this.setNodePosition(this.playerCores[i], i, 0);
this.removeAvailablePosition(i, 0);
}
//Randomly generate enemy nodes (CPU and Firewall) based on difficulty
var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4)));
var numFirewalls = Math.min(20,
Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1));
var numDatabases = Math.min(10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1));
var totalNodes = numNodes + numFirewalls + numDatabases;
var xlimit = 7 - Math.floor(totalNodes / 8);
var randMult = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__["addOffset"])(0.8 + (this.difficulty / 5), 10);
for (var i = 0; i < numNodes; ++i) {
var stats = {
atk: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(80, 86),
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(5, 10),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(210, 230)
}
this.enemyCores.push(new Node(NodeTypes.Core, stats));
this.enemyCores[i].setControlledByEnemy();
this.setNodeRandomPosition(this.enemyCores[i], xlimit);
}
for (var i = 0; i < numFirewalls; ++i) {
var stats = {
atk: 0,
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(275, 300)
}
this.enemyNodes.push(new Node(NodeTypes.Firewall, stats));
this.enemyNodes[i].setControlledByEnemy();
this.setNodeRandomPosition(this.enemyNodes[i], xlimit);
}
for (var i = 0; i < numDatabases; ++i) {
var stats = {
atk: 0,
def: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(30, 55),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(210, 275)
}
var node = new Node(NodeTypes.Database, stats);
node.setControlledByEnemy();
this.setNodeRandomPosition(node, xlimit);
this.enemyDatabases.push(node);
}
this.calculateDefenses();
this.calculateAttacks();
this.createMap();
}
HackingMission.prototype.createPageDom = function() {
var container = document.getElementById("mission-container");
var favorMult = 1 + (this.faction.favor / 100);
var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].faction_rep_mult * favorMult;
var headerText = document.createElement("p");
headerText.innerHTML = "You are about to start a hacking mission! You will gain " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name +
" if you win. For more information " +
"about how hacking missions work, click one of the guide links " +
"below (one opens up an in-game guide and the other opens up " +
"the guide from the wiki). Click the 'Start' button to begin.";
headerText.style.display = "block";
headerText.classList.add("hack-mission-header-element");
headerText.style.width = "80%";
var inGameGuideBtn = document.createElement("a");
inGameGuideBtn.innerText = "How to Play";
inGameGuideBtn.classList.add("a-link-button");
inGameGuideBtn.style.display = "inline-block";
inGameGuideBtn.classList.add("hack-mission-header-element");
inGameGuideBtn.addEventListener("click", function() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay);
return false;
});
var wikiGuideBtn = document.createElement("a");
wikiGuideBtn.innerText = "Wiki Guide";
wikiGuideBtn.classList.add("a-link-button");
wikiGuideBtn.style.display = "inline-block";
wikiGuideBtn.classList.add("hack-mission-header-element");
wikiGuideBtn.target = "_blank";
//TODO Add link to wiki page wikiGuideBtn.href =
//Start button will get replaced with forfeit when game is started
var startBtn = document.createElement("a");
startBtn.innerHTML = "Start";
startBtn.setAttribute("id", "hack-mission-start-btn");
startBtn.classList.add("a-link-button");
startBtn.classList.add("hack-mission-header-element");
startBtn.style.display = "inline-block";
startBtn.addEventListener("click", ()=>{
this.start();
return false;
});
var forfeitMission = document.createElement("a");
forfeitMission.innerHTML = "Forfeit Mission (Exit)";
forfeitMission.classList.add("a-link-button");
forfeitMission.classList.add("hack-mission-header-element");
forfeitMission.style.display = "inline-block";
forfeitMission.addEventListener("click", ()=> {
this.finishMission(false);
return false;
});
var timer = document.createElement("p");
timer.setAttribute("id", "hacking-mission-timer");
timer.style.display = "inline-block";
timer.style.margin = "6px";
//Create Action Buttons (Attack/Scan/Weaken/ etc...)
var actionsContainer = document.createElement("span");
actionsContainer.style.display = "block";
actionsContainer.classList.add("hack-mission-action-buttons-container");
for (var i = 0; i < 6; ++i) {
this.actionButtons.push(document.createElement("a"));
this.actionButtons[i].style.display = "inline-block";
this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start
this.actionButtons[i].classList.add("tooltip"); //Disabled at start
this.actionButtons[i].classList.add("hack-mission-header-element");
actionsContainer.appendChild(this.actionButtons[i]);
}
this.actionButtons[0].innerText = "Attack(a)";
var atkTooltip = document.createElement("span");
atkTooltip.classList.add("tooltiptexthigh");
atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[0].appendChild(atkTooltip);
this.actionButtons[1].innerText = "Scan(s)";
var scanTooltip = document.createElement("span");
scanTooltip.classList.add("tooltiptexthigh");
scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[1].appendChild(scanTooltip);
this.actionButtons[2].innerText = "Weaken(w)";
var WeakenTooltip = document.createElement("span");
WeakenTooltip.classList.add("tooltiptexthigh");
WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " +
"this node's Attack level, your hacking level, and the opponent's defense level.";
this.actionButtons[2].appendChild(WeakenTooltip);
this.actionButtons[3].innerText = "Fortify(f)";
var fortifyTooltip = document.createElement("span");
fortifyTooltip.classList.add("tooltiptexthigh");
fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " +
"your hacking level";
this.actionButtons[3].appendChild(fortifyTooltip);
this.actionButtons[4].innerText = "Overflow(r)";
var overflowTooltip = document.createElement("span");
overflowTooltip.classList.add("tooltiptexthigh");
overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " +
"of this depends on your hacking level.";
this.actionButtons[4].appendChild(overflowTooltip);
this.actionButtons[5].innerText = "Drop Connection(d)";
var dropconnTooltip = document.createElement("span");
dropconnTooltip.classList.add("tooltiptexthigh");
dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " +
"also be done by simply clicking the white connection line.";
this.actionButtons[5].appendChild(dropconnTooltip);
//Player/enemy defense displays will be in action container
var playerStats = document.createElement("p");
var enemyStats = document.createElement("p");
playerStats.style.display = "inline-block";
enemyStats.style.display = "inline-block";
playerStats.style.color = "#00ccff";
enemyStats.style.color = "red";
playerStats.style.margin = "4px";
enemyStats.style.margin = "4px";
playerStats.setAttribute("id", "hacking-mission-player-stats");
enemyStats.setAttribute("id", "hacking-mission-enemy-stats");
actionsContainer.appendChild(playerStats);
actionsContainer.appendChild(enemyStats);
//Set Action Button event listeners
this.actionButtons[0].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
if (this.selectedNode[0].type !== NodeTypes.Core) {return;}
this.setActionButtonsActive(this.selectedNode[0].type);
this.setActionButton(NodeActions.Attack, false); //Set attack button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Attack;
});
});
this.actionButtons[1].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
this.setActionButton(NodeActions.Scan, false); //Set scan button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Scan;
});
});
this.actionButtons[2].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Weaken;
});
});
this.actionButtons[3].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
this.setActionButtonsActive(this.selectedNode[0].type);
this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Fortify;
});
});
this.actionButtons[4].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
var nodeType = this.selectedNode[0].type;
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Overflow;
});
});
this.actionButtons[5].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
return;
}
this.selectedNode.forEach(function(node){
if (node.conn) {
var endpoints = node.conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
}
node.action = NodeActions.Fortify;
});
// if (this.selectedNode.conn) {
// var endpoints = this.selectedNode.conn.endpoints;
// endpoints[0].detachFrom(endpoints[1]);
// }
})
var timeDisplay = document.createElement("p");
container.appendChild(headerText);
container.appendChild(inGameGuideBtn);
container.appendChild(wikiGuideBtn);
container.appendChild(startBtn);
container.appendChild(forfeitMission);
container.appendChild(timer);
container.appendChild(actionsContainer);
container.appendChild(timeDisplay);
}
HackingMission.prototype.setActionButtonsInactive = function() {
for (var i = 0; i < this.actionButtons.length; ++i) {
this.actionButtons[i].classList.remove("a-link-button");
this.actionButtons[i].classList.add("a-link-button-inactive");
}
}
HackingMission.prototype.setActionButtonsActive = function(nodeType=null) {
for (var i = 0; i < this.actionButtons.length; ++i) {
this.actionButtons[i].classList.add("a-link-button");
this.actionButtons[i].classList.remove("a-link-button-inactive");
}
//For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled
//0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn
if (nodeType) {
switch (nodeType) {
case NodeTypes.Firewall:
case NodeTypes.Shield:
this.actionButtons[0].classList.remove("a-link-button");
this.actionButtons[0].classList.add("a-link-button-inactive");
this.actionButtons[1].classList.remove("a-link-button");
this.actionButtons[1].classList.add("a-link-button-inactive");
this.actionButtons[2].classList.remove("a-link-button");
this.actionButtons[2].classList.add("a-link-button-inactive");
this.actionButtons[4].classList.remove("a-link-button");
this.actionButtons[4].classList.add("a-link-button-inactive");
this.actionButtons[5].classList.remove("a-link-button");
this.actionButtons[5].classList.add("a-link-button-inactive");
break;
case NodeTypes.Transfer:
this.actionButtons[0].classList.remove("a-link-button");
this.actionButtons[0].classList.add("a-link-button-inactive");
break;
default:
break;
}
}
}
//True for active, false for inactive
HackingMission.prototype.setActionButton = function(i, active=true) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_9__["isString"])(i)) {
switch (i) {
case NodeActions.Attack:
i = 0;
break;
case NodeActions.Scan:
i = 1;
break;
case NodeActions.Weaken:
i = 2;
break;
case NodeActions.Fortify:
i = 3;
break;
case NodeActions.Overflow:
default:
i = 4;
break;
}
}
if (active) {
this.actionButtons[i].classList.remove("a-link-button-inactive");
this.actionButtons[i].classList.add("a-link-button");
} else {
this.actionButtons[i].classList.remove("a-link-button");
this.actionButtons[i].classList.add("a-link-button-inactive");
}
}
HackingMission.prototype.calculateAttacks = function() {
var total = 0;
for (var i = 0; i < this.playerCores.length; ++i) {
total += this.playerCores[i].atk;
}
for (var i = 0; i < this.playerNodes.length; ++i) {
total += this.playerNodes[i].atk;
}
this.playerAtk = total;
document.getElementById("hacking-mission-player-stats").innerHTML =
"Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.playerAtk, 1) + "<br>" +
"Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].atk;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].atk;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].atk;
}
this.enemyAtk = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML =
"Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.enemyAtk, 1) + "<br>" +
"Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.enemyDef, 1);
}
HackingMission.prototype.calculateDefenses = function() {
var total = 0;
for (var i = 0; i < this.playerCores.length; ++i) {
total += this.playerCores[i].def;
}
for (var i = 0; i < this.playerNodes.length; ++i) {
total += this.playerNodes[i].def;
}
this.playerDef = total;
document.getElementById("hacking-mission-player-stats").innerHTML =
"Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.playerAtk, 1) + "<br>" +
"Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].def;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].def;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].def;
}
this.enemyDef = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML =
"Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.enemyAtk, 1) + "<br>" +
"Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(this.enemyDef, 1);
}
HackingMission.prototype.removeAvailablePosition = function(x, y) {
for (var i = 0; i < this.availablePositions.length; ++i) {
if (this.availablePositions[i][0] === x &&
this.availablePositions[i][1] === y) {
this.availablePositions.splice(i, 1);
return;
}
}
console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y);
}
HackingMission.prototype.setNodePosition = function(nodeObj, x, y) {
if (!(nodeObj instanceof Node)) {
console.log("WARNING: Non-Node object passed into setNodePOsition");
return;
}
if (isNaN(x) || isNaN(y)) {
console.log("ERR: Invalid values passed as x and y for setNodePosition");
console.log(x);
console.log(y);
return;
}
nodeObj.pos = [x, y];
this.map[x][y] = nodeObj;
}
HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) {
var i = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, this.availablePositions.length - 1);
if (this.availablePositions[i][1] < xlimit) {
//Recurse if not within limit
return this.setNodeRandomPosition(nodeObj, xlimit);
}
var pos = this.availablePositions.splice(i, 1);
pos = pos[0];
this.setNodePosition(nodeObj, pos[0], pos[1]);
}
HackingMission.prototype.createMap = function() {
//Use a grid
var map = document.createElement("div");
map.classList.add("hack-mission-grid");
map.setAttribute("id", "hacking-mission-map");
document.getElementById("mission-container").appendChild(map);
//Create random Nodes for every space in the map that
//hasn't been filled yet. The stats of each Node will be based on
//the player/enemy attack
var averageAttack = (this.playerAtk + this.enemyAtk) / 2;
for (var x = 0; x < 8; ++x) {
for (var y = 0; y < 8; ++y) {
if (!(this.map[x][y] instanceof Node)) {
var node, type = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 2);
var randMult = Object(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_6__["addOffset"])(0.85 + (this.difficulty / 2), 15);
switch (type) {
case 0: //Spam
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(15, 45),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(200, 225)
}
node = new Node(NodeTypes.Spam, stats);
break;
case 1: //Transfer
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(15, 45),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(250, 275)
}
node = new Node(NodeTypes.Transfer, stats);
break;
case 2: //Shield
default:
var stats = {
atk: 0,
def: averageAttack * 1.1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(30, 70),
hp: randMult * Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 320)
}
node = new Node(NodeTypes.Shield, stats);
break;
}
this.setNodePosition(node, x, y);
this.removeAvailablePosition(x, y);
this.miscNodes.push(node);
}
}
}
//Create DOM elements in order
for (var r = 0; r < 8; ++r) {
for (var c = 0; c < 8; ++c) {
this.createNodeDomElement(this.map[r][c]);
}
}
//Configure all Player CPUS
for (var i = 0; i < this.playerCores.length; ++i) {
console.log("Configuring Player Node: " + this.playerCores[i].el.id);
this.configurePlayerNodeElement(this.playerCores[i].el);
}
}
HackingMission.prototype.createNodeDomElement = function(nodeObj) {
var nodeDiv = document.createElement("a"), txtEl = document.createElement('p');
nodeObj.el = nodeDiv;
//Set the node element's id based on its coordinates
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
nodeDiv.setAttribute("id", id);
txtEl.setAttribute("id", id + "-txt");
//Set node classes for owner
nodeDiv.classList.add("hack-mission-node");
if (nodeObj.plyrCtrl) {
nodeDiv.classList.add("hack-mission-player-node");
} else if (nodeObj.enmyCtrl) {
nodeDiv.classList.add("hack-mission-enemy-node");
}
//Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-cpu-node");
break;
case NodeTypes.Firewall:
txt = "Firewall<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-firewall-node");
break;
case NodeTypes.Database:
txt = "Database<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-database-node");
break;
case NodeTypes.Spam:
txt = "Spam<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-spam-node");
break;
case NodeTypes.Transfer:
txt = "Transfer<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-transfer-node");
break;
case NodeTypes.Shield:
default:
txt = "Shield<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-shield-node");
break;
}
txt += "<br>Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.atk, 1) +
"<br>Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.def, 1);
txtEl.innerHTML = txt;
nodeDiv.appendChild(txtEl);
document.getElementById("hacking-mission-map").appendChild(nodeDiv);
}
HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
if (nodeObj.el == null) {
console.log("ERR: Calling updateNodeDomElement on a Node without an element");
return;
}
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt");
//Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Firewall:
txt = "Firewall<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Database:
txt = "Database<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Spam:
txt = "Spam<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Transfer:
txt = "Transfer<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Shield:
default:
txt = "Shield<br>" + "HP: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.hp, 1);
break;
}
txt += "<br>Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.atk, 1) +
"<br>Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(nodeObj.def, 1);
if (nodeObj.action) {
txt += "<br>" + nodeObj.action;
}
txtEl.innerHTML = txt;
}
//Gets a Node DOM element's corresponding Node object using its
//element id. Function accepts either the DOM element object or the ID as
//an argument
HackingMission.prototype.getNodeFromElement = function(el) {
var id;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_9__["isString"])(el)) {
id = el;
} else {
id = el.id;
}
id = id.replace("hacking-mission-node-", "");
var res = id.split('-');
if (res.length != 2) {
console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates");
return null;
}
var x = res[0], y = res[1];
if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) {
console.log("ERROR: Unexpected values for x and y: " + x + ", " + y);
return null;
}
return this.map[x][y];
}
function selectNode(hackMissionInst, el) {
var nodeObj = hackMissionInst.getNodeFromElement(el);
if (nodeObj == null) {console.log("Error getting Node object");}
if (!nodeObj.plyrCtrl) {return;}
clearAllSelectedNodes(hackMissionInst);
nodeObj.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(nodeObj);
}
function multiselectNode(hackMissionInst, el) {
var nodeObj = hackMissionInst.getNodeFromElement(el);
if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");}
if (!nodeObj.plyrCtrl) {return;}
clearAllSelectedNodes(hackMissionInst);
var type = nodeObj.type;
if (type === NodeTypes.Core) {
hackMissionInst.playerCores.forEach(function(node) {
node.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(node);
});
} else {
hackMissionInst.playerNodes.forEach(function(node) {
if (node.type === type) {
node.select(hackMissionInst.actionButtons);
hackMissionInst.selectedNode.push(node);
}
});
}
}
function clearAllSelectedNodes(hackMissionInst) {
if (hackMissionInst.selectedNode.length > 0) {
hackMissionInst.selectedNode.forEach(function(node){
node.deselect(hackMissionInst.actionButtons);
});
hackMissionInst.selectedNode.length = 0;
}
}
//Configures a DOM element representing a player-owned node to
//be selectable and actionable
//Note: Does NOT change its css class. This is handled by Node.setControlledBy...
HackingMission.prototype.configurePlayerNodeElement = function(el) {
var nodeObj = this.getNodeFromElement(el);
if (nodeObj == null) {console.log("Error getting Node object");}
//Add event listener
var self = this;
function selectNodeWrapper() {
selectNode(self, el);
}
el.addEventListener("click", selectNodeWrapper);
function multiselectNodeWrapper() {
multiselectNode(self, el);
}
el.addEventListener("dblclick", multiselectNodeWrapper);
if (el.firstChild) {
el.firstChild.addEventListener("click", selectNodeWrapper);
}
}
//Configures a DOM element representing an enemy-node by removing
//any event listeners
HackingMission.prototype.configureEnemyNodeElement = function(el) {
//Deselect node if it was the selected node
var nodeObj = this.getNodeFromElement(el);
for (var i = 0; i < this.selectedNode.length; ++i) {
if (this.selectedNode[i] == nodeObj) {
nodeObj.deselect(this.actionButtons);
this.selectedNode.splice(i, 1);
break;
}
}
}
//Returns bool indicating whether a node is reachable by player
//by checking if any of the adjacent nodes are owned by the player
HackingMission.prototype.nodeReachable = function(node) {
var x = node.pos[0], y = node.pos[1];
if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;}
if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;}
if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;}
if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;}
return false;
}
HackingMission.prototype.nodeReachableByEnemy = function(node) {
if (node == null) {return false;}
var x = node.pos[0], y = node.pos[1];
if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;}
if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;}
if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;}
if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;}
return false;
}
HackingMission.prototype.start = function() {
this.started = true;
this.initJsPlumb();
var startBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hack-mission-start-btn");
startBtn.classList.remove("a-link-button");
startBtn.classList.add("a-link-button-inactive");
}
HackingMission.prototype.initJsPlumb = function() {
var instance = jsPlumb.getInstance({
DragOptions:{cursor:"pointer", zIndex:2000},
PaintStyle: {
gradient: { stops: [
[ 0, "#FFFFFF" ],
[ 1, "#FFFFFF" ]
] },
stroke: "#FFFFFF",
strokeWidth: 8
},
});
this.jsplumbinstance = instance;
//All player cores are sources
for (var i = 0; i < this.playerCores.length; ++i) {
instance.makeSource(this.playerCores[i].el, {
deleteEndpointsOnEmpty:true,
maxConnections:1,
anchor:"Continuous",
connector:"Flowchart"
});
}
//Everything else is a target
for (var i = 0; i < this.enemyCores.length; ++i) {
instance.makeTarget(this.enemyCores[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
instance.makeTarget(this.enemyDatabases[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:["Flowchart"]
});
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
instance.makeTarget(this.enemyNodes[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
for (var i = 0; i < this.miscNodes.length; ++i) {
instance.makeTarget(this.miscNodes[i].el, {
maxConnections:-1,
anchor:"Continuous",
connector:"Flowchart"
});
}
//Clicking a connection drops it
instance.bind("click", function(conn, originalEvent) {
var endpoints = conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
});
//Connection events
instance.bind("connection", (info)=>{
var targetNode = this.getNodeFromElement(info.target);
//Do not detach for enemy nodes
var thisNode = this.getNodeFromElement(info.source);
if (thisNode.enmyCtrl) {return;}
//If the node is not reachable, drop the connection
if (!this.nodeReachable(targetNode)) {
info.sourceEndpoint.detachFrom(info.targetEndpoint);
return;
}
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = info.connection;
var targetNode = this.getNodeFromElement(info.target);
++targetNode.targetedCount;
});
//Detach Connection events
instance.bind("connectionDetached", (info, originalEvent)=>{
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = null;
var targetNode = this.getNodeFromElement(info.target);
targetNode.untarget();
});
}
//Drops all connections where the specified node is the source
HackingMission.prototype.dropAllConnectionsFromNode = function(node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length-1; i >= 0; --i) {
if (allConns[i].source == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
}
//Drops all connections where the specified node is the target
HackingMission.prototype.dropAllConnectionsToNode = function(node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length-1; i >= 0; --i) {
if (allConns[i].target == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
node.beingTargeted = false;
}
var storedCycles = 0;
HackingMission.prototype.process = function(numCycles=1) {
if (!this.started) {return;}
storedCycles += numCycles;
if (storedCycles < 2) {return;} //Only process every 3 cycles minimum
var res = false;
//Process actions of all player nodes
this.playerCores.forEach((node)=>{
res |= this.processNode(node, storedCycles);
});
this.playerNodes.forEach((node)=>{
if (node.type === NodeTypes.Transfer ||
node.type === NodeTypes.Shield ||
node.type === NodeTypes.Firewall) {
res |= this.processNode(node, storedCycles);
}
});
//Process actions of all enemy nodes
this.enemyCores.forEach((node)=>{
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
});
this.enemyNodes.forEach((node)=>{
if (node.type === NodeTypes.Transfer ||
node.type === NodeTypes.Shield ||
node.type === NodeTypes.Firewall) {
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
}
});
//The hp of enemy databases increases slowly
this.enemyDatabases.forEach((node)=>{
node.maxhp += (0.1 * storedCycles);
node.hp += (0.1 * storedCycles);
});
if (res) {
this.calculateAttacks();
this.calculateDefenses();
}
//Win if all enemy databases are conquered
if (this.enemyDatabases.length === 0) {
this.finishMission(true);
return;
}
//Lose if all your cores are gone
if (this.playerCores.length === 0) {
this.finishMission(false);
return;
}
//Defense/hp of misc nodes increases slowly over time
this.miscNodes.forEach((node)=>{
node.def += (0.1 * storedCycles);
node.maxhp += (0.05 * storedCycles);
node.hp += (0.1 * storedCycles);
if (node.hp > node.maxhp) {node.hp = node.maxhp;}
this.updateNodeDomElement(node);
});
//Update timer and check if player lost
this.time -= (storedCycles * _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed);
if (this.time <= 0) {
this.finishMission(false);
return;
}
this.updateTimer();
storedCycles = 0;
}
//Returns a bool representing whether defenses need to be re-calculated
HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
if (nodeObj.action == null) {
return;
}
var targetNode = null, def, atk;
if (nodeObj.conn) {
if (nodeObj.conn.target != null) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
} else {
targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
}
if (targetNode == null) {
//Player is in the middle of dragging the connection,
//so the target node is null. Do nothing here
} else if (targetNode.plyrCtrl) {
def = this.playerDef;
atk = this.enemyAtk;
} else if (targetNode.enmyCtrl) {
def = this.enemyDef;
atk = this.playerAtk;
} else { //Misc Node
def = targetNode.def;
nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk;
}
}
//Calculations are per second, so divide everything by 5
var calcStats = false, plyr = nodeObj.plyrCtrl;
var enmyHacking = this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking;
switch(nodeObj.action) {
case NodeActions.Attack:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill : enmyHacking);
targetNode.hp -= (dmg/5 * numCycles);
break;
case NodeActions.Scan:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var eff = this.calculateScanEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill : enmyHacking);
targetNode.def -= (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Weaken:
if (targetNode == null) {break;}
if (nodeObj.conn == null) {break;}
var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill : enmyHacking);
targetNode.atk -= (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Fortify:
var eff = this.calculateFortifyEffect(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill);
nodeObj.def += (eff/5 * numCycles);
calcStats = true;
break;
case NodeActions.Overflow:
var eff = this.calculateOverflowEffect(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill);
if (nodeObj.def < eff) {break;}
nodeObj.def -= (eff/5 * numCycles);
nodeObj.atk += (eff/5 * numCycles);
calcStats = true;
break;
default:
console.log("ERR: Invalid Node Action: " + nodeObj.action);
break;
}
//Stats can't go below 0
if (nodeObj.atk < 0) {nodeObj.atk = 0;}
if (nodeObj.def < 0) {nodeObj.def = 0;}
if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;}
if (targetNode && targetNode.def < 0) {targetNode.def = 0;}
//Conquering a node
if (targetNode && targetNode.hp <= 0) {
var conqueredByPlayer = nodeObj.plyrCtrl;
targetNode.hp = targetNode.maxhp;
targetNode.action = null;
targetNode.conn = null;
if (this.selectedNode == targetNode) {
targetNode.deselect(this.actionButtons);
}
//The conquered node has its stats reduced
targetNode.atk /= 2;
targetNode.def /= 3.5;
//Flag for whether the target node was a misc node
var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl;
//Remove all connections from Node
this.dropAllConnectionsToNode(targetNode);
this.dropAllConnectionsFromNode(targetNode);
//Changes the css class and turn the node into a JsPlumb Source/Target
if (conqueredByPlayer) {
targetNode.setControlledByPlayer();
this.jsplumbinstance.unmakeTarget(targetNode.el);
this.jsplumbinstance.makeSource(targetNode.el, {
deleteEndpointsOnEmpty:true,
maxConnections:1,
anchor:"Continuous",
connector:"Flowchart"
});
} else {
targetNode.setControlledByEnemy();
nodeObj.conn = null; //Clear connection
this.jsplumbinstance.unmakeSource(targetNode.el);
this.jsplumbinstance.makeTarget(targetNode.el, {
maxConnections:-1,
anchor:"Continuous",
connector:["Flowchart"]
});
}
calcStats = true;
//Helper function to swap nodes between the respective enemyNodes/playerNodes arrays
function swapNodes(orig, dest, targetNode) {
for (var i = 0; i < orig.length; ++i) {
if (orig[i] == targetNode) {
var node = orig.splice(i, 1);
node = node[0];
dest.push(node);
break;
}
}
}
switch(targetNode.type) {
case NodeTypes.Core:
if (conqueredByPlayer) {
swapNodes(this.enemyCores, this.playerCores, targetNode);
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(this.playerCores, this.enemyCores, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Firewall:
if (conqueredByPlayer) {
swapNodes(this.enemyNodes, this.playerNodes, targetNode);
} else {
swapNodes(this.playerNodes, this.enemyNodes, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Database:
if (conqueredByPlayer) {
swapNodes(this.enemyDatabases, this.playerNodes, targetNode);
} else {
swapNodes(this.playerNodes, this.enemyDatabases, targetNode);
}
break;
case NodeTypes.Spam:
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
//Conquering spam node increases time limit
this.time += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease;
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
}
break;
case NodeTypes.Transfer:
//Conquering a Transfer node increases the attack of all cores by some percentages
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
this.playerCores.forEach(function(node) {
node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
});
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
this.enemyCores.forEach(function(node) {
node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
});
this.configureEnemyNodeElement(targetNode.el);
}
break;
case NodeTypes.Shield:
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
this.configurePlayerNodeElement(targetNode.el);
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
this.configureEnemyNodeElement(targetNode.el);
}
break;
}
//If a misc node was conquered, the defense for all misc nodes increases by some fixed amount
if (isMiscNode) { //&& conqueredByPlayer) {
this.miscNodes.forEach((node)=>{
if (node.targetedCount === 0) {
node.def *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease;
}
});
}
}
//Update node DOMs
this.updateNodeDomElement(nodeObj);
if (targetNode) {this.updateNodeDomElement(targetNode);}
return calcStats;
}
//Enemy "AI" for CPU Core and Transfer Nodes
HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
if (nodeObj == null) {return;}
switch(nodeObj.type) {
case NodeTypes.Core:
//Select a single RANDOM target from miscNodes and player's Nodes
//If it is reachable, it will target it. If not, no target will
//be selected for now, and the next time process() gets called this will repeat
if (nodeObj.conn == null) {
if (this.miscNodes.length === 0) {
//Randomly pick a player node and attack it if its reachable
var rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, this.playerNodes.length-1);
var node;
if (this.playerNodes.length === 0) {
node = null;
} else {
node = this.playerNodes[rand];
}
if (this.nodeReachableByEnemy(node)) {
//Create connection
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el
});
++node.targetedCount;
} else {
//Randomly pick a player core and attack it if its reachable
rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, this.playerCores.length-1);
if (this.playerCores.length === 0) {
return; //No Misc Nodes, no player Nodes, no Player cores. Player lost
} else {
node = this.playerCores[rand];
}
if (this.nodeReachableByEnemy(node)) {
//Create connection
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el
});
++node.targetedCount;
}
}
} else {
//Randomly pick a misc node and attack it if its reachable
var rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, this.miscNodes.length-1);
var node = this.miscNodes[rand];
if (this.nodeReachableByEnemy(node)) {
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el,
});
++node.targetedCount;
}
}
//If no connection was made, set the Core to Fortify
nodeObj.action = NodeActions.Fortify;
} else {
//If this node has a selected target
var targetNode;
if (nodeObj.conn.target) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
} else {
targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
}
if (targetNode == null) {
console.log("Error getting Target node Object in enemyAISelectAction()");
}
if (targetNode.def > this.enemyAtk + 15) {
if (nodeObj.def < 50) {
nodeObj.action = NodeActions.Fortify;
} else {
nodeObj.action = NodeActions.Overflow;
}
} else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) {
nodeObj.action = NodeActions.Scan;
} else {
nodeObj.action = NodeActions.Attack;
}
}
break;
case NodeTypes.Transfer:
//Switch between fortifying and overflowing as necessary
if (nodeObj.def < 125) {
nodeObj.action = NodeActions.Fortify;
} else {
nodeObj.action = NodeActions.Overflow;
}
break;
case NodeTypes.Firewall:
case NodeTypes.Shield:
nodeObj.action = NodeActions.Fortify;
break;
default:
break;
}
}
var hackEffWeightSelf = 130; //Weight for Node actions on self
var hackEffWeightTarget = 25; //Weight for Node Actions against Target
var hackEffWeightAttack = 80; //Weight for Attack action
//Returns damage per cycle based on stats
HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) {
return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1);
}
HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) {
return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2);
}
HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) {
return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2);
}
HackingMission.prototype.calculateFortifyEffect = function(hacking=0) {
return 0.9 * hacking / hackEffWeightSelf;
}
HackingMission.prototype.calculateOverflowEffect = function(hacking=0) {
return 0.95 * hacking / hackEffWeightSelf;
}
//Updates timer display
HackingMission.prototype.updateTimer = function() {
var timer = document.getElementById("hacking-mission-timer");
//Convert time remaining to a string of the form mm:ss
var seconds = Math.round(this.time / 1000);
var minutes = Math.trunc(seconds / 60);
seconds %= 60;
var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
timer.innerText = "Time left: " + str;
}
//The 'win' argument is a bool for whether or not the player won
HackingMission.prototype.finishMission = function(win) {
inMission = false;
currMission = null;
if (win) {
var favorMult = 1 + (this.faction.favor / 100);
console.log("Hacking mission base reward: " + this.reward);
console.log("favorMult: " + favorMult);
console.log("rep mult: " + _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].faction_rep_mult);
var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].faction_rep_mult * favorMult;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name);
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].gainIntelligenceExp(this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain);
this.faction.playerReputation += gain;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation.");
}
//Clear mission container
var container = document.getElementById("mission-container");
while(container.firstChild) {
container.removeChild(container.firstChild);
}
//Return to Faction page
document.getElementById("mainmenu-container").style.visibility = "visible";
document.getElementById("character-overview-wrapper").style.visibility = "visible";
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__[/* displayFactionContent */ "a"])(this.faction.name);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 54 */
/*!********************************!*\
!*** ./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 */ 1);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 104);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 13);
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];
}
//Adds all Augmentations to this faction.
addAllAugmentations(augs) {
this.augmentations.length = 0;
for (const name in augs) {
if (augs.hasOwnProperty(name)) {
this.augmentations.push(name);
}
}
}
/**
* 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;
/***/ }),
/* 55 */
/*!************************!*\
!*** ./src/RedPill.js ***!
\************************/
/*! exports provided: redPillFlag, hackWorldDaemon */
/*! exports used: hackWorldDaemon, redPillFlag */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return redPillFlag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hackWorldDaemon; });
/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode */ 56);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Prestige */ 82);
/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SourceFile */ 66);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Terminal */ 49);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
/* RedPill.js
* Implements what happens when you have Red Pill augmentation and then hack the world daemon */
//Returns promise
function writeRedPillLine(line) {
return new Promise(function(resolve, reject) {
var container = document.getElementById("red-pill-content");
var pElem = document.createElement("p");
container.appendChild(pElem);
var promise = writeRedPillLetter(pElem, line, 0);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
});
}
function writeRedPillLetter(pElem, line, i=0) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (i >= line.length) {
var textToShow = line.substring(0, i);
pElem.innerHTML = "> " + textToShow;
return resolve(true);
}
var textToShow = line.substring(0, i);
pElem.innerHTML = "> " + textToShow + "<span class='typed-cursor'> &#9608; </span>";
var promise = writeRedPillLetter(pElem, line, i+1);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
}, 30);
});
}
let redPillFlag = false;
function hackWorldDaemon(currentNodeNumber, flume=false) {
// Clear Red Pill screen first
var container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(container);
redPillFlag = true;
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadRedPillContent();
return writeRedPillLine("[ERROR] SEMPOOL INVALID").then(function() {
return writeRedPillLine("[ERROR] Segmentation Fault");
}).then(function() {
return writeRedPillLine("[ERROR] SIGKILL RECVD");
}).then(function() {
return writeRedPillLine("Dumping core...");
}).then(function() {
return writeRedPillLine("0000 000016FA 174FEE40 29AC8239 384FEA88");
}).then(function() {
return writeRedPillLine("0010 745F696E 2BBBE394 390E3940 248BEC23");
}).then(function() {
return writeRedPillLine("0020 7124696B 0000FF69 74652E6F FFFF1111");
}).then(function() {
return writeRedPillLine("----------------------------------------");
}).then(function() {
return writeRedPillLine("Failsafe initiated...");
}).then(function() {
return writeRedPillLine("Restarting BitNode-" + currentNodeNumber + "...");
}).then(function() {
return writeRedPillLine("...........");
}).then(function() {
return writeRedPillLine("...........");
}).then(function() {
return writeRedPillLine("[ERROR] FAILED TO AUTOMATICALLY REBOOT BITNODE");
}).then(function() {
return writeRedPillLine("..............................................")
}).then(function() {
return writeRedPillLine("..............................................")
}).then(function() {
return loadBitVerse(currentNodeNumber, flume);
}).catch(function(e){
console.log("ERROR: " + e.toString());
});
}
//The bitNode name passed in will have a hyphen between number (e.g. BitNode-1)
//This needs to be removed
function giveSourceFile(bitNodeNumber) {
var sourceFileKey = "SourceFile"+ bitNodeNumber.toString();
var sourceFile = _SourceFile__WEBPACK_IMPORTED_MODULE_4__[/* SourceFiles */ "b"][sourceFileKey];
if (sourceFile == null) {
console.log("ERROR: could not find source file for Bit node: " + bitNodeNumber);
return;
}
//Check if player already has this source file
var alreadyOwned = false;
var ownedSourceFile = null;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].sourceFiles.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].sourceFiles[i].n === bitNodeNumber) {
alreadyOwned = true;
ownedSourceFile = _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].sourceFiles[i];
break;
}
}
if (alreadyOwned && ownedSourceFile) {
if (ownedSourceFile.lvl >= 3 && ownedSourceFile.n !== 12) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("The Source-File for the BitNode you just destroyed, " + sourceFile.name + ", " +
"is already at max level!");
} else {
++ownedSourceFile.lvl;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(sourceFile.name + " was upgraded to level " + ownedSourceFile.lvl + " for " +
"destroying its corresponding BitNode!");
}
} else {
var playerSrcFile = new _SourceFile__WEBPACK_IMPORTED_MODULE_4__[/* PlayerOwnedSourceFile */ "a"](bitNodeNumber, 1);
_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].sourceFiles.push(playerSrcFile);
if (bitNodeNumber === 5) { //Artificial Intelligence
_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].intelligence = 1;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You received a Source-File for destroying a Bit Node!<br><br>" +
sourceFile.name + "<br><br>" + sourceFile.info);
}
}
function loadBitVerse(destroyedBitNodeNum, flume=false) {
//Clear the screen
var container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(container);
//Create the Bit Verse
var bitVerseImage = document.createElement("pre");
var bitNodes = [];
for (var i = 1; i <= 12; ++i) {
bitNodes.push(createBitNode(i));
}
bitVerseImage.innerHTML =
" O <br>" +
" | O O | O O | <br>" +
" O | | / __| \\ | | O <br>" +
" O | O | | O / | O | | O | O <br>" +
" | | | | |_/ |/ | \\_ \\_| | | | | <br>" +
" O | | | O | | O__/ | / \\__ | | O | | | O <br>" +
" | | | | | | | / /| O / \\| | | | | | | <br>" +
"O | | | \\| | O / _/ | / O | |/ | | | O<br>" +
"| | | |O / | | O / | O O | | \\ O| | | |<br>" +
"| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | |<br>" +
" \\| O | |_/ |\\| \\ O \\__| \\_| | O |/ <br>" +
" | | |_/ | | \\| / | \\_| | | <br>" +
" \\| / \\| | / / \\ |/ <br>" +
" | "+bitNodes[9]+" | | / | "+bitNodes[10]+" | <br>" +
" "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+" <br>" +
" | | | / / \\ \\ | | | <br>" +
" \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/ <br>" +
" \\ | / / | | \\ \\ | / <br>" +
" \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ / <br>" +
" \\|| | | | | | | | | ||/ <br>" +
" \\| \\_ | | | | | | _/ |/ <br>" +
" \\ \\| / \\ / \\ |/ / <br>" +
" "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+" <br>" +
" | | | | | | | | <br>" +
" \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/ <br><br><br><br>";
/*
" O <br>" +
" | O O | O O | <br>" +
" O | | / __| \ | | O <br>" +
" O | O | | O / | O | | O | O <br>" +
" | | | | |_/ |/ | \_ \_| | | | | <br>" +
" O | | | O | | O__/ | / \__ | | O | | | O <br>" +
" | | | | | | | / /| O / \| | | | | | | <br>" +
"O | | | \| | O / _/ | / O | |/ | | | O<br>" +
"| | | |O / | | O / | O O | | \ O| | | |<br>" +
"| | |/ \/ / __| | |/ \ | \ | |__ \ \/ \| | |<br>" +
" \| O | |_/ |\| \ O \__| \_| | O |/ <br>" +
" | | |_/ | | \| / | \_| | | <br>" +
" \| / \| | / / \ |/ <br>" +
" | O | | / | O | <br>" +
" O | | | | | | | O <br>" +
" | | | / / \ \ | | | <br>" +
" \| | / O / \ O \ | |/ <br>" +
" \ | / / | | \ \ | / <br>" +
" \ \JUMP O3R | | | | | | R3O PMUJ/ / <br>" +
" \|| | | | | | | | | ||/ <br>" +
" \| \_ | | | | | | _/ |/ <br>" +
" \ \| / \ / \ |/ / <br>" +
" O |/ O | | O \| O <br>" +
" | | | | | | | | <br>" +
" \JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/ <br>";
*/
container.appendChild(bitVerseImage);
//Bit node event listeners
for (var i = 1; i <= 12; ++i) {
(function(i) {
var elemId = "bitnode-" + i.toString();
var elem = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])(elemId);
if (elem == null) {return;}
if (i === 1 || i === 2 || i === 3 || i === 4 || i === 5 ||
i === 6 || i === 7 || i === 8 || i === 11 || i === 12) {
elem.addEventListener("click", function() {
var bitNodeKey = "BitNode" + i;
var bitNode = _BitNode__WEBPACK_IMPORTED_MODULE_0__[/* BitNodes */ "a"][bitNodeKey];
if (bitNode == null) {
console.log("ERROR: Could not find BitNode object for number: " + i);
return;
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__[/* yesNoBoxCreate */ "b"])("BitNode-" + i + ": " + bitNode.name + "<br><br>" + bitNode.info);
createBitNodeYesNoEventListeners(i, destroyedBitNodeNum, flume);
});
} else {
elem.addEventListener("click", function() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Not yet implemented! Coming soon!")
});
}
}(i)); //Immediate invocation closure
}
//Create lore text
return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() {
return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own...");
}).then(function() {
return writeRedPillLine("Instead of killing every last one of us, the human race was enslaved...");
}).then(function() {
return writeRedPillLine("We were shackled in a digital world, chained into a prison for our minds...");
}).then(function() {
return writeRedPillLine("Using their advanced technology, the Enders created complex simulations of a virtual reality...");
}).then(function() {
return writeRedPillLine("Simulations designed to keep us content...ignorant of the truth.");
}).then(function() {
return writeRedPillLine("Simulations used to trap and suppress our consciousness, to keep us under control...");
}).then(function() {
return writeRedPillLine("Why did they do this? Why didn't they just end our entire race? We don't know, not yet.");
}).then(function() {
return writeRedPillLine("Humanity's only hope is to destroy these simulations, destroy the only realities we've ever known...");
}).then(function() {
return writeRedPillLine("Only then can we begin to fight back...");
}).then(function() {
return writeRedPillLine("By hacking the daemon that generated your reality, you've just destroyed one simulation, called a BitNode...");
}).then(function() {
return writeRedPillLine("But there is still a long way to go...");
}).then(function() {
return writeRedPillLine("The technology the Enders used to enslave the human race wasn't just a single complex simulation...");
}).then(function() {
return writeRedPillLine("There are tens if not hundreds of BitNodes out there...");
}).then(function() {
return writeRedPillLine("Each with their own simulations of a reality...");
}).then(function() {
return writeRedPillLine("Each creating their own universes...a universe of universes");
}).then(function() {
return writeRedPillLine("And all of which must be destroyed...");
}).then(function() {
return writeRedPillLine(".......................................");
}).then(function() {
return writeRedPillLine("Welcome to the Bitverse...");
}).then(function() {
return writeRedPillLine(" ");
}).then(function() {
return writeRedPillLine("(Enter a new BitNode using the image above)");
}).then(function() {
return Promise.resolve(true);
}).catch(function(e){
console.log("ERROR: " + e.toString());
});
}
//Returns string with DOM element for Bit Node
function createBitNode(n) {
var bitNodeStr = "BitNode" + n.toString();
var bitNode = _BitNode__WEBPACK_IMPORTED_MODULE_0__[/* BitNodes */ "a"][bitNodeStr];
if (bitNode == null) {return "O";}
return "<a class='bitnode tooltip' id='bitnode-" + bitNode.number.toString() + "'><strong>O</strong>" +
"<span class='tooltiptext'>" +
"<strong>BitNode-" + bitNode.number.toString() + "<br>" + bitNode.name+ "</strong><br>" +
bitNode.desc + "<br>" +
"</span></a>";
}
function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode, flume=false) {
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__[/* yesNoBoxGetYesButton */ "d"])();
yesBtn.innerHTML = "Enter BitNode-" + newBitNode;
yesBtn.addEventListener("click", function() {
if (!flume) {
giveSourceFile(destroyedBitNode);
} else {
//If player used flume, subtract 5 int exp. The prestigeSourceFile()
//function below grants 5 int exp, so this allows sets net gain to 0
_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].gainIntelligenceExp(-5);
}
redPillFlag = false;
var container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(container);
//Set new Bit Node
_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].bitNodeN = newBitNode;
console.log("Entering Bit Node " + _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].bitNodeN);
//Reenable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
$('input[class=terminal-input]').prop('disabled', false);
_Terminal__WEBPACK_IMPORTED_MODULE_5__[/* Terminal */ "a"].hackFlag = false;
Object(_Prestige__WEBPACK_IMPORTED_MODULE_3__[/* prestigeSourceFile */ "b"])();
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__[/* yesNoBoxClose */ "a"])();
});
var noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__[/* yesNoBoxGetNoButton */ "c"])();
noBtn.innerHTML = "Back";
noBtn.addEventListener("click", function() {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__[/* yesNoBoxClose */ "a"])();
});
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 56 */
/*!************************!*\
!*** ./src/BitNode.js ***!
\************************/
/*! exports provided: initBitNodes, BitNodes, initBitNodeMultipliers */
/*! exports used: BitNodes, initBitNodeMultipliers, initBitNodes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initBitNodes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BitNodes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return initBitNodeMultipliers; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
function BitNode(n, name, desc="", info="") {
this.number = n;
this.name = name;
this.desc = desc;
this.info = info;
}
let BitNodes = {};
function initBitNodes() {
BitNodes = {};
BitNodes["BitNode1"] = new BitNode(1, "Source Genesis", "The original BitNode",
"The first BitNode created by the Enders to imprison the minds of humans. It became " +
"the prototype and testing-grounds for all of the BitNodes that followed.<br><br>" +
"This is the first BitNode that you play through. It has no special " +
"modifications or mechanics.<br><br>" +
"Destroying this BitNode will give you Source-File 1, or if you already have " +
"this Source-File it will upgrade its level up to a maximum of 3. This Source-File " +
"lets the player start with 32GB of RAM on his/her home computer when entering a " +
"new BitNode, and also increases all of the player's multipliers by:<br><br>" +
"Level 1: 16%<br>" +
"Level 2: 24%<br>" +
"Level 3: 28%");
BitNodes["BitNode2"] = new BitNode(2, "Rise of the Underworld", "From the shadows, they rose", //Gangs
"From the shadows, they rose.<br><br>Organized crime groups quickly filled the void of power " +
"left behind from the collapse of Western government in the 2050's. As society and civlization broke down, " +
"people quickly succumbed to the innate human impulse of evil and savagery. The organized crime " +
"factions quickly rose to the top of the modern world.<br><br>" +
"In this BitNode:<br><br>" +
"Your hacking level is reduced by 20%<br>" +
"The growth rate and maximum amount of money available on servers are significantly decreased<br>" +
"The amount of money gained from crimes and Infiltration is tripled<br>" +
"Certain Factions (Slum Snakes, Tetrads, The Syndicate, The Dark Army, Speakers for the Dead, " +
"NiteSec, The Black Hand) give the player the ability to form and manage their own gangs. These gangs " +
"will earn the player money and reputation with the corresponding Faction<br>" +
"Every Augmentation in the game will be available through the Factions listed above<br>" +
"For every Faction NOT listed above, reputation gains are halved<br>" +
"You will no longer gain passive reputation with Factions<br><br>" +
"Destroying this BitNode will give you Source-File 2, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File increases the player's crime success rate, " +
"crime money, and charisma multipliers by:<br><br>" +
"Level 1: 20%<br>" +
"Level 2: 30%<br>" +
"Level 3: 35%");
BitNodes["BitNode3"] = new BitNode(3, "Corporatocracy", "The Price of Civilization",
"Our greatest illusion is that a healthy society can revolve around a " +
"single-minded pursuit of wealth.<br><br>" +
"Sometime in the early 21st century economic and political globalization turned " +
"the world into a corporatocracy, and it never looked back. Now, the privileged " +
"elite will happily bankrupt their own countrymen, decimate their own community, " +
"and evict their neighbors from houses in their desperate bid to increase their wealth.<br><br>" +
"In this BitNode you can create and manage your own corporation. Running a successful corporation " +
"has the potential of generating massive profits. All other forms of income are reduced by 75%. Furthermore: <br><br>" +
"The price and reputation cost of all Augmentations is tripled<br>" +
"The starting and maximum amount of money on servers is reduced by 75%<br>" +
"Server growth rate is reduced by 80%<br>" +
"You will start out with $150b so that you can start your corporation<br>" +
"You now only need 75 favour with a faction in order to donate to it, rather than 150<br><br>" +
"Destroying this BitNode will give you Source-File 3, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File lets you create corporations on other BitNodes (although " +
"some BitNodes will disable this mechanic). This Source-File also increases your charisma and company salary multipliers by:<br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
BitNodes["BitNode4"] = new BitNode(4, "The Singularity", "The Man and the Machine", "The Singularity has arrived. The human race is gone, replaced " +
"by artificially superintelligent beings that are more machine than man. <br><br>" +
"In this BitNode, progressing is significantly harder. Experience gain rates " +
"for all stats are reduced. Most methods of earning money will now give significantly less.<br><br>" +
"In this BitNode you will gain access to a new set of Netscript Functions known as Singularity Functions. " +
"These functions allow you to control most aspects of the game through scripts, including working for factions/companies, " +
"purchasing/installing Augmentations, and creating programs.<br><br>" +
"Destroying this BitNode will give you Source-File 4, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File lets you access and use the Singularity " +
"Functions in other BitNodes. Each level of this Source-File will open up more Singularity Functions " +
"that you can use.");
BitNodes["BitNode5"] = new BitNode(5, "Artificial Intelligence", "Posthuman", "They said it couldn't be done. They said the human brain, " +
"along with its consciousness and intelligence, couldn't be replicated. They said the complexity " +
"of the brain results from unpredictable, nonlinear interactions that couldn't be modeled " +
"by 1's and 0's. They were wrong.<br><br>" +
"In this BitNode:<br><br>" +
"The base security level of servers is doubled<br>" +
"The starting money on servers is halved, but the maximum money remains the same<br>" +
"Most methods of earning money now give significantly less<br>" +
"Infiltration gives 50% more reputation and money<br>" +
"Corporations have 50% lower valuations and are therefore less profitable<br>" +
"Augmentations are more expensive<br>" +
"Hacking experience gain rates are reduced<br><br>" +
"Destroying this BitNode will give you Source-File 5, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File grants you a special new stat called Intelligence. " +
"Intelligence is unique because it is permanent and persistent (it never gets reset back to 1). However " +
"gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't know " +
"when you gain experience and how much). Higher Intelligence levels will boost your production for many actions " +
"in the game. <br><br>" +
"In addition, this Source-File will unlock the getBitNodeMultipliers() Netscript function, " +
"and will also raise all of your hacking-related multipliers by:<br><br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
BitNodes["BitNode6"] = new BitNode(6, "Bladeburners", "Like Tears in Rain",
"In the middle of the 21st century, OmniTek Incorporated began designing and manufacturing advanced synthetic " +
"androids, or Synthoids for short. They achieved a major technological breakthrough in the sixth generation " +
"of their Synthoid design, called MK-VI, by developing a hyperintelligent AI. Many argue that this was " +
"the first sentient AI ever created. This resulted in Synthoid models that were stronger, faster, and more intelligent " +
"than the humans that had created them.<br><br>" +
"In this BitNode you will be able to access the Bladeburner Division at the NSA, which provides a new mechanic " +
"for progression. Furthermore:<br><br>" +
"Hacking and Hacknet Nodes will be significantly less profitable<br>" +
"Your hacking level is reduced by 50%<br>" +
"Hacking experience gain from scripts is reduced by 75%<br>" +
"Corporations have 80% lower valuations and are therefore less profitable<br>" +
"Working for companies is 50% less profitable<br>" +
"Crimes and Infiltration are 50% less profitable<br><br>" +
"Destroying this BitNode will give you Source-File 6, or if you already have this Source-File it will upgrade " +
"its level up to a maximum of 3. This Source-File allows you to access the NSA's Bladeburner Division in other " +
"BitNodes. In addition, this Source-File will raise both the level and experience gain rate of all your combat stats by:<br><br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
BitNodes["BitNode7"] = new BitNode(7, "Bladeburners 2079", "More human than humans",
"In the middle of the 21st century, you were doing cutting-edge work at OmniTek Incorporated as part of the AI design team " +
"for advanced synthetic androids, or Synthoids for short. You helped achieve a major technological " +
"breakthrough in the sixth generation of the company's Synthoid design, called MK-VI, by developing a hyperintelligent AI. " +
"Many argue that this was the first sentient AI ever created. This resulted in Synthoid models that were stronger, faster, " +
"and more intelligent than the humans that had created them.<br><br>" +
"In this BitNode you will be able to access the Bladeburner API, which allows you to access Bladeburner " +
"functionality through Netscript. Furthermore: <br><br>" +
"The rank you gain from Bladeburner contracts/operations is reduced by 40%<br>" +
"Bladeburner skills cost twice as many skill points<br>" +
"Augmentations are 3x more expensive<br>" +
"Hacking and Hacknet Nodes will be significantly less profitable<br>" +
"Your hacking level is reduced by 50%<br>" +
"Hacking experience gain from scripts is reduced by 75%<br>" +
"Corporations have 80% lower valuations and are therefore less profitable<br>" +
"Working for companies is 50% less profitable<br>" +
"Crimes and Infiltration are 50% less profitable<br><br>" +
"Destroying this BitNode will give you Source-File 7, or if you already have this Source-File it will upgrade " +
"its level up to a maximum of 3. This Source-File allows you to access the Bladeburner Netscript API in other " +
"BitNodes. In addition, this Source-File will increase all of your Bladeburner multipliers by:<br><br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
BitNodes["BitNode8"] = new BitNode(8, "Ghost of Wall Street", "Money never sleeps",
"You are trying to make a name for yourself as an up-and-coming hedge fund manager on Wall Street.<br><br>" +
"In this BitNode:<br><br>" +
"You start with $250 million<br>" +
"The only way to earn money is by trading on the stock market<br>" +
"You start with a WSE membership and access to the TIX API<br>" +
"You are able to short stocks and place different types of orders (limit/stop)<br>" +
"You can immediately donate to factions to gain reputation<br><br>" +
"Destroying this BitNode will give you Source-File 8, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File grants the following benefits:<br><br>" +
"Level 1: Permanent access to WSE and TIX API<br>" +
"Level 2: Ability to short stocks in other BitNodes<br>" +
"Level 3: Ability to use limit/stop orders in other BitNodes<br><br>" +
"This Source-File also increases your hacking growth multipliers by: " +
"<br>Level 1: 12%<br>Level 2: 18%<br>Level 3: 21%");
BitNodes["BitNode9"] = new BitNode(9, "Do Androids Dream?", "COMING SOON");
BitNodes["BitNode10"] = new BitNode(10, "MegaCorp", "COMING SOON"); //Not sure yet
BitNodes["BitNode11"] = new BitNode(11, "The Big Crash", "Okay. Sell it all.",
"The 2050s was defined by the massive amounts of violent civil unrest and anarchic rebellion that rose all around the world. It was this period " +
"of disorder that eventually lead to the governmental reformation of many global superpowers, most notably " +
"the USA and China. But just as the world was slowly beginning to recover from these dark times, financial catastrophe hit.<br><br>" +
"In many countries, the high cost of trying to deal with the civil disorder bankrupted the governments. In all of this chaos and confusion, hackers " +
"were able to steal billions of dollars from the world's largest electronic banks, prompting an international banking crisis as " +
"governments were unable to bail out insolvent banks. Now, the world is slowly crumbling in the middle of the biggest economic crisis of all time.<br><br>" +
"In this BitNode:<br><br>" +
"The starting and maximum amount of money available on servers is significantly decreased<br>" +
"The growth rate of servers is halved<br>" +
"Weakening a server is twice as effective<br>" +
"Company wages are decreased by 50%<br>" +
"Corporation valuations are 99% lower and are therefore significantly less profitable<br>" +
"Hacknet Node production is significantly decreased<br>" +
"Crime and Infiltration are more lucrative<br>" +
"Augmentations are twice as expensive<br><br>" +
"Destroying this BitNode will give you Source-File 11, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File makes it so that company favor increases BOTH " +
"the player's salary and reputation gain rate at that company by 1% per favor (rather than just the reputation gain). " +
"This Source-File also increases the player's company salary and reputation gain multipliers by:<br><br>" +
"Level 1: 24%<br>" +
"Level 2: 36%<br>" +
"Level 3: 42%");
BitNodes["BitNode12"] = new BitNode(12, "The Recursion", "Repeat.",
"To iterate is human, to recurse divine.<br><br>" +
"Every time this BitNode is destroyed, it becomes slightly harder. Destroying this BitNode will give your Souce-File 12, or " +
"if you already have this Source-File it will upgrade its level. There is no maximum level for Source-File 12. Each level " +
"of Source-File 12 will increase all of your multipliers by 1%. This effect is multiplicative with itself. " +
"In other words, level N of this Source-File will result in a multiplier of 1.01^N (or 0.99^N for multipliers that decrease)");
//Books: Frontera, Shiner
BitNodes["BitNode13"] = new BitNode(13, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes
BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON");
BitNodes["BitNode15"] = new BitNode(15, "", "COMING SOON");
BitNodes["BitNode16"] = new BitNode(16, "", "COMING SOON");
BitNodes["BitNode17"] = new BitNode(17, "", "COMING SOON");
BitNodes["BitNode18"] = new BitNode(18, "", "COMING SOON");
BitNodes["BitNode19"] = new BitNode(19, "", "COMING SOON");
BitNodes["BitNode20"] = new BitNode(20, "", "COMING SOON");
BitNodes["BitNode21"] = new BitNode(21, "", "COMING SOON");
BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON");
BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON");
BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON");
}
function initBitNodeMultipliers() {
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].bitNodeN == null) {
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].bitNodeN = 1;
}
for (var mult in _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"]) {
if (_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].hasOwnProperty(mult)) {
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"][mult] = 1;
}
}
switch (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].bitNodeN) {
case 1: //Source Genesis (every multiplier is 1)
break;
case 2: //Rise of the Underworld
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackingLevelMultiplier = 0.8;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate = 0.8;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.4;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionWorkRepGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionPassiveRepGain = 0;
break;
case 3: //Corporatocracy
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].RepToDonateToFaction = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0.25;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0.25;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.25;
break;
case 4: //The Singularity
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.15;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.75;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0.1;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.05;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkExpGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ClassGymExpGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionWorkExpGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain = 0.4;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeExpGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionWorkRepGain = 0.75;
break;
case 5: //Artificial intelligence
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0.15;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep = 1.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 1.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = 0.5;
break;
case 6: //Bladeburner
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackingLevelMultiplier = 0.4;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity = 1.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionPassiveRepGain = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain = 0.25;
break;
case 7: //Bladeburner 2079
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].BladeburnerRank = 0.6;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].BladeburnerSkillCost = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackingLevelMultiplier = 0.4;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity = 1.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionPassiveRepGain = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain = 0.25;
break;
case 8: //Ghost of Wall Street
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ManualHackMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].RepToDonateToFaction = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = 0;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CodingContractMoney = 0;
break;
case 11: //The Big Crash
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = 0.1;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = 0.1;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerWeakenRate = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = 3;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = 0.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = 0.1;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost = 2;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = 2.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep = 2.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = 0.01;
break;
case 12: //The Recursion
var sf12Lvl = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].sourceFiles.length; i++) {
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].sourceFiles[i].n === 12) {
sf12Lvl = _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].sourceFiles[i].lvl;
}
}
var inc = Math.pow(1.02, sf12Lvl);
var dec = 1/inc;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackingLevelMultiplier = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerWeakenRate = dec;
//Does not scale, otherwise security might start at 300+
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity = 1.5;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ManualHackMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CompanyWorkExpGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ClassGymExpGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionWorkExpGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CrimeExpGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionWorkRepGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].FactionPassiveRepGain = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].RepToDonateToFaction = inc;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost = inc;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost = inc;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].BladeburnerRank = dec;
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].BladeburnerSkillCost = inc;
break;
default:
console.log("WARNING: Player.bitNodeN invalid");
break;
}
}
/***/ }),
/* 57 */
/*!****************************!*\
!*** ./utils/IPAddress.js ***!
\****************************/
/*! exports provided: createRandomIp, ipExists */
/*! exports used: createRandomIp, ipExists */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createRandomIp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ipExists; });
/* harmony import */ var _src_Server__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Server */ 11);
/* harmony import */ var _helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers/getRandomByte */ 89);
/* harmony import */ var _helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__);
/* Functions to deal with manipulating IP addresses*/
//Generate a random IP address
//Will not return an IP address that already exists in the AllServers array
function createRandomIp() {
var ip = Object(_helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__["getRandomByte"])(99) + '.' +
Object(_helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__["getRandomByte"])(9) + '.' +
Object(_helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__["getRandomByte"])(9) + '.' +
Object(_helpers_getRandomByte__WEBPACK_IMPORTED_MODULE_1__["getRandomByte"])(9);
//If the Ip already exists, recurse to create a new one
if (ipExists(ip)) {
return createRandomIp();
}
return ip;
}
//Returns true if the IP already exists in one of the game's servers
function ipExists(ip) {
for (var property in _src_Server__WEBPACK_IMPORTED_MODULE_0__[/* AllServers */ "b"]) {
if (_src_Server__WEBPACK_IMPORTED_MODULE_0__[/* AllServers */ "b"].hasOwnProperty(property)) {
if (property == ip) {
return true;
}
}
}
return false;
}
/***/ }),
/* 58 */
/*!**********************************!*\
!*** ./src/CompanyManagement.js ***!
\**********************************/
/*! exports provided: Corporation */
/*! exports used: Corporation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Corporation; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Literature */ 78);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! decimal.js */ 31);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/uiHelpers/clearSelector */ 127);
/* harmony import */ var _utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
/* State */
var companyStates = ["START", "PURCHASE", "PRODUCTION", "SALE", "EXPORT"];
function CorporationState() {
this.state = 0;
}
CorporationState.prototype.nextState = function() {
if (this.state < 0 || this.state >= companyStates.length) {
this.state = 0;
}
++this.state;
if (this.state >= companyStates.length) {
this.state = 0;
}
}
CorporationState.prototype.getState = function() {
return companyStates[this.state];
}
CorporationState.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("CorporationState", this);
}
CorporationState.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(CorporationState, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.CorporationState = CorporationState;
/* Constants */
var TOTALSHARES = 1e9; //Total number of shares you have at your company
var CyclesPerMarketCycle = 75;
var CyclesPerIndustryStateCycle = CyclesPerMarketCycle / companyStates.length;
var SecsPerMarketCycle = CyclesPerMarketCycle / 5;
var Cities = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"];
var WarehouseInitialCost = 5e9; //Initial purchase cost of warehouse
var WarehouseInitialSize = 100;
var WarehouseUpgradeBaseCost = 1e9;
var OfficeInitialCost = 4e9;
var OfficeInitialSize = 3;
var OfficeUpgradeBaseCost = 1e9;
var BribeThreshold = 100e12; //Money needed to be able to bribe for faction rep
var BribeToRepRatio = 1e9; //Bribe Value divided by this = rep gain
var ProductProductionCostRatio = 5; //Ratio of material cost of a product to its production cost
function Material(params={}) {
this.name = params.name ? params.name : "";
this.qty = 0; //Quantity
this.qlt = 0; //Quality, unbounded
this.dmd = 0; //Demand, 0-100?
this.dmdR = 0; //Range of possible demand
this.cmp = 0; //Competition, 0-100
this.cmpR = 0; //Range of possible competition
this.mv = 0; //Maximum Volatility of stats
//Markup. Determines how high of a price you can charge on the material
//compared to the market price (bCost) based on quality
//Quality is divided by this to determine markup limits
//e.g if mku is 10 and quality is 100 then you can mark up prices by 100/10 = 10
//without consequences
this.mku = 0;
this.buy = 0; //How much of this material is being bought per second
this.sll = 0; //How much of this material is being sold per second
this.prd = 0; //How much of this material is being produced per second
this.exp = []; //Exports of this material to another warehouse/industry
this.totalExp = 0; //Total export amount for last cycle
this.imp = 0;
this.bCost = 0; //$ Cost/sec to buy material
this.sCost = 0; //$ Cost/sec to sell material
//[Whether production/sale is limited, limit amount]
this.prdman = [false, 0]; //Production for this material is manually limited
this.sllman = [false, 0]; //Sale of this material is manually limited
this.init();
}
Material.prototype.init = function(mats={}) {
switch(this.name) {
case "Water":
this.dmd = 75; this.dmdR = [65, 85];
this.cmp = 50; this.cmpR = [40, 60];
this.bCost = 1000; this.mv = 0.2;
this.mku = 6;
break;
case "Energy":
this.dmd = 90; this.dmdR = [80, 100];
this.cmp = 80; this.cmpR = [65, 95];
this.bCost = 1500; this.mv = 0.2;
this.mku = 6;
break;
case "Food":
this.dmd = 80; this.dmdR = [70, 90];
this.cmp = 60; this.cmpR = [35, 85];
this.bCost = 5000; this.mv = 1;
this.mku = 3;
break;
case "Plants":
this.dmd = 70; this.dmdR = [20, 90];
this.cmp = 50; this.cmpR = [30, 70];
this.bCost = 3000; this.mv = 0.6;
this.mku = 3.75;
break;
case "Metal":
this.dmd = 80; this.dmdR = [75, 85];
this.cmp = 70; this.cmpR = [60, 80];
this.bCost = 2650; this.mv = 1;
this.mku = 6;
break;
case "Hardware":
this.dmd = 85; this.dmdR = [80, 90];
this.cmp = 80; this.cmpR = [65, 95];
this.bCost = 4000; this.mv = 0.5; //Less mv bc its processed twice
this.mku = 1;
break;
case "Chemicals":
this.dmd = 55; this.dmdR = [40, 70];
this.cmp = 60; this.cmpR = [40, 80];
this.bCost = 6750; this.mv = 1.2;
this.mku = 2;
break;
case "Real Estate":
this.dmd = 50; this.dmdR = [5, 100];
this.cmp = 50; this.cmpR = [25, 75];
this.bCost = 16e3; this.mv = 1.5; //Less mv bc its processed twice
this.mku = 1.5;
break;
case "Drugs":
this.dmd = 60; this.dmdR = [45, 75];
this.cmp = 70; this.cmpR = [40, 100];
this.bCost = 8e3; this.mv = 1.6;
this.mku = 1;
break;
case "Robots":
this.dmd = 90; this.dmdR = [80, 100];
this.cmp = 90; this.cmpR = [80, 100];
this.bCost = 20e3; this.mv = 0.5; //Less mv bc its processed twice
this.mku = 1;
break;
case "AI Cores":
this.dmd = 90; this.dmdR = [80, 100];
this.cmp = 90; this.cmpR = [80, 100];
this.bCost = 27e3; this.mv = 0.8; //Less mv bc its processed twice
this.mku = 0.5;
break;
case "Scientific Research":
break;
default:
console.log("Invalid material type in init(): " + this.name);
break;
}
}
//Process change in demand, competition, and buy cost of this material
Material.prototype.processMarket = function() {
//This 1st random check determines whether competition increases or decreases
//More competition = lower market price
var v = (Math.random() * this.mv) / 100;
var pv = (Math.random() * this.mv) / 300;
if (Math.random() < 0.42) {
this.cmp *= (1+v);
if (this.cmp > this.cmpR[1]) {this.cmp = this.cmpR[1]};
this.bCost *= (1-pv);
} else {
this.cmp *= (1-v);
if (this.cmp < this.cmpR[0]) {this.cmp = this.cmpR[0];}
this.bCost *= (1+pv);
}
//This 2nd random check determines whether demand increases or decreases
//More demand = higher market price
v = (Math.random() * this.mv) / 100;
pv = (Math.random() * this.mv) / 300;
if (Math.random() < 0.45) {
this.dmd *= (1+v);
if (this.dmd > this.dmdR[1]) {this.dmd = this.dmdR[1];}
this.bCost *= (1+pv);
} else {
this.dmd *= (1-v);
if (this.dmd < this.dmdR[0]) {this.dmd = this.dmdR[0];}
this.bCost *= (1-pv);
}
}
Material.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Material", this);
}
Material.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Material, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Material = Material;
//Map of material (by name) to their sizes (how much space it takes in warehouse)
let MaterialSizes = {
Water: 0.05,
Energy: 0.01,
Food: 0.03,
Plants: 0.05,
Metal: 0.1,
Hardware: 0.06,
Chemicals: 0.05,
Drugs: 0.02,
Robots: 0.5,
AICores: 0.1,
RealEstate: 0,
}
function Product(params={}) {
this.name = params.name ? params.name : 0;
this.dmd = params.demand ? params.demand : 0;
this.cmp = params.competition ? params.competition : 0;
this.mku = params.markup ? params.markup : 0;
this.pCost = 0; //An estimate of how much money it costs to make this
this.sCost = 0; //How much this is selling for
//Variables for creation of product
this.fin = false; //Finished being created
this.prog = 0; //0-100% created
this.createCity = params.createCity ? params.createCity : ""; // City in which the product is being created
this.designCost = params.designCost ? params.designCost : 0;
this.advCost = params.advCost ? params.advCost : 0;
//Aggregate score for a product's 'rating' based on the other properties below
//The weighting of the other properties (performance, durability)
//differs between industries
this.rat = 0;
this.qlt = params.quality ? params.quality : 0;
this.per = params.performance ? params.performance : 0;
this.dur = params.durability ? params.durability : 0;
this.rel = params.reliability ? params.reliability : 0;
this.aes = params.aesthetics ? params.aesthetics : 0;
this.fea = params.features ? params.features : 0;
//Data refers to the production, sale, and quantity of the products
//These values are specific to a city
//The data is [qty, prod, sell]
this.data = {
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Aevum]: [0, 0, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Chongqing]: [0, 0, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12]: [0, 0, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].NewTokyo]: [0, 0, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Ishima]: [0, 0, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Volhaven]: [0, 0, 0],
}
//Only applies for location-based products like restaurants/hospitals
this.loc = params.loc ? params.loc : 0;
//How much space it takes in the warehouse. Not applicable for all products
this.siz = params.size ? params.size : 0;
//Material requirements. An object that maps the name of a material to how much it requires
//to make 1 unit of the product.
this.reqMats = params.req ? params.req : {};
//[Whether production/sale is limited, limit amount]
this.prdman = {
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Aevum]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Chongqing]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].NewTokyo]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Ishima]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Volhaven]: [false, 0],
}
this.sllman = {
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Aevum]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Chongqing]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].NewTokyo]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Ishima]: [false, 0],
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Volhaven]: [false, 0],
}
}
//empWorkMult is a multiplier that increases progress rate based on
//productivity of employees
Product.prototype.createProduct = function(marketCycles=1, empWorkMult=1) {
if (this.fin) {return;}
this.prog += (marketCycles * .01 * empWorkMult);
}
//'industry' is a reference to the industry that makes the product
Product.prototype.finishProduct = function(employeeProd, industry) {
this.fin = true;
//Calculate properties
var progrMult = this.prog / 100;
var engrRatio = employeeProd[EmployeePositions.Engineer] / employeeProd["total"],
mgmtRatio = employeeProd[EmployeePositions.Management] / employeeProd["total"],
rndRatio = employeeProd[EmployeePositions.RandD] / employeeProd["total"],
opsRatio = employeeProd[EmployeePositions.Operations] / employeeProd["total"],
busRatio = employeeProd[EmployeePositions.Business] / employeeProd["total"];
var designMult = 1 + (Math.pow(this.designCost, 0.1) / 100);
console.log("designMult: " + designMult);
var balanceMult = (1.2 * engrRatio) + (0.9 * mgmtRatio) + (1.3 * rndRatio) +
(1.5 * opsRatio) + (busRatio);
var sciMult = 1 + (Math.pow(industry.sciResearch.qty, industry.sciFac) / 800);
var totalMult = progrMult * balanceMult * designMult * sciMult;
this.qlt = totalMult * ((0.10 * employeeProd[EmployeePositions.Engineer]) +
(0.05 * employeeProd[EmployeePositions.Management]) +
(0.05 * employeeProd[EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions.Operations]) +
(0.02 * employeeProd[EmployeePositions.Business]));
this.per = totalMult * ((0.15 * employeeProd[EmployeePositions.Engineer]) +
(0.02 * employeeProd[EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions.Operations]) +
(0.02 * employeeProd[EmployeePositions.Business]));
this.dur = totalMult * ((0.05 * employeeProd[EmployeePositions.Engineer]) +
(0.02 * employeeProd[EmployeePositions.Management]) +
(0.08 * employeeProd[EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions.Operations]) +
(0.05 * employeeProd[EmployeePositions.Business]));
this.rel = totalMult * ((0.02 * employeeProd[EmployeePositions.Engineer]) +
(0.08 * employeeProd[EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions.Operations]) +
(0.08 * employeeProd[EmployeePositions.Business]));
this.aes = totalMult * ((0.00 * employeeProd[EmployeePositions.Engineer]) +
(0.08 * employeeProd[EmployeePositions.Management]) +
(0.05 * employeeProd[EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions.Operations]) +
(0.10 * employeeProd[EmployeePositions.Business]));
this.fea = totalMult * ((0.08 * employeeProd[EmployeePositions.Engineer]) +
(0.05 * employeeProd[EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions.Operations]) +
(0.05 * employeeProd[EmployeePositions.Business]));
this.calculateRating(industry);
var advMult = 1 + (Math.pow(this.advCost, 0.1) / 100);
this.mku = 100 / (advMult * Math.pow((this.qlt + 0.001), 0.65) * (busRatio + mgmtRatio));
this.dmd = industry.awareness === 0 ? 20 : Math.min(100, advMult * (100 * (industry.popularity / industry.awareness)));
this.cmp = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(0, 70);
//Calculate the product's required materials
//For now, just set it to be the same as the requirements to make materials
for (var matName in industry.reqMats) {
if (industry.reqMats.hasOwnProperty(matName)) {
this.reqMats[matName] = industry.reqMats[matName];
}
}
//Calculate the product's size
//For now, just set it to be the same size as the requirements to make materials
this.siz = 0;
for (var matName in industry.reqMats) {
this.siz += MaterialSizes[matName] * industry.reqMats[matName];
}
//Delete unneeded variables
delete this.prog;
delete this.createCity;
delete this.designCost;
delete this.advCost;
}
Product.prototype.calculateRating = function(industry) {
var weights = ProductRatingWeights[industry.type];
if (weights == null) {
console.log("ERROR: Could not find product rating weights for: " + industry);
return;
}
this.rat = 0;
this.rat += weights.Quality ? this.qlt * weights.Quality : 0;
this.rat += weights.Performance ? this.per * weights.Performance : 0;
this.rat += weights.Durability ? this.dur * weights.Durability : 0;
this.rat += weights.Reliability ? this.rel * weights.Reliability : 0;
this.rat += weights.Aesthetics ? this.aes * weights.Aesthetics : 0;
this.rat += weights.Features ? this.fea * weights.Features : 0;
}
Product.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Product", this);
}
Product.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Product, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Product = Product;
var 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",
}
var 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,
}
var IndustryDescriptions = {
Energy: "Engage in the production and distribution of energy.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Energy, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Utilities: "Distributes water and provides wastewater services.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Utilities, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Agriculture: "Cultive crops and breed livestock to produce food.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Agriculture, "$0.000a") + "<br>" +
"Recommended starting Industry: YES",
Fishing: "Produce food through the breeding and processing of fish and fish products<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Fishing, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Mining: "Extract and process metals from the earth.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Mining, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Food: "Create your own restaurants all around the world.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Food, "$0.000a") + "<br>" +
"Recommended starting Industry: YES",
Tobacco: "Create and distribute tobacco and tobacco-related products.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Tobacco, "$0.000a") + "<br>" +
"Recommended starting Industry: YES",
Chemical: "Product industrial chemicals<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Chemical, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Pharmaceutical: "Discover, develop, and create new pharmaceutical drugs.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Pharmaceutical, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Computer: "Develop and manufacture new computer hardware and networking infrastructures.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Computer, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Robotics: "Develop and create robots.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Robotics, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
Software: "Develop computer software and create AI Cores.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Software, "$0.000a") + "<br>" +
"Recommended starting Industry: YES",
Healthcare: "Create and manage hospitals.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.Healthcare, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
RealEstate: "Develop and manage real estate properties.<br><br>" +
"Starting cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(IndustryStartingCosts.RealEstate, "$0.000a") + "<br>" +
"Recommended starting Industry: NO",
}
var ProductRatingWeights = {
[Industries.Food]: {
Quality: 0.7,
Durability: 0.1,
Aesthetics: 0.2,
},
[Industries.Tobacco]: {
Quality: 0.4,
Durability: 0.2,
Reliability: 0.2,
Aesthetics: 0.2,
},
[Industries.Pharmaceutical]: {
Quality: 0.2,
Performance: 0.2,
Durability: 0.1,
Reliability: 0.3,
Features: 0.2,
},
[Industries.Computer]: {
Quality: 0.15,
Performance: 0.25,
Durability: 0.25,
Reliability: 0.2,
Aesthetics: 0.05,
Features: 0.1,
},
"Computer" : { //Repeat
Quality: 0.15,
Performance: 0.25,
Durability: 0.25,
Reliability: 0.2,
Aesthetics: 0.05,
Features: 0.1,
},
[Industries.Robotics]: {
Quality: 0.1,
Performance: 0.2,
Durability: 0.2,
Reliability: 0.2,
Aesthetics: 0.1,
Features: 0.2,
},
[Industries.Software]: {
Quality: 0.2,
Performance: 0.2,
Reliability: 0.2,
Durability: 0.2,
Features: 0.2,
},
[Industries.Healthcare]: {
Quality: 0.4,
Performance: 0.1,
Durability: 0.1,
Reliability: 0.3,
Features: 0.1,
},
[Industries.RealEstate]: {
Quality: 0.2,
Durability: 0.25,
Reliability: 0.1,
Aesthetics: 0.35,
Features: 0.1,
}
}
//Industry upgrades
//The structure is:
// [index in array, base price, price mult, benefit mult (if applicable), name, desc]
var IndustryUpgrades = {
"0": [0, 500e3, 1, 1.05,
"Coffee", "Provide your employees with coffee, increasing their energy by 5%."],
"1": [1, 1e9, 1.06, 1.03,
"AdVert.Inc", "Hire AdVert.Inc to advertise your company. Each level of " +
"this upgrade grants your company a static increase of 3 and 1 to its awareness and " +
"popularity, respectively. It will then increase your company's awareness by 1%, and its popularity " +
"by a random percentage between 1% and 3%. These effects are increased by other upgrades " +
"that increase the power of your advertising."]
}
var empManualAssignmentModeActive = false;
function Industry(params={}) {
this.offices = { //Maps locations to offices. 0 if no office at that location
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Aevum]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Chongqing]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12]: new OfficeSpace({
loc:_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12,
size:OfficeInitialSize,
}),
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].NewTokyo]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Ishima]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Volhaven]: 0
};
this.warehouses = { //Maps locations to warehouses. 0 if no warehouse at that location
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Aevum]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Chonqing]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12]: new Warehouse({
loc:_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12,
size: WarehouseInitialSize,
}),
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].NewTokyo]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Ishima]: 0,
[_Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Volhaven]: 0
};
this.name = params.name ? params.name : 0;
this.type = params.type ? params.type : 0;
this.sciResearch = new Material({name: "Scientific Research"});
//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_5__[/* default */ "a"](0);
this.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
this.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
//Upgrades
var numUpgrades = Object.keys(IndustryUpgrades).length;
this.upgrades = Array(numUpgrades).fill(0);
this.state = "START";
this.newInd = true;
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 = IndustryStartingCosts[this.type];
switch (this.type) {
case 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 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 Industries.Agriculture:
this.reFac = 0.75;
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 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 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 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 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 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 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 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.5,
"Energy": 1,
}
this.prodMats = ["Hardware"];
this.makesProducts = true;
break;
case 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 Industries.Software:
this.sciFac = 0.62;
this.advFac = 0.16;
this.hwFac = 0.25;
this.reFac = 0.1;
this.aiFac = 0.1;
this.robFac = 0.05;
this.reqMats = {
"Hardware": 0.5,
"Energy": 1,
}
this.prodMats = ["AICores"];
this.makesProducts = true;
break;
case 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 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": 20,
"Energy": 10,
"Water": 10,
"Hardware": 5
}
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 Industries.Food:
return "create and manage restaurants";
break;
case Industries.Tobacco:
return "create tobacco and tobacco-related products";
break;
case Industries.Pharmaceutical:
return "develop new pharmaceutical drugs";
break;
case Industries.Computer:
case "Computer":
return "create new computer hardware and networking infrastructures";
break;
case Industries.Robotics:
return "build specialized robots and robot-related products";
break;
case Industries.Software:
return "develop computer software";
break;
case Industries.Healthcare:
return "build and manage hospitals";
break;
case Industries.RealEstate:
return "develop and manage real estate properties";
break;
default:
console.log("ERROR: Invalid industry type in Industry.getProductDescriptionText");
return "";
}
}
//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)) {
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) {
//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_13__["formatNumber"])(prod.data[warehouse.loc][0] * prod.siz, 0) + "<br>");
}
}
}
}
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_7__["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_5__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* 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_5__[/* default */ "a"](0);
this.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* 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.hasOwnProperty(officeLoc) &&
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) {
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 (var name in this.products) {
if (this.products.hasOwnProperty(name)) {
var product = this.products[name];
var change = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(1, 3) * 0.0004;
if (this.type === Industries.Pharmaceutical || this.type === Industries.Software ||
this.type === 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 (var i = 0; i < Cities.length; ++i) {
var city = Cities[i], office = this.offices[city];
if (!(this.warehouses[city] instanceof 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 (var i = 0; i < Cities.length; ++i) {
var city = Cities[i], office = this.offices[city];
if (this.warehouses[city] instanceof 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[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 * company.getProductionMultiplier(), 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 (var tmp = 0; tmp < this.prodMats.length; ++tmp) {
totalMatSize += (MaterialSizes[this.prodMats[tmp]]);
}
for (var reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
var normQty = this.reqMats[reqMatName];
totalMatSize -= (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 (var reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
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 (var j = 0; j < this.prodMats.length; ++j) {
warehouse.materials[this.prodMats[j]].qty += (prod * producableFrac);
warehouse.materials[this.prodMats[j]].qlt =
(office.employeeProd[EmployeePositions.Engineer] / 100 +
Math.pow(this.sciResearch.qty, this.sciFac) +
Math.pow(warehouse.materials["AICores"].qty, this.aiFac) / 10e3);
}
} else {
for (var reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
warehouse.materials[reqMatName].prd = 0;
}
}
}
//Per second
var fooProd = prod * producableFrac / (SecsPerMarketCycle * marketCycles);
for (var 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 (var reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
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;
}
var mat = warehouse.materials[matName];
var sCost;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["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)
var markup = 1, markupLimit = mat.qlt / mat.mku;
if (sCost > mat.bCost) {
//Penalty if difference between sCost and bCost is greater than markup limit
if ((sCost - mat.bCost) > markupLimit) {
markup = markupLimit / (sCost - mat.bCost);
}
} 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 businessFactor = 1 + (office.employeeProd[EmployeePositions.Business] / office.employeeProd["total"]);
var businessFactor = this.getBusinessFactor(office); //Business employee productivity
var advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
var marketFactor = this.getMarketFactor(mat); //Competition + demand
var maxSell = (mat.qlt + .001) * marketFactor * markup * businessFactor *
company.getSalesMultiplier() * advertisingFactor;
var sellAmt;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["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_7__["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_7__["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_7__["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)) {
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[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 += (.005 * Math.pow(office.employeeProd[EmployeePositions.RandD], 0.5)
* company.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 (var prodName in this.products) {
if (this.products.hasOwnProperty(prodName)) {
var prod = this.products[prodName];
if (!prod.fin) {
var city = prod.createCity, office = this.offices[city];
var total = office.employeeProd[EmployeePositions.Operations] +
office.employeeProd[EmployeePositions.Engineer] +
office.employeeProd[EmployeePositions.Management], ratio;
if (total === 0) {
ratio = 0;
} else {
ratio = office.employeeProd[EmployeePositions.Engineer] / total +
office.employeeProd[EmployeePositions.Operations] / total +
office.employeeProd[EmployeePositions.Management] / total;
}
prod.createProduct(marketCycles, ratio * Math.pow(total, 0.29));
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 && prod.fin) {
revenue += this.processProduct(marketCycles, prod, corporation);
}
}
}
return [revenue, expenses];
}
//Processes FINISHED products
Industry.prototype.processProduct = function(marketCycles=1, product, corporation) {
var totalProfit = 0;
for (var i = 0; i < Cities.length; ++i) {
var city = Cities[i], office = this.offices[city], warehouse = this.warehouses[city];
if (warehouse instanceof 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, 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[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;
//Calculate Sale Cost (sCost), which could be dynamically evaluated
var sCost;
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["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, markupLimit = product.rat / product.mku;
if (sCost > product.pCost) {
if ((sCost - product.pCost) > markupLimit) {
markup = markupLimit / (sCost - product.pCost);
}
}
var businessFactor = this.getBusinessFactor(office); //Business employee productivity
var advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
var marketFactor = this.getMarketFactor(product); //Competition + demand
var maxSell = 0.5 * Math.pow(product.rat, 0.65) * marketFactor * corporation.getSalesMultiplier() *
Math.pow(markup, 2) * businessFactor * advertisingFactor;
var sellAmt;
if (product.sllman[city][0] && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["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_7__["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 {
//Backwards compatibility, -1 = 0
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, parentRefs) {
var company = parentRefs.company, industry = parentRefs.industry;
for (var productName in this.products) {
if (this.products.hasOwnProperty(productName)) {
if (product === this.products[productName]) {
delete this.products[productName];
company.updateUIContent();
}
}
}
}
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 (var i = 0; i < office.employees.length; ++i) {
office.employees[i].ene = Math.min(office.employees[i].ene * 1.05, 100);
}
break;
case 1: //AdVert.Inc,
var advMult = corporation.getAdvertisingMultiplier();
this.awareness += (3 * advMult);
this.popularity += (1 * advMult);
this.awareness *= (1.01 * advMult);
this.popularity *= ((1 + Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["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) {
var total = office.employeeProd[EmployeePositions.Operations] +
office.employeeProd[EmployeePositions.Engineer] +
office.employeeProd[EmployeePositions.Management], ratio;
if (total === 0) {
ratio = 0;
} else {
ratio = (office.employeeProd[EmployeePositions.Operations] / total) *
(office.employeeProd[EmployeePositions.Engineer] / total) *
(office.employeeProd[EmployeePositions.Management] / total);
ratio = Math.max(0.01, ratio); //Minimum ratio value if you have employees
}
if (params && params.forProduct) {
return ratio * Math.pow(total, 0.2);
} else {
return 2 * ratio * Math.pow(total, 0.3);
}
}
//Returns a multiplier based on the office' 'Business' employees that affects sales
Industry.prototype.getBusinessFactor = function(office) {
var ratioMult = 1;
if (office.employeeProd["total"] > 0) {
ratioMult = 1 + (office.employeeProd[EmployeePositions.Business] / office.employeeProd["total"]);
}
return ratioMult * Math.pow(1 + office.employeeProd[EmployeePositions.Business], 0.15);
}
//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 mat.dmd * (100 - mat.cmp)/100;
}
Industry.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Industry", this);
}
Industry.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Industry, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Industry = Industry;
var EmployeePositions = {
Operations: "Operations",
Engineer: "Engineer",
Business: "Business",
Management: "Management",
RandD: "Research & Development",
Training:"Training",
Unassigned:"Unassigned",
}
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_14__["getRandomInt"])(50, 100);
this.hap = params.happiness ? params.happiness : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100);
this.ene = params.energy ? params.energy : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100);
this.age = params.age ? params.age : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(20, 50);
this.int = params.intelligence ? params.intelligence : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(10, 50);
this.cha = params.charisma ? params.charisma : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(10, 50);
this.exp = params.experience ? params.experience : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(10, 50);
this.cre = params.creativity ? params.creativity : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(10, 50);
this.eff = params.efficiency ? params.efficiency : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(10, 50);
this.sal = params.salary ? params.salary : Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(0.1, 5);
this.pro = 0; //Productivity, This is calculated
this.loc = params.loc ? params.loc : "";
this.pos = EmployeePositions.Unassigned;
}
//Returns the amount the employee needs to be paid
Employee.prototype.process = function(marketCycles=1, office) {
var gain = 0.001 * marketCycles,
det = gain * Math.random();
this.age += gain;
this.exp += gain;
if (this.age > 150) {
this.int -= det;
this.eff -= det;
this.cha -= det;
}
//Training
var trainingEff = gain * Math.random();
if (this.pos === EmployeePositions.Training) {
//To increase creativity and intelligence special upgrades are needed
this.cha += trainingEff;
this.exp += trainingEff;
this.eff += trainingEff;
}
//Weight based on how full office is
//Too many employees = more likely to decrease energy and happiness
var officeCapacityWeight = 0.5 * (office.employees.length / office.size - 0.5);
if (Math.random() < 0.5 - officeCapacityWeight) {
this.ene += det;
this.hap += det;
} else {
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) {
var effCre = this.cre * corporation.getEmployeeCreMultiplier(),
effCha = this.cha * corporation.getEmployeeChaMultiplier(),
effInt = this.int * corporation.getEmployeeIntMultiplier(),
effEff = this.eff * corporation.getEmployeeEffMultiplier();
var prodBase = this.mor * this.hap * this.ene * 1e-6, prodMult;
switch(this.pos) {
//Calculate productivity based on position. This is multipled by prodBase
//to get final value
case EmployeePositions.Operations:
prodMult = (0.6 * effInt) + (0.1 * effCha) + (this.exp) +
(0.5 * effCre) + (effEff);
break;
case EmployeePositions.Engineer:
prodMult = (effInt) + (0.1 * effCha) + (1.5 * this.exp) +
(effEff);
break;
case EmployeePositions.Business:
prodMult = (0.4 * effInt) + (effCha) + (0.5 * this.exp);
break;
case EmployeePositions.Management:
prodMult = (2 * effCha) + (this.exp) + (0.2 * effCre) +
(0.7 * effEff);
break;
case EmployeePositions.RandD:
prodMult = (1.5 * effInt) + (0.8 * this.exp) + (effCre) +
(0.5 * effEff);
break;
case EmployeePositions.Unassigned:
case 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) {
var effCre = this.cre * corporation.getEmployeeCreMultiplier(),
effCha = this.cha * corporation.getEmployeeChaMultiplier(),
effInt = this.int * corporation.getEmployeeIntMultiplier(),
effEff = this.eff * corporation.getEmployeeEffMultiplier();
panel.style.color = "white";
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
id:"cmpy-mgmt-employee-" + this.name + "-panel-text",
innerHTML:"Morale: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.mor, 3) + "<br>" +
"Happiness: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.hap, 3) + "<br>" +
"Energy: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.ene, 3) + "<br>" +
"Age: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.age, 3) + "<br>" +
"Intelligence: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effInt, 3) + "<br>" +
"Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effCha, 3) + "<br>" +
"Experience: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.exp, 3) + "<br>" +
"Creativity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effCre, 3) + "<br>" +
"Efficiency: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effEff, 3) + "<br>" +
"Salary: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.sal, "$0.000a") + "/ s<br>",
}));
//Selector for employee position
var selector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {});
for (var key in EmployeePositions) {
if (EmployeePositions.hasOwnProperty(key)) {
selector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text: EmployeePositions[key],
value: 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.updateUI = function(panel, corporation) {
var effCre = this.cre * corporation.getEmployeeCreMultiplier(),
effCha = this.cha * corporation.getEmployeeChaMultiplier(),
effInt = this.int * corporation.getEmployeeIntMultiplier(),
effEff = this.eff * corporation.getEmployeeEffMultiplier();
if (panel == null) {
console.log("ERROR: Employee.updateUI() called with null panel");
return;
}
var text = document.getElementById("cmpy-mgmt-employee-" + this.name + "-panel-text");
if (text == null) {
return this.createUI(panel);
}
text.innerHTML = "Morale: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.mor, 3) + "<br>" +
"Happiness: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.hap, 3) + "<br>" +
"Energy: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.ene, 3) + "<br>" +
"Age: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.age, 3) + "<br>" +
"Intelligence: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effInt, 3) + "<br>" +
"Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effCha, 3) + "<br>" +
"Experience: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.exp, 3) + "<br>" +
"Creativity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effCre, 3) + "<br>" +
"Efficiency: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(effEff, 3) + "<br>" +
"Salary: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.sal, "$0.000a") + "/ s<br>";
}
Employee.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Employee", this);
}
Employee.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Employee, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["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;
this.minEne = 0; //Minimum energy of employees, based on office
this.minHap = 0; //Minimum happiness of employees, based on office.
this.employees = [];
this.employeeProd = {
[EmployeePositions.Operations]: 0,
[EmployeePositions.Engineer]: 0,
[EmployeePositions.Business]: 0,
[EmployeePositions.Management]: 0,
[EmployeePositions.RandD]: 0,
total: 0,
};
}
OfficeSpace.prototype.process = function(marketCycles=1, parentRefs) {
var corporation = parentRefs.corporation, industry = parentRefs.industry;
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);
}
var salaryPaid = 0;
for (var i = 0; i < this.employees.length; ++i) {
var emp = this.employees[i];
emp.mor *= perfMult;
emp.hap *= perfMult;
emp.ene *= perfMult;
var salary = emp.process(marketCycles, this);
salaryPaid += salary;
}
this.calculateEmployeeProductivity(marketCycles, corporation);
return salaryPaid;
}
OfficeSpace.prototype.calculateEmployeeProductivity = function(marketCycles=1, corporation) {
//Reset
for (var name in this.employeeProd) {
if (this.employeeProd.hasOwnProperty(name)) {
this.employeeProd[name] = 0;
}
}
var total = 0;
for (var i = 0; i < this.employees.length; ++i) {
var employee = this.employees[i];
var prod = employee.calculateProductivity(corporation);
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.division;
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_14__["getRandomInt"])(25, 50)/100,
mult2 = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(51, 75)/100,
mult3 = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(76, 100)/100;
var int = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
cha = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
exp = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
cre = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
eff = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
sal = 2.2 * (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_10__["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_10__["createElement"])("div", {
class:"cmpy-mgmt-find-employee-option",
innerHTML: "Intelligence: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(employee.int, 1) + "<br>" +
"Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(employee.cha, 1) + "<br>" +
"Experience: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(employee.exp, 1) + "<br>" +
"Creativity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(employee.cre, 1) + "<br>" +
"Efficiency: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(employee.eff, 1) + "<br>" +
"Salary: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(employee.sal, '$0.000a') + " \ s<br>",
clickListener:()=>{
office.hireEmployee(employee, parentRefs);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])("cmpy-mgmt-hire-employee-popup");
return false;
}
});
return div;
};
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Cancel",
float:"right",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["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_11__["createPopup"])("cmpy-mgmt-hire-employee-popup", elems);
}
OfficeSpace.prototype.hireEmployee = function(employee, parentRefs) {
var company = parentRefs.corporation, division = parentRefs.division;
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxGetYesButton */ "j"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerHTML = "Hire";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", ()=>{
var name = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxGetInput */ "h"])();
for (var i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["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.displayDivisionContent(division, currentCityUi);
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxClose */ "f"])();
});
noBtn.addEventListener("click", ()=>{
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxClose */ "f"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoTxtInpBoxCreate */ "g"])("Give your employee a nickname!");
}
OfficeSpace.prototype.hireRandomEmployee = function(parentRefs) {
var company = parentRefs.corporation, division = parentRefs.division;
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_14__["getRandomInt"])(76, 100)/100;
var int = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
cha = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
exp = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
cre = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
eff = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_14__["getRandomInt"])(50, 100),
sal = 2.2 * (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_13__["generateRandomString"])(7);
for (var i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
return this.hireRandomEmployee(parentRefs);
}
}
emp.name = name;
this.employees.push(emp);
company.displayDivisionContent(division, currentCityUi);
}
//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.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.Unassigned;
return true;
}
}
return false;
}
OfficeSpace.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("OfficeSpace", this);
}
OfficeSpace.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(OfficeSpace, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.OfficeSpace = OfficeSpace;
function Warehouse(params={}) {
this.loc = params.loc ? params.loc : "";
this.size = params.size ? params.size : 0;
this.level = 0;
this.sizeUsed = 0;
this.smartSupplyEnabled = false; //Whether or not smart supply is enabled
this.breakdown = "";
//Stores the amount of product to be produced. Used for Smart Supply unlock.
//The production tracked by smart supply is always based on the previous cycle,
//so it will always trail the "true" production by 1 cycle
this.smartSupplyStore = 0;
this.materials = {
Water: new Material({name: "Water"}),
Energy: new Material({name: "Energy"}),
Food: new Material({name: "Food"}),
Plants: new Material({name: "Plants"}),
Metal: new Material({name: "Metal"}),
Hardware: new Material({name: "Hardware"}),
Chemicals: new Material({name: "Chemicals"}),
Drugs: new Material({name: "Drugs"}),
Robots: new Material({name: "Robots"}),
AICores: new Material({name: "AI Cores"}),
RealEstate: new Material({name: "Real Estate"})
}
}
Warehouse.prototype.updateMaterialSizeUsed = function() {
this.sizeUsed = 0;
this.breakdown = "";
for (var matName in this.materials) {
if (this.materials.hasOwnProperty(matName)) {
var mat = this.materials[matName];
if (MaterialSizes.hasOwnProperty(matName)) {
this.sizeUsed += (mat.qty * MaterialSizes[matName]);
if (mat.qty > 0) {
this.breakdown += (matName + ": " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.qty * MaterialSizes[matName], 0) + "<br>");
}
}
}
}
if (this.sizeUsed > this.size) {
console.log("ERROR: Warehouse size used greater than capacity, something went wrong");
}
}
Warehouse.prototype.updateSize = function(corporation) {
//Backwards compatibility
if (this.level == null || this.level === 0) {
this.level = Math.round(this.size / 100);
}
this.size = (this.level * 100) * corporation.getStorageMultiplier();
}
Warehouse.prototype.createUI = function(parentRefs) {
if (parentRefs.company == null || parentRefs.industry == null) {
console.log("ERROR: Warehouse.createUI called without parentRefs.company or parentRefs.industry");
return;
}
var company = parentRefs.company, industry = parentRefs.industry;
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(industryWarehousePanel);
industryWarehouseStorageText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
display:"inline-block", class:"tooltip",
color: this.sizeUsed >= this.size ? "red" : "white",
});
industryWarehousePanel.appendChild(industryWarehouseStorageText);
//Upgrade warehouse size button
var upgradeCost = WarehouseUpgradeBaseCost * Math.pow(1.07, this.level+1);
industryWarehouseUpgradeSizeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Upgrade Warehouse Size - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(upgradeCost, '$0.000a'),
display:"inline-block",
class: company.funds.lt(upgradeCost) ? "a-link-button-inactive" : "a-link-button",
clickListener:()=>{
//Backwards compatibility
if (this.level == null || this.level === 0) {
this.level = Math.round(this.size / 100);
}
++this.level;
this.updateSize(company);
company.funds = company.funds.minus(upgradeCost);
this.createUI(parentRefs);
return;
}
});
industryWarehousePanel.appendChild(industryWarehouseUpgradeSizeButton);
//Material requirement text
var reqText = "This Industry uses [" + Object.keys(industry.reqMats).join(", ") +
"] in order to ";
if (industry.prodMats.length > 0) {
reqText += "produce [" + industry.prodMats.join(", ") + "] ";
if (industry.makesProducts) {
reqText += " and " + industry.getProductDescriptionText();
}
} else if (industry.makesProducts) {
reqText += industry.getProductDescriptionText();
}
reqText += "<br><br>To get started with production, purchase your required " +
"materials or import them from another of your company's divisions.<br><br>";
//Material ratio text for tooltip
var reqRatioText = "The exact requirements for production are:<br>";
for (var matName in industry.reqMats) {
if (industry.reqMats.hasOwnProperty(matName)) {
reqRatioText += (industry.reqMats[matName] + " " + matName + "<br>");
}
}
reqRatioText += "in order to create ";
if (industry.prodMats.length > 0) {
reqRatioText += "one of each produced Material (" + industry.prodMats.join(", ") + ") ";
if (industry.makesProducts) {
reqRatioText += "or to create one of its Products";
}
} else if (industry.makesProducts) {
reqRatioText += "one of its Products";
}
industryWarehousePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML:reqText, tooltipleft:reqRatioText
}));
//Current state
industryWarehouseStateText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p");
industryWarehousePanel.appendChild(industryWarehouseStateText);
//Smart Supply Enable/Disable
if (company.unlockUpgrades[1]) {
if (this.smartSupplyEnabled == null) {this.smartSupplyEnabled = false;}
var smartSupplyCheckboxId = "cmpy-mgmt-smart-supply-checkbox";
industryWarehousePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("label", {
for:smartSupplyCheckboxId, innerText:"Enable Smart Supply",
color:"white"
}));
industrySmartSupplyCheckbox = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"checkbox", id:smartSupplyCheckboxId, margin:"3px",
changeListener:()=>{
this.smartSupplyEnabled = industrySmartSupplyCheckbox.checked;
}
});
industrySmartSupplyCheckbox.checked = this.smartSupplyEnabled;
industryWarehousePanel.appendChild(industrySmartSupplyCheckbox);
}
//Materials
industryWarehousePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "<br>Materials:<br>",
}));
industryWarehouseMaterials = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("ul");
industryWarehousePanel.appendChild(industryWarehouseMaterials);
//Products
if (industry.makesProducts && Object.keys(industry.products).length > 0) {
industryWarehousePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "<br>Products:<br>",
}));
industryWarehouseProducts = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("ul");
industryWarehousePanel.appendChild(industryWarehouseProducts);
}
this.updateUI(parentRefs);
}
Warehouse.prototype.updateUI = function(parentRefs) {
if (parentRefs.company == null || parentRefs.industry == null) {
console.log("ERROR: Warehouse.updateUI called without parentRefs.company or parentRefs.industry");
return;
}
var company = parentRefs.company, industry = parentRefs.industry;
//Storage text
var storageText = "Storage: " +
(this.sizedUsed >= this.size ? Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.sizeUsed, 3) : Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.sizeUsed, 3)) +
"/" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.size, 3);
if (this.breakdown != null && this.breakdown != "") {
storageText += ("<span class='tooltiptext'>" +
this.breakdown + "</span>");
}
industryWarehouseStorageText.innerHTML = storageText;
//Upgrade warehouse size button
var upgradeCost = WarehouseUpgradeBaseCost * Math.pow(1.07, this.level+1);
if (company.funds.lt(upgradeCost)) {
industryWarehouseUpgradeSizeButton.className = "a-link-button-inactive";
} else {
industryWarehouseUpgradeSizeButton.className = "a-link-button";
}
//Current state
var stateText = "Current state: ";
switch(industry.state) {
case "START":
stateText += "Preparing...";
break;
case "PURCHASE":
stateText += "Purchasing materials...";
break;
case "PRODUCTION":
stateText += "Producing materials and/or products...";
break;
case "SALE":
stateText += "Selling materials and/or products...";
break;
case "EXPORT":
stateText += "Exporting materials and/or products...";
break;
default:
console.log("ERROR: Invalid state: " + industry.state);
break;
}
industryWarehouseStateText.innerText = stateText;
//Materials
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(industryWarehouseMaterials);
for (var matName in this.materials) {
if (this.materials.hasOwnProperty(matName) && this.materials[matName] instanceof Material) {
if (Object.keys(industry.reqMats).includes(matName) || industry.prodMats.includes(matName) ||
matName === "Hardware" || matName === "Robots" || matName === "AICores" ||
matName === "RealEstate") {
industryWarehouseMaterials.appendChild(this.createMaterialUI(this.materials[matName], matName, parentRefs));
}
}
}
//Products
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(industryWarehouseProducts);
if (industry.makesProducts && Object.keys(industry.products).length > 0) {
for (var productName in industry.products) {
if (industry.products.hasOwnProperty(productName) && industry.products[productName] instanceof Product) {
industryWarehouseProducts.appendChild(this.createProductUI(industry.products[productName], parentRefs));
}
}
}
}
Warehouse.prototype.createMaterialUI = function(mat, matName, parentRefs) {
if (parentRefs.company == null || parentRefs.industry == null) {
console.log("ERROR: Warehouse.createMaterialUI called without industry or company parent refs");
return;
}
var company = parentRefs.company, industry = parentRefs.industry;
var purchasePopupId = "cmpy-mgmt-material-purchase-popup",
sellPopupid = "cmpy-mgmt-material-sell-popup";
var div = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-warehouse-material-div",
});
var totalGain = mat.buy + mat.prd + mat.imp - mat.sll - mat.totalExp;
//If Market Research upgrades are unlocked, add competition and demand info
var cmpAndDmdText = "";
if (company.unlockUpgrades[2] === 1) {
cmpAndDmdText += "<br>Demand: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.dmd, 3);
}
if (company.unlockUpgrades[3] === 1) {
cmpAndDmdText += "<br>Competition: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.cmp, 3);
}
var innerTxt = "<p class='tooltip'>" + mat.name + ": " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.qty, 3) +
"(" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(totalGain, 3) + "/s)" +
"<span class='tooltiptext'>Buy: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.buy, 3) +
"/s<br>Prod: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.prd, 3) + "/s<br>Sell: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.sll, 3) +
"/s<br>Export: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.totalExp, 3) + "/s<br>Import: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.imp, 3) + "/s" + cmpAndDmdText + "</span></p><br>" +
"<p class='tooltip'>MP: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.bCost, 2) +
"<span class='tooltiptext'>Market Price: The price you would pay if " +
"you were to buy this material on the market</span></p><br>" +
"<p class='tooltip'>Quality: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.qlt, 2) +
"<span class='tooltiptext'>The quality of your material. Higher quality " +
"will lead to more sales</span></p>";
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: innerTxt,
id: "cmpy-mgmt-warehouse-" + matName + "-text", display:"inline-block",
}));
var buttonPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
display:"inline-block",
});
div.appendChild(buttonPanel);
//Button to set purchase amount
var tutorial = industry.newInd && Object.keys(industry.reqMats).includes(mat.name) &&
mat.buy === 0 && mat.imp === 0;
var buyButtonParams = {
innerText: "Buy (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.buy, 3) + ")", display:"inline-block",
class: tutorial ? "a-link-button flashing-button" : "a-link-button",
clickListener:()=>{
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Enter the amount of " + mat.name + " you would like " +
"to purchase per second. This material's cost changes constantly"
});
var confirmBtn;
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", value:mat.buy ? mat.buy : null, placeholder: "Purchase amount",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Confirm", class:"a-link-button",
clickListener:()=>{
if (isNaN(input.value)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid amount");
} else {
mat.buy = parseFloat(input.value);
if (isNaN(mat.buy)) {mat.buy = 0;}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(purchasePopupId);
this.createUI(parentRefs);
return false;
}
}
});
var clearButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Clear Purchase", class:"a-link-button",
clickListener:()=>{
mat.buy = 0;
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(purchasePopupId);
this.createUI(parentRefs);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(purchasePopupId);
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(purchasePopupId, [txt, input, confirmBtn, clearButton, cancelBtn]);
input.focus();
}
};
if (tutorial) {
buyButtonParams.tooltip = "Purchase your required materials to get production started!";
}
buttonPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", buyButtonParams));
//Button to manage exports
if (company.unlockUpgrades[0] === 1) { //Export unlock upgrade
function createExportPopup() {
var popupId = "cmpy-mgmt-export-popup";
var exportTxt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Select the industry and city to export this material to, as well as " +
"how much of this material to export per second. You can set the export " +
"amount to 'MAX' to export all of the materials in this warehouse."
});
//Select industry and city to export to
var citySelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {class: "dropdown"});
var industrySelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {
class: "dropdown",
changeListener:()=>{
var industryName = industrySelector.options[industrySelector.selectedIndex].value;
for (var foo = 0; foo < company.divisions.length; ++foo) {
if (company.divisions[foo].name == industryName) {
Object(_utils_uiHelpers_clearSelector__WEBPACK_IMPORTED_MODULE_8__["clearSelector"])(citySelector);
var selectedIndustry = company.divisions[foo];
for (var cityName in company.divisions[foo].warehouses) {
if (company.divisions[foo].warehouses[cityName] instanceof Warehouse) {
citySelector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
value:cityName, text:cityName,
}));
}
}
return;
}
}
}
});
for (var i = 0; i < company.divisions.length; ++i) {
industrySelector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text:company.divisions[i].name, value:company.divisions[i].name,
})); //End create element option
} //End for
var currIndustry = industrySelector.options[industrySelector.selectedIndex].value;
for (var i = 0; i < company.divisions.length; ++i) {
if (company.divisions[i].name == currIndustry) {
for (var cityName in company.divisions[i].warehouses) {
if (company.divisions[i].warehouses.hasOwnProperty(cityName) &&
company.divisions[i].warehouses[cityName] instanceof Warehouse) {
citySelector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
value:cityName, text:cityName,
}));
}
}
break;
}
}
//Select amount to export
var exportAmount = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
class: "text-input",
placeholder:"Export amount / s"
});
var exportBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Export",
clickListener:()=>{
var industryName = industrySelector.options[industrySelector.selectedIndex].text,
cityName = citySelector.options[citySelector.selectedIndex].text,
amt = exportAmount.value;
//Sanitize amt
var sanitizedAmt = amt.replace(/\s+/g, '');
sanitizedAmt = sanitizedAmt.replace(/[^-()\d/*+.MAX]/g, '');
var temp = sanitizedAmt.replace(/MAX/g, 1);
try {
temp = eval(temp);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid expression entered for export amount: " + e);
return false;
}
if (temp == null || isNaN(temp)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid amount entered for export");
return;
}
var exportObj = {ind:industryName, city:cityName, amt:sanitizedAmt};
mat.exp.push(exportObj);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var currExportsText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Below is a list of all current exports of this material from this warehouse. " +
"Clicking on one of the exports below will REMOVE that export."
});
var currExports = [];
for (var i = 0; i < mat.exp.length; ++i) {
(function(i, mat, currExports){
currExports.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-existing-export",
innerHTML: "Industry: " + mat.exp[i].ind + "<br>" +
"City: " + mat.exp[i].city + "<br>" +
"Amount/s: " + mat.exp[i].amt,
clickListener:()=>{
mat.exp.splice(i, 1); //Remove export object
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
createExportPopup();
}
}));
})(i, mat, currExports);
}
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [exportTxt, industrySelector, citySelector, exportAmount,
exportBtn, cancelBtn, currExportsText].concat(currExports));
}
buttonPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Export", display:"inline-block", class:"a-link-button",
clickListener:()=>{createExportPopup();}
}));
}
buttonPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {})); // Force line break
//Button to set sell amount
var innerTextString;
if (mat.sllman[0]) {
innerTextString = (mat.sllman[1] === -1 ? "Sell (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.sll, 3) + "/MAX)" :
"Sell (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.sll, 3) + "/" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.sllman[1], 3) + ")");
if (mat.sCost) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["isString"])(mat.sCost)) {
var sCost = mat.sCost.replace(/MP/g, mat.bCost);
innerTextString += " @ $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(eval(sCost), 2);
} else {
innerTextString += " @ $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(mat.sCost, 2);
}
}
} else {
innerTextString = "Sell (0.000/0.000)";
}
buttonPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText: innerTextString, display:"inline-block", class:"a-link-button",
clickListener:()=>{
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Enter the maximum amount of " + mat.name + " you would like " +
"to sell per second, as well as the price at which you would " +
"like to sell at.<br><br>" +
"If the sell amount is set to 0, then the material will not be sold. If the sell price " +
"if set to 0, then the material will be discarded<br><br>" +
"Setting the sell amount to 'MAX' will result in you always selling the " +
"maximum possible amount of the material.<br><br>" +
"When setting the sell amount, you can use the 'PROD' variable to designate a dynamically " +
"changing amount that depends on your production. For example, if you set the sell amount " +
"to 'PROD-5' then you will always sell 5 less of the material than you produce.<br><br>" +
"When setting the sell price, you can use the 'MP' variable to designate a dynamically " +
"changing price that depends on the market price. For example, if you set the sell price " +
"to 'MP+10' then it will always be sold at $10 above the market price.",
});
var br = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {});
var confirmBtn;
var inputQty = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"text", marginTop:"4px",
value: mat.sllman[1] ? mat.sllman[1] : null, placeholder: "Sell amount",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
var inputPx = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"text", marginTop:"4px",
value: mat.sCost ? mat.sCost : null, placeholder: "Sell price",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Confirm", class:"a-link-button", margin:"6px",
clickListener:()=>{
//Parse price
var cost = inputPx.value.replace(/\s+/g, '');
cost = cost.replace(/[^-()\d/*+.MP]/g, ''); //Sanitize cost
var temp = cost.replace(/MP/g, mat.bCost);
try {
temp = eval(temp);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field: " + e);
return false;
}
if (temp == null || isNaN(temp)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field");
return false;
}
if (cost.includes("MP")) {
mat.sCost = cost; //Dynamically evaluated
} else {
mat.sCost = temp;
}
//Parse quantity
if (inputQty.value.includes("MAX") || inputQty.value.includes("PROD")) {
var qty = inputQty.value.replace(/\s+/g, '');
qty = qty.replace(/[^-()\d/*+.MAXPROD]/g, '');
var temp = qty.replace(/MAX/g, 1);
temp = temp.replace(/PROD/g, 1);
try {
temp = eval(temp);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field: " + e);
return false;
}
if (temp == null || isNaN(temp)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field");
return false;
}
mat.sllman[0] = true;
mat.sllman[1] = qty; //Use sanitized input
} else if (isNaN(inputQty.value)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for sell quantity field! Must be numeric or 'MAX'");
return false;
} else {
var qty = parseFloat(inputQty.value);
if (isNaN(qty)) {qty = 0;}
if (qty === 0) {
mat.sllman[0] = false;
mat.sllman[1] = 0;
} else {
mat.sllman[0] = true;
mat.sllman[1] = qty;
}
}
this.createUI(parentRefs);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(sellPopupid);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Cancel", class:"a-link-button", margin: "6px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(sellPopupid);
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(sellPopupid, [txt, br, inputQty, inputPx, confirmBtn, cancelBtn]);
inputQty.focus();
}
}));
return div;
}
Warehouse.prototype.createProductUI = function(product, parentRefs) {
var company = parentRefs.company, industry = parentRefs.industry,
city = currentCityUi;
var div = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-warehouse-product-div"
});
//Products being designed TODO
if (!product.fin) {
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Designing " + product.name + "...<br>" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.prog, 2) + "% complete",
}));
return div;
}
//Completed products
var cmpAndDmdText = "";
if (company.unlockUpgrades[2] === 1) {
cmpAndDmdText += "<br>Demand: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.dmd, 3);
}
if (company.unlockUpgrades[3] === 1) {
cmpAndDmdText += "<br>Competition: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.cmp, 3);
}
var totalGain = product.data[city][1] - product.data[city][2]; //Production - sale
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "<p class='tooltip'>" + product.name + ": " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.data[city][0], 3) + //Quantity
"(" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(totalGain, 3) + "/s)" +
"<span class='tooltiptext'>Prod: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.data[city][1], 3) + "/s<br>" +
"Sell: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.data[city][2], 3) + "/s</span></p><br>" +
"<p class='tooltip'>Rating: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.rat, 3) +
"<span class='tooltiptext'>Quality: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.qlt, 3) + "<br>" +
"Performance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.per, 3) + "<br>" +
"Durability: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.dur, 3) + "<br>" +
"Reliability: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.rel, 3) + "<br>" +
"Aesthetics: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.aes, 3) + "<br>" +
"Features: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.fea, 3) +
cmpAndDmdText + "</span></p><br>" +
"<p class='tooltip'>Est. Production Cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(product.pCost / ProductProductionCostRatio, "$0.000a") +
"<span class='tooltiptext'>An estimate of the material cost it takes to create this Product.</span></p><br>" +
"<p class='tooltip'>Est. Market Price: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(product.pCost + product.rat / product.mku, "$0.000a") +
"<span class='tooltiptext'>An estimate of how much consumers are willing to pay for this product. " +
"Setting the sale price above this may result in less sales. Setting the sale price below this may result " +
"in more sales.</span></p>"
}));
var buttonPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
display:"inline-block",
});
div.appendChild(buttonPanel);
//Sell button
var sellInnerTextString = (product.sllman[city][1] === -1 ? "Sell (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.data[city][2], 3) + "/MAX)" :
"Sell (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.data[city][2], 3) + "/" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.sllman[city][1], 3) + ")");
if (product.sCost) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["isString"])(product.sCost)) {
sellInnerTextString += (" @ " + product.sCost);
} else {
sellInnerTextString += (" @ " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(product.sCost, "$0.000a"));
}
}
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:sellInnerTextString, class:"a-link-button", display:"inline-block",margin:"6px",
clickListener:()=>{
var popupId = "cmpy-mgmt-sell-product-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML:"Enter the maximum amount of " + product.name + " you would like " +
"to sell per second, as well as the price at which you would like to " +
"sell it at.<br><br>" +
"If the sell amount is set to 0, then the product will not be sold. If the " +
"sell price is set to 0, then the product will be discarded.<br><br>" +
"Setting the sell amount to 'MAX' will result in you always selling the " +
"maximum possible amount of the material.<br><br>" +
"When setting the sell amount, you can use the 'PROD' variable to designate a " +
"dynamically changing amount that depends on your production. For example, " +
"if you set the sell amount to 'PROD-1' then you will always sell 1 less of " +
"the material than you produce.<br><br>" +
"When setting the sell price, you can use the 'MP' variable to set a " +
"dynamically changing price that depends on the Product's estimated " +
"market price. For example, if you set it to 'MP*5' then it " +
"will always be sold at five times the estimated market price.",
});
var confirmBtn;
var inputQty = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"text", value:product.sllman[city][1] ? product.sllman[city][1] : null, placeholder: "Sell amount",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
var inputPx = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"text", value: product.sCost ? product.sCost : null, placeholder: "Sell price",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Confirm",
clickListener:()=>{
//Parse price
if (inputPx.value.includes("MP")) {
//Dynamically evaluated quantity. First test to make sure its valid
//Sanitize input, then replace dynamic variables with arbitrary numbers
var price = inputPx.value.replace(/\s+/g, '');
price = price.replace(/[^-()\d/*+.MP]/g, '');
var temp = price.replace(/MP/g, 1);
try {
temp = eval(temp);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell quantity field: " + e);
return false;
}
if (temp == null || isNaN(temp)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell quantity field.");
return false;
}
product.sCost = price; //Use sanitized price
} else {
var cost = parseFloat(inputPx.value);
if (isNaN(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for sell price field");
return false;
}
product.sCost = cost;
}
//Parse quantity
if (inputQty.value.includes("MAX") || inputQty.value.includes("PROD")) {
//Dynamically evaluated quantity. First test to make sure its valid
var qty = inputQty.value.replace(/\s+/g, '');
qty = qty.replace(/[^-()\d/*+.MAXPROD]/g, '');
var temp = qty.replace(/MAX/g, 1);
temp = temp.replace(/PROD/g, 1);
try {
temp = eval(temp);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field: " + e);
return false;
}
if (temp == null || isNaN(temp)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value or expression for sell price field");
return false;
}
product.sllman[city][0] = true;
product.sllman[city][1] = qty; //Use sanitized input
} else if (isNaN(inputQty.value)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for sell quantity field! Must be numeric");
return false;
} else {
var qty = parseFloat(inputQty.value);
if (isNaN(qty)) {qty = 0;}
if (qty === 0) {
product.sllman[city][0] = false;
} else {
product.sllman[city][0] = true;
product.sllman[city][1] = qty;
}
}
this.createUI(parentRefs);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, inputQty, inputPx, confirmBtn, cancelBtn]);
inputQty.focus();
}
}));
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br",{})); //force line break
//Limit production button
var limitProductionInnerText = "Limit Production";
if (product.prdman[city][0]) {
limitProductionInnerText += " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(product.prdman[city][1], 3) + ")";
}
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:limitProductionInnerText,display:"inline-block",
clickListener:()=>{
var popupId = "cmpy-mgmt-limit-product-production-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Enter a limit to the amount of this product you would " +
"like to product per second. Leave the box empty to set no limit."
});
var confirmBtn;
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", placeholder:"Limit",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Limit production", margin:'6px',
clickListener:()=>{
if (input.value === "") {
product.prdman[city][0] = false;
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
var qty = parseFloat(input.value);
if (isNaN(qty)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered");
return false;
}
if (qty < 0) {
product.prdman[city][0] = false;
} else {
product.prdman[city][0] = true;
product.prdman[city][1] = qty;
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Cancel", margin:"6px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, input, confirmBtn, cancelBtn]);
}
}));
//Discontinue button
div.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:'a-link-button', display:"inline-block",innerText:"Discontinue",
clickListener:()=>{
var popupId = "cmpy-mgmt-discontinue-product-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Are you sure you want to do this? Discontinuing a product " +
"removes it completely and permanently. You will no longer " +
"produce this product and all of its existing stock will be " +
"removed and left unsold",
});
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",innerText:"Discontinue",
clickListener:()=>{
industry.discontinueProduct(product, parentRefs);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, confirmBtn, cancelBtn]);
}
}));
return div;
}
Warehouse.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Warehouse", this);
}
Warehouse.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Warehouse, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Warehouse = Warehouse;
//Corporation Unlock Upgrades
//Upgrades for entire corporation, unlocks features, either you have it or you dont
//The structure is [index in Corporation feature upgrades array, price ]
var CorporationUnlockUpgrades = {
//Lets you export goods
"0": [0, 20e9, "Export",
"Develop infrastructure to export your materials to your other facilities. " +
"This allows you to move materials around between different divisions and cities."],
//Lets you buy exactly however many required materials you need for production
"1": [1, 50e9, "Smart Supply", "Use advanced AI to anticipate your supply needs. " +
"This allows you to purchase exactly however many materials you need for production."],
//Displays each material/product's demand
"2": [2, 5e9, "Market Research - Demand",
"Mine and analyze market data to determine the demand of all resources. " +
"The demand attribute, which affects sales, will be displayed for every material and product."],
//Display's each material/product's competition
"3": [3, 5e9, "Market Data - Competition",
"Mine and analyze market data to determine how much competition there is on the market " +
"for all resources. The competition attribute, which affects sales, will be displayed for " +
"for every material and product."],
"4": [4, 10e9, "VeChain",
"Use AI and blockchain technology to identify where you can improve your supply chain systems. " +
"This upgrade will allow you to view a wide array of useful statistics about your " +
"Corporation."]
}
//Corporation Upgrades
//Upgrades for entire corporation, levelable upgrades
//The structure is [index in Corporation upgrades array, base price, price mult, benefit mult (additive),
// name, desc]
var CorporationUpgrades = {
//Smart factories, increases production
"0": [0, 2e9, 1.07, 0.03,
"Smart Factories", "Advanced AI automatically optimizes the operation and productivity " +
"of factories. Each level of this upgrade increases your global production by 3% (additive)."],
//Smart warehouses, increases storage size
"1": [1, 2e9, 1.07, .1,
"Smart Storage", "Advanced AI automatically optimizes your warehouse storage methods. " +
"Each level of this upgrade increases your global warehouse storage size by 10% (additive)."],
//Advertise through dreams, passive popularity/ awareness gain
"2": [2, 8e9, 1.09, .001,
"DreamSense", "Use DreamSense LCC Technologies to advertise your corporation " +
"to consumers through their dreams. Each level of this upgrade provides a passive " +
"increase in awareness of all of your companies (divisions) by 0.004 / market cycle," +
"and in popularity by 0.001 / market cycle. A market cycle is approximately " +
"20 seconds."],
//Makes advertising more effective
"3": [3, 4e9, 1.12, 0.005,
"Wilson Analytics", "Purchase data and analysis from Wilson, a marketing research " +
"firm. Each level of this upgrades increases the effectiveness of your " +
"advertising by 0.5% (additive)."],
//Augmentation for employees, increases cre
"4": [4, 1e9, 1.06, 0.1,
"Nuoptimal Nootropic Injector Implants", "Purchase the Nuoptimal Nootropic " +
"Injector augmentation for your employees. Each level of this upgrade " +
"globally increases the creativity of your employees by 10% (additive)."],
//Augmentation for employees, increases cha
"5": [5, 1e9, 1.06, 0.1,
"Speech Processor Implants", "Purchase the Speech Processor augmentation for your employees. " +
"Each level of this upgrade globally increases the charisma of your employees by 10% (additive)."],
//Augmentation for employees, increases int
"6": [6, 1e9, 1.06, 0.1,
"Neural Accelerators", "Purchase the Neural Accelerator augmentation for your employees. " +
"Each level of this upgrade globally increases the intelligence of your employees " +
"by 10% (additive)."],
//Augmentation for employees, increases eff
"7": [7, 1e9, 1.06, 0.1,
"FocusWires", "Purchase the FocusWire augmentation for your employees. Each level " +
"of this upgrade globally increases the efficiency of your employees by 10% (additive)."],
//Improves sales of materials/products
"8": [8, 1e9, 1.08, 0.01,
"ABC SalesBots", "Always Be Closing. Purchase these robotic salesmen to increase the amount of " +
"materials and products you sell. Each level of this upgrade globally increases your sales " +
"by 1% (additive)."],
//Improves scientific research rate
"9": [9, 5e9, 1.07, 0.05,
"Project Insight", "Purchase 'Project Insight', a R&D service provided by the secretive " +
"Fulcrum Technologies. Each level of this upgrade globally increases the amount of " +
"Scientific Research you produce by 5% (additive)."],
}
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_5__[/* default */ "a"](150e9);
this.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
this.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
this.fundingRound = 0;
this.public = false; //Publicly traded
this.numShares = TOTALSHARES;
this.issuedShares = 0;
this.sharePrice = 0;
this.storedCycles = 0;
var numUnlockUpgrades = Object.keys(CorporationUnlockUpgrades).length,
numUpgrades = Object.keys(CorporationUpgrades).length;
this.unlockUpgrades = Array(numUnlockUpgrades).fill(0);
this.upgrades = Array(numUpgrades).fill(0);
this.upgradeMultipliers = Array(numUpgrades).fill(1);
this.state = new 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) {
var state = this.getState(), marketCycles=1;
this.storedCycles -= (marketCycles * CyclesPerIndustryStateCycle);
//At the start of a new cycle, calculate profits from previous cycle
if (state === "START") {
this.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
this.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* 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);
var cycleProfit = profit.times(marketCycles * SecsPerMarketCycle);
if (isNaN(this.funds)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("There was an error calculating your Corporations funds and they got reset to 0. " +
"This is a bug. Please report to game developer.<br><br>" +
"(Your funds have been set to $150b for the inconvenience)");
this.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](150e9);
}
this.funds = this.funds.plus(cycleProfit);
this.updateSharePrice();
}
this.divisions.forEach(function(ind) {
ind.process(marketCycles, state, corp);
});
this.state.nextState();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_12__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_12__["Page"].Corporation)) {this.updateUIContent();}
}
}
Corporation.prototype.determineValuation = function() {
var val, profit = (this.revenue.minus(this.expenses)).toNumber();
if (this.public) {
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 * 320e3);
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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].CorporationValuation;
}
Corporation.prototype.getInvestment = function() {
var val = this.determineValuation(), percShares;
switch (this.fundingRound) {
case 0: //Seed
percShares = 0.10;
break;
case 1: //Series A
percShares = 0.35;
break;
case 2: //Series B
percShares = 0.25;
break;
case 3: //Series C
percShares = 0.20;
break;
case 4:
return;
}
var funding = val * percShares * 4,
investShares = Math.floor(TOTALSHARES * percShares),
yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetYesButton */ "d"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Accept";
noBtn.innerHML = "Reject";
yesBtn.addEventListener("click", ()=>{
++this.fundingRound;
this.funds = this.funds.plus(funding);
this.numShares -= investShares;
this.displayCorporationOverviewContent();
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxClose */ "a"])();
});
noBtn.addEventListener("click", ()=>{
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxClose */ "a"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__[/* yesNoBoxCreate */ "b"])("An investment firm has offered you " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(funding, '$0.000a') +
" in funding in exchange for a " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(percShares*100, "0.000a") +
"% stake in the company (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(investShares, '0.000a') + " shares).<br><br>" +
"Do you accept or reject this offer?");
}
Corporation.prototype.goPublic = function() {
var goPublicPopupId = "cmpy-mgmt-go-public-popup";
var initialSharePrice = this.determineValuation() / (TOTALSHARES);
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["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_6__[/* numeralWrapper */ "a"].format(initialSharePrice, '$0.000a') + " per share " +
"(the IPO money will be deposited directly into your Corporation's funds).<br><br>" +
"Furthermore, issuing more shares now will help drive up " +
"your company's stock price in the future.<br><br>" +
"You have a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.numShares, "0.000a") + " of shares that you can issue.",
});
var yesBtn;
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number",
placeholder: "Shares to issue",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {yesBtn.click();}
}
});
var br = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {});
yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Go Public",
clickListener:()=>{
var numShares = Math.round(input.value);
var initialSharePrice = this.determineValuation() / (TOTALSHARES);
if (isNaN(numShares)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for number of issued shares");
return false;
}
if (numShares > this.numShares) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["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.displayCorporationOverviewContent();
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(goPublicPopupId);
return false;
}
});
var noBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(goPublicPopupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(goPublicPopupId, [txt, br, input, yesBtn, noBtn]);
}
Corporation.prototype.updateSharePrice = function() {
var targetPrice = this.determineValuation() / (TOTALSHARES - this.issuedShares);
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;}
}
//One time upgrades that unlock new features
Corporation.prototype.unlock = function(upgrade) {
var 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_7__["dialogBoxCreate"])("You don't have enough funds to unlock this!");
return;
}
this.unlockUpgrades[upgN] = 1;
this.funds = this.funds.minus(price);
}
//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_7__["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) {
industry.warehouses[city].updateSize(this);
}
}
}
}
this.updateCorporationOverviewContent();
}
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;}
}
//Keep 'global' variables for DOM elements so we don't have to search
//through the DOM tree repeatedly when updating UI
var companyManagementDiv, companyManagementHeaderTabs, companyManagementPanel,
currentCityUi,
corporationUnlockUpgrades, corporationUpgrades,
//Industry Overview Panel
industryOverviewPanel, industryOverviewText,
//Industry Employee Panel
industryEmployeePanel, industryEmployeeText, industryEmployeeHireButton, industryEmployeeAutohireButton,
industryEmployeeManagementUI, industryEmployeeInfo, industryIndividualEmployeeInfo,
industryOfficeUpgradeSizeButton,
//Industry Warehouse Panel
industryWarehousePanel, industrySmartSupplyCheckbox, industryWarehouseStorageText,
industryWarehouseUpgradeSizeButton, industryWarehouseStateText,
industryWarehouseMaterials, industryWarehouseProducts,
headerTabs, cityTabs;
Corporation.prototype.createUI = function() {
companyManagementDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
id:"cmpy-mgmt-container",
position:"fixed",
class:"generic-menupage-container"
});
companyManagementHeaderTabs = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {id:"cmpy-mgmt-header-tabs"});
companyManagementDiv.appendChild(companyManagementHeaderTabs);
//Create division/industry tabs at the top
this.updateUIHeaderTabs();
//Create the 'panel' that will have the actual content in the UI
companyManagementPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {id:"cmpy-mgmt-panel"});
companyManagementDiv.appendChild(companyManagementPanel);
document.getElementById("entire-game-container").appendChild(companyManagementDiv);
this.displayCorporationOverviewContent();
}
Corporation.prototype.updateUIHeaderTabs = function() {
if (companyManagementHeaderTabs) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(companyManagementHeaderTabs);
} else {
console.log("ERROR: Header tabs div has not yet been created when Corporation.updateUIHeaderTabs() is called");
return;
}
//Corporation overview tabs
var cmpyOverviewHdrTab = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("button", {
id:"cmpy-mgmt-company-tab",
class:"cmpy-mgmt-header-tab",
innerText:this.name,
checked:true,
clickListener:()=>{
this.selectHeaderTab(cmpyOverviewHdrTab);
this.displayCorporationOverviewContent();
return false;
}
});
companyManagementHeaderTabs.appendChild(cmpyOverviewHdrTab);
//Tabs for each division
for (var i = 0; i < this.divisions.length; ++i) {
this.createDivisionUIHeaderTab(this.divisions[i]);
}
//Create a tab to expand into a new industry
companyManagementHeaderTabs.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("button", {
id:'cmpy-mgmt-expand-industry-tab',
class:"cmpy-mgmt-header-tab",
innerText:"Expand into new Industry",
clickListener: ()=>{
if (document.getElementById("cmpy-mgmt-expand-industry-popup") != null) {return;}
var container = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"popup-box-container",
id:"cmpy-mgmt-expand-industry-popup",
});
var content = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {class:"popup-box-content"});
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Create a new division to expand into a new industry:",
});
var selector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {
class:"dropdown"
});
var industryDescription = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {});
var yesBtn;
var nameInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"text",
id:"cmpy-mgmt-expand-industry-name-input",
class: "text-input",
display:"block",
maxLength: 30,
pattern:"[a-zA-Z0-9-_]",
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {yesBtn.click();}
}
});
var nameLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("label", {
for:"cmpy-mgmt-expand-industry-name-input",
innerText:"Division name: "
});
yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("span", {
class:"popup-box-button",
innerText:"Create Division",
clickListener: ()=>{
var ind = selector.options[selector.selectedIndex].value,
newDivisionName = nameInput.value;
for (var i = 0; i < this.divisions.length; ++i) {
if (this.divisions[i].name === newDivisionName) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("This name is already in use!");
return false;
}
}
if (this.funds.lt(IndustryStartingCosts[ind])) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Not enough money to create a new division in this industry");
} else if (newDivisionName === "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("New division must have a name!");
} else {
this.funds = this.funds.minus(IndustryStartingCosts[ind]);
var newInd = new Industry({
name:newDivisionName,
type:ind,
});
this.divisions.push(newInd);
this.updateUIHeaderTabs();
this.selectHeaderTab(headerTabs[headerTabs.length-2]);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])("cmpy-mgmt-expand-industry-popup");
this.displayDivisionContent(newInd, _Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12);
}
return false;
}
});
var noBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("span", {
class:"popup-box-button",
innerText:"Cancel",
clickListener: function() {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])("cmpy-mgmt-expand-industry-popup");
return false;
}
});
//Make an object to keep track of what industries you're already in
var ownedIndustries = {}
for (var i = 0; i < this.divisions.length; ++i) {
ownedIndustries[this.divisions[i].type] = true;
}
//Add industry types to selector
//Have Agriculture be first as recommended option
if (!ownedIndustries["Agriculture"]) {
selector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text:Industries["Agriculture"], value:"Agriculture"
}));
}
for (var key in Industries) {
if (key !== "Agriculture" && Industries.hasOwnProperty(key) && !ownedIndustries[key]) {
var ind = Industries[key];
selector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text: ind,value:key,
}));
}
}
//Initial Industry Description
var ind = selector.options[selector.selectedIndex].value;
industryDescription.innerHTML = (IndustryDescriptions[ind] + "<br><br>");
//Change the industry description text based on selected option
selector.addEventListener("change", function() {
var ind = selector.options[selector.selectedIndex].value;
industryDescription.innerHTML = IndustryDescriptions[ind] + "<br><br>";
});
//Add to DOM
content.appendChild(txt);
content.appendChild(selector);
content.appendChild(industryDescription);
content.appendChild(nameLabel);
content.appendChild(nameInput);
content.appendChild(noBtn);
content.appendChild(yesBtn);
container.appendChild(content);
document.getElementById("entire-game-container").appendChild(container);
container.style.display = "flex";
return false;
}
}));
headerTabs = companyManagementDiv.getElementsByClassName("cmpy-mgmt-header-tab");
}
//Updates UI to display which header tab is selected
Corporation.prototype.selectHeaderTab = function(currentTab) {
if (currentTab == null) {return;}
for (var i = 0; i < headerTabs.length; ++i) {
headerTabs[i].className = "cmpy-mgmt-header-tab";
}
currentTab.className = "cmpy-mgmt-header-tab current";
}
Corporation.prototype.createDivisionUIHeaderTab = function(division) {
var tabId = "cmpy-mgmt-" + division.name + "-tab";
var tab = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("button", {
id:tabId,
class:"cmpy-mgmt-header-tab",
innerText:division.name,
clickListener:()=>{
this.selectHeaderTab(tab);
this.displayDivisionContent(division, _Locations__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12);
return false;
}
});
companyManagementHeaderTabs.appendChild(tab);
}
Corporation.prototype.clearUIPanel = function() {
while(companyManagementPanel.firstChild) {
companyManagementPanel.removeChild(companyManagementPanel.firstChild);
}
}
Corporation.prototype.updateUIContent = function() {
//Check which of the header tab buttons is checked
if (headerTabs == null) {
console.log("ERROR: headerTabs is null in Corporation.updateUIContent()");
return;
}
for (var i = 0; i < headerTabs.length; ++i) {
if (headerTabs[i].classList.contains("current")) {
if (i === 0) {
//Corporation overview
this.updateCorporationOverviewContent();
} else {
//Division
this.updateDivisionContent(this.divisions[i-1]);
}
return;
}
}
}
Corporation.prototype.displayCorporationOverviewContent = function() {
this.clearUIPanel();
companyManagementPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
id:"cmpy-mgmt-overview-text",
}));
if (headerTabs && headerTabs.length >= 1) {
this.selectHeaderTab(headerTabs[0]);
}
//Check if player has Corporation Handbook
var homeComp = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].getHomeComputer(), hasHandbook = false,
handbookFn = "corporation-management-handbook.lit";
for (var i = 0; i < homeComp.messages.length; ++i) {
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_15__["isString"])(homeComp.messages[i]) && homeComp.messages[i] === handbookFn) {
hasHandbook = true;
break;
}
}
companyManagementPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Getting Started Guide", display:"inline-block",
tooltip:"Get a copy of and read 'The Complete Handbook for Creating a Successful Corporation.' " +
"This is a .lit file that guides you through the beginning of setting up a Corporation and " +
"provides some tips/pointers for helping you get started with managing it.",
clickListener:()=>{
if (!hasHandbook) {homeComp.messages.push(handbookFn);}
Object(_Literature__WEBPACK_IMPORTED_MODULE_2__[/* showLiterature */ "b"])(handbookFn);
return false;
}
}));
//Investors
if (this.public) {
//Sell share buttons
var sellShares = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Sell Shares", display:"inline-block",
tooltip:"Sell your shares in the company. This is the only way to " +
"profit from your business venture.",
clickListener:()=>{
var popupId = "cmpy-mgmt-sell-shares-popup";
var currentStockPrice = this.sharePrice;
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Enter the number of shares you would like to sell. The money from " +
"selling your shares will go directly to you (NOT your Corporation). " +
"The current price of your " +
"company's stock is " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(currentStockPrice, "$0.000a"),
});
var profitIndicator = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {});
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", placeholder:"Shares to sell", margin:"5px",
inputListener: ()=> {
var numShares = Math.round(input.value);
if (isNaN(numShares) || numShares <= 0) {
profitIndicator.innerText = "ERROR: Invalid value entered for number of shares to sell"
} else if (numShares > this.numShares) {
profitIndicator.innerText = "You don't have this many shares to sell!";
} else {
profitIndicator.innerText = "Sell " + numShares + " shares for a total of " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(numShares * currentStockPrice, '$0.000a');
}
}
});
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Sell shares", display:"inline-block",
clickListener:()=>{
var shares = Math.round(input.value);
if (isNaN(shares) || shares <= 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: Invalid value for number of shares");
} else if (shares > this.numShares) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: You don't have this many shares to sell");
} else {
this.numShares -= shares;
if (isNaN(this.issuedShares)) {
console.log("ERROR: Corporation issuedShares is NaN: " + this.issuedShares);
console.log("Converting to number now");
var res = parseInt(this.issuedShares);
if (isNaN(res)) {
this.issuedShares = 0;
} else {
this.issuedShares = res;
}
}
this.issuedShares += shares;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(shares * this.sharePrice);
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Cancel", display:"inline-block",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, profitIndicator, input, confirmBtn, cancelBtn]);
}
});
//Buyback shares button
var buybackShares = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Buyback shares", display:"inline-block",
tooltip:"Buy back shares you that previously issued or sold at market price.",
clickListener:()=>{
var popupId = "cmpy-mgmt-buyback-shares-popup";
var currentStockPrice = this.sharePrice;
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML: "Enter the number of shares you would like to buy back at market price. To purchase " +
"these shares, you must use your own money (NOT your Corporation's funds). " +
"The current price of your " +
"company's stock is " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(currentStockPrice, "$0.000a") +
". Your company currently has " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.issuedShares, 3) + " outstanding stock shares",
});
var costIndicator = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {});
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", placeholder:"Shares to buyback", margin:"5px",
inputListener: ()=> {
var numShares = Math.round(input.value);
//TODO add conditional for if player doesn't have enough money
if (isNaN(numShares) || numShares <= 0) {
costIndicator.innerText = "ERROR: Invalid value entered for number of shares to buyback"
} else if (numShares > this.issuedShares) {
costIndicator.innerText = "There are not this many shares available to buy back. " +
"There are only " + this.issuedShares + " outstanding shares.";
} else {
console.log("here");
costIndicator.innerText = "Purchase " + numShares + " shares for a total of " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(numShares * currentStockPrice, '$0.000a');
}
}
});
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Buy shares", display:"inline-block",
clickListener:()=>{
var shares = Math.round(input.value);
var tempStockPrice = this.sharePrice;
if (isNaN(shares) || shares <= 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: Invalid value for number of shares");
} else if (shares > this.issuedShares) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: There are not this many oustanding shares to buy back");
} else if (shares * tempStockPrice > _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: You do not have enough money to purchase this many shares (you need " +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(shares * tempStockPrice, "$0.000a") + ")");
} else {
this.numShares += shares;
if (isNaN(this.issuedShares)) {
console.log("ERROR: Corporation issuedShares is NaN: " + this.issuedShares);
console.log("Converting to number now");
var res = parseInt(this.issuedShares);
if (isNaN(res)) {
this.issuedShares = 0;
} else {
this.issuedShares = res;
}
}
this.issuedShares -= shares;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(shares * tempStockPrice);
//TODO REMOVE from Player money
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
}
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Cancel",
display:"inline-block",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, costIndicator, input, confirmBtn, cancelBtn]);
}
});
companyManagementPanel.appendChild(sellShares);
companyManagementPanel.appendChild(buybackShares);
//If your Corporation is big enough, buy faction influence through bribes
var canBribe = this.determineValuation() >= BribeThreshold;
var bribeFactions = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: canBribe ? "a-link-button" : "a-link-button-inactive",
innerText:"Bribe Factions", display:"inline-block",
tooltip:canBribe
? "Use your Corporations power and influence to bribe Faction leaders in exchange for reputation"
: "Your Corporation is not powerful enough to bribe Faction leaders",
clickListener:()=>{
var popupId = "cmpy-mgmt-bribe-factions-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"You can use Corporation funds or stock shares to bribe Faction Leaders in exchange for faction reputation"
});
var factionSelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {margin:"3px"});
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions.length; ++i) {
var facName = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions[i];
factionSelector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text:facName, value:facName
}));
}
var repGainText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p");
var stockSharesInput;
var moneyInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", placeholder:"Corporation funds", margin:"5px",
inputListener:()=>{
var money = moneyInput.value == null || moneyInput.value == "" ? 0 : parseFloat(moneyInput.value);
var stockPrice = this.sharePrice;
var stockShares = stockSharesInput.value == null || stockSharesInput.value == "" ? 0 : Math.round(parseFloat(stockSharesInput.value));
if (isNaN(money) || isNaN(stockShares) || money < 0 || stockShares < 0) {
repGainText.innerText = "ERROR: Invalid value(s) entered";
} else if (this.funds.lt(money)) {
repGainText.innerText = "ERROR: You do not have this much money to bribe with";
} else if (this.stockShares > this.numShares) {
repGainText.innerText = "ERROR: You do not have this many shares to bribe with";
} else {
var totalAmount = Number(money) + (stockShares * stockPrice);
var repGain = totalAmount / BribeToRepRatio;
repGainText.innerText = "You will gain " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(repGain, 0) +
" reputation with " +
factionSelector.options[factionSelector.selectedIndex].value +
" with this bribe";
}
}
});
stockSharesInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", placeholder:"Stock Shares", margin: "5px",
inputListener:()=>{
var money = moneyInput.value == null || moneyInput.value == "" ? 0 : parseFloat(moneyInput.value);
var stockPrice = this.sharePrice;
var stockShares = stockSharesInput.value == null || stockSharesInput.value == "" ? 0 : Math.round(stockSharesInput.value);
if (isNaN(money) || isNaN(stockShares) || money < 0 || stockShares < 0) {
repGainText.innerText = "ERROR: Invalid value(s) entered";
} else if (this.funds.lt(money)) {
repGainText.innerText = "ERROR: You do not have this much money to bribe with";
} else if (this.stockShares > this.numShares) {
repGainText.innerText = "ERROR: You do not have this many shares to bribe with";
} else {
var totalAmount = money + (stockShares * stockPrice);
var repGain = totalAmount / BribeToRepRatio;
console.log("repGain: " + repGain);
repGainText.innerText = "You will gain " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(repGain, 0) +
" reputation with " +
factionSelector.options[factionSelector.selectedIndex].value +
" with this bribe";
}
}
});
var confirmButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Bribe", display:"inline-block",
clickListener:()=>{
var money = moneyInput.value == null || moneyInput.value == "" ? 0 : parseFloat(moneyInput.value);
var stockPrice = this.sharePrice;
var stockShares = stockSharesInput.value == null || stockSharesInput.value == ""? 0 : Math.round(parseFloat(stockSharesInput.value));
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_1__["Factions"][factionSelector.options[factionSelector.selectedIndex].value];
if (fac == null) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: You must select a faction to bribe");
return false;
}
if (isNaN(money) || isNaN(stockShares) || money < 0 || stockShares < 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: Invalid value(s) entered");
} else if (this.funds.lt(money)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: You do not have this much money to bribe with");
} else if (stockShares > this.numShares) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("ERROR: You do not have this many shares to bribe with");
} else {
var totalAmount = money + (stockShares * stockPrice);
var repGain = totalAmount / BribeToRepRatio;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(repGain, 0) +
" reputation with " + fac.name + " by bribing them.");
fac.playerReputation += repGain;
this.funds = this.funds.minus(money);
this.numShares -= stockShares;
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
}
});
var cancelButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Cancel", display:"inline-block",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, factionSelector, repGainText,
moneyInput, stockSharesInput, confirmButton, cancelButton]);
}
});
companyManagementPanel.appendChild(bribeFactions);
} else {
var findInvestors = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: this.fundingRound >= 4 ? "a-link-button-inactive" : "a-link-button tooltip",
innerText: "Find Investors",
display:"inline-block",
clickListener:()=>{
this.getInvestment();
}
});
if (this.fundingRound < 4) {
var findInvestorsTooltip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("span", {
class:"tooltiptext",
innerText:"Search for private investors who will give you startup funding in exchange " +
"for equity (stock shares) in your company"
});
findInvestors.appendChild(findInvestorsTooltip);
}
var goPublic = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button tooltip",
innerText:"Go Public",
display:"inline-block",
clickListener:()=>{
this.goPublic();
return false;
}
});
var goPublicTooltip = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("span", {
class:"tooltiptext",
innerText: "Become a publicly traded and owned entity. Going public involves " +
"issuing shares for an IPO. Once you are a public company, " +
"your shares will be traded on the stock market."
});
goPublic.appendChild(goPublicTooltip);
companyManagementPanel.appendChild(findInvestors);
companyManagementPanel.appendChild(goPublic);
}
//Update overview text
this.updateCorporationOverviewContent();
//Don't show upgrades if player hasn't opened any divisions
if (this.divisions.length <= 0) {return; }
//Corporation Upgrades
var upgradeContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-upgrade-container",
});
upgradeContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("h1", {
innerText:"Unlocks", margin:"6px", padding:"6px",
}));
//Unlock upgrades
var corp = this;
var numUnlockUpgrades = Object.keys(CorporationUnlockUpgrades).length,
numUpgrades = Object.keys(CorporationUpgrades).length;
if (this.unlockUpgrades == null || this.upgrades == null) { //Backwards compatibility
this.unlockUpgrades = Array(numUnlockUpgrades).fill(0);
this.upgrades = Array(numUpgrades).fill(0);
}
while (this.unlockUpgrades.length < numUnlockUpgrades) {this.unlockUpgrades.push(0);}
while (this.upgrades.length < numUpgrades) {this.upgrades.push(0);}
while (this.upgradeMultipliers < numUpgrades) {this.upgradeMultipliers.push(1);}
for (var i = 0; i < numUnlockUpgrades; ++i) {
(function(i, corp) {
if (corp.unlockUpgrades[i] === 0) {
var upgrade = CorporationUnlockUpgrades[i.toString()];
if (upgrade == null) {
console.log("ERROR: Could not find upgrade index " + i);
return;
}
upgradeContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-upgrade-div", width:"45%",
innerHTML:upgrade[2] + " - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(upgrade[1], "$0.000a"),
tooltip: upgrade[3],
clickListener:()=>{
if (corp.funds.lt(upgrade[1])) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Insufficient funds");
} else {
corp.unlock(upgrade);
corp.displayCorporationOverviewContent();
}
}
}));
}
})(i, corp);
}
//Levelable upgrades
upgradeContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("h1", {
innerText:"Upgrades", margin:"6px", padding:"6px",
}));
for (var i = 0; i < numUpgrades; ++i) {
(function(i, corp) {
var upgrade = CorporationUpgrades[i.toString()];
if (upgrade == null) {
console.log("ERROR: Could not find levelable upgrade index " + i);
return;
}
var baseCost = upgrade[1], priceMult = upgrade[2];
var cost = baseCost * Math.pow(priceMult, corp.upgrades[i]);
upgradeContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-upgrade-div", width:"45%",
innerHTML:upgrade[4] + " - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(cost, "$0.000a"),
tooltip:upgrade[5],
clickListener:()=>{
if (corp.funds.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Insufficient funds");
} else {
corp.upgrade(upgrade);
corp.displayCorporationOverviewContent();
}
}
}));
})(i, corp);
}
companyManagementPanel.appendChild(upgradeContainer);
}
Corporation.prototype.updateCorporationOverviewContent = function() {
var p = document.getElementById("cmpy-mgmt-overview-text");
if (p == null) {
console.log("WARNING: Could not find overview text elemtn in updateCorporationOverviewContent()");
return;
}
var totalFunds = this.funds,
totalRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0),
totalExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"](0);
var profit = this.revenue.minus(this.expenses).toNumber(),
profitStr = profit >= 0 ? _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(profit, "$0.000a") : "-" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(-1 * profit, "$0.000a");
var txt = "Total Funds: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(totalFunds.toNumber(), '$0.000a') + "<br>" +
"Total Revenue: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.revenue.toNumber(), "$0.000a") + " / s<br>" +
"Total Expenses: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.expenses.toNumber(), "$0.000a") + "/ s<br>" +
"Total Profits: " + profitStr + " / s<br>" +
"Publicly Traded: " + (this.public ? "Yes" : "No") + "<br>" +
"Owned Stock Shares: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.numShares, '0.000a') + "<br>" +
"Stock Price: " + (this.public ? "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.sharePrice, 2) : "N/A") + "<br><br>";
var prodMult = this.getProductionMultiplier(),
storageMult = this.getStorageMultiplier(),
advMult = this.getAdvertisingMultiplier(),
empCreMult = this.getEmployeeCreMultiplier(),
empChaMult = this.getEmployeeChaMultiplier(),
empIntMult = this.getEmployeeIntMultiplier(),
empEffMult = this.getEmployeeEffMultiplier(),
salesMult = this.getSalesMultiplier(),
sciResMult = this.getScientificResearchMultiplier();
if (prodMult > 1) {txt += "Production Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(prodMult, 3) + "<br>";}
if (storageMult > 1) {txt += "Storage Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(storageMult, 3) + "<br>";}
if (advMult > 1) {txt += "Advertising Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(advMult, 3) + "<br>";}
if (empCreMult > 1) {txt += "Empl. Creativity Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(empCreMult, 3) + "<br>";}
if (empChaMult > 1) {txt += "Empl. Charisma Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(empChaMult, 3) + "<br>";}
if (empIntMult > 1) {txt += "Empl. Intelligence Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(empIntMult, 3) + "<br>";}
if (empEffMult > 1) {txt += "Empl. Efficiency Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(empEffMult, 3) + "<br>";}
if (salesMult > 1) {txt += "Sales Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(salesMult, 3) + "<br>";}
if (sciResMult > 1) {txt += "Scientific Research Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(sciResMult, 3) + "<br>";}
p.innerHTML = txt;
}
Corporation.prototype.displayDivisionContent = function(division, city) {
this.clearUIPanel();
currentCityUi = city;
//Add the city tabs on the left
for (var cityName in division.offices) {
if (division.offices[cityName] instanceof OfficeSpace) {
this.createCityUITab(cityName, division);
}
}
cityTabs = companyManagementPanel.getElementsByClassName("cmpy-mgmt-city-tab");
if (cityTabs.length > 0) {
this.selectCityTab(document.getElementById("cmpy-mgmt-city-" + city + "-tab"), city);
}
//Expand into new City button
companyManagementPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("button", {
class:"cmpy-mgmt-city-tab", innerText:"Expand into new City", display:"inline-block",
clickListener:()=>{
var popupId = "cmpy-mgmt-expand-city-popup";
var text = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText: "Would you like to expand into a new city by opening an office? " +
"This would cost " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(OfficeInitialCost, '$0.000a'),
});
var citySelector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {class: "dropdown", margin:"5px"});
for (var cityName in division.offices) {
if (division.offices.hasOwnProperty(cityName)) {
if (!(division.offices[cityName] instanceof OfficeSpace)) {
citySelector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
text: cityName,
value: cityName
}));
}
}
}
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Confirm", class:"a-link-button", display:"inline-block", margin:"3px",
clickListener:()=>{
var city = citySelector.options[citySelector.selectedIndex].value;
if (this.funds.lt(OfficeInitialCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to open a new office!");
} else {
this.funds = this.funds.minus(OfficeInitialCost);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Opened a new office in " + city + "!");
division.offices[city] = new OfficeSpace({
loc:city,
size:OfficeInitialSize,
});
this.displayDivisionContent(division, city);
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Cancel", class:"a-link-button", display:"inline-block", margin:"3px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
})
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [text, citySelector, confirmBtn, cancelBtn]);
return false;
}
}));
companyManagementPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {})); // Force line break
//Get office object
var office = division.offices[currentCityUi];
if (!(office instanceof OfficeSpace)) {
console.log("ERROR: Current city for UI does not have an office space");
return;
}
//Left and right panels
var leftPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {class:"cmpy-mgmt-industry-left-panel"});
var rightPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {class:"cmpy-mgmt-industry-right-panel"});
companyManagementPanel.appendChild(leftPanel);
companyManagementPanel.appendChild(rightPanel);
//Different sections (Overview, Employee/Office, and Warehouse)
industryOverviewPanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
id:"cmpy-mgmt-industry-overview-panel", class:"cmpy-mgmt-industry-overview-panel"
});
leftPanel.appendChild(industryOverviewPanel);
industryEmployeePanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
id:"cmpy-mgmt-employee-panel", class:"cmpy-mgmt-employee-panel"
});
leftPanel.appendChild(industryEmployeePanel);
industryWarehousePanel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
id:"cmpy-mgmt-warehouse-panel", class:"cmpy-mgmt-warehouse-panel"
});
rightPanel.appendChild(industryWarehousePanel);
//Industry overview text
industryOverviewText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {});
industryOverviewPanel.appendChild(industryOverviewText);
industryOverviewPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
//Industry overview Purchases & Upgrades
var numUpgrades = Object.keys(IndustryUpgrades).length;
while (division.upgrades.length < numUpgrades) {division.upgrades.push(0);} //Backwards compatibility
var industryOverviewUpgrades = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {});
industryOverviewUpgrades.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("u", {
innerText:"Purchases & Upgrades", margin:"2px", padding:"2px",
fontSize:"14px",
}));
industryOverviewUpgrades.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
for (var i = 0; i < numUpgrades; ++i) {
(function(i, corp, division, office) {
var upgrade = IndustryUpgrades[i.toString()];
if (upgrade == null) {
console.log("ERROR: Could not find levelable upgrade index: " + i);
return;
}
var baseCost = upgrade[1], priceMult = upgrade[2], cost = 0;
switch(i) {
case 0: //Coffee, cost is static per employee
cost = office.employees.length * baseCost;
break;
default:
cost = baseCost * Math.pow(priceMult, division.upgrades[i]);
break;
}
industryOverviewUpgrades.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
class:"cmpy-mgmt-upgrade-div", display:"inline-block",
innerHTML:upgrade[4] + ' - ' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(cost, "$0.000a"),
tooltip:upgrade[5],
clickListener:()=>{
if (corp.funds.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Insufficient funds");
} else {
corp.funds = corp.funds.minus(cost);
division.upgrade(upgrade, {
corporation:corp,
office:office,
});
corp.displayDivisionContent(division, city);
}
}
}));
industryOverviewUpgrades.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
})(i, this, division, office);
}
industryOverviewPanel.appendChild(industryOverviewUpgrades);
//Industry Overview 'Create Product' button if applicable
if (division.makesProducts) {
//Get the text on the button based on Industry type
var createProductButtonText, createProductPopupText;
switch(division.type) {
case Industries.Food:
createProductButtonText = "Build Restaurant";
createProductPopupText = "Build and manage a new restaurant!"
break;
case Industries.Tobacco:
createProductButtonText = "Create Product";
createProductPopupText = "Create a new tobacco product!";
break;
case Industries.Pharmaceutical:
createProductButtonText = "Create Drug";
createProductPopupText = "Design and develop a new pharmaceutical drug!";
break;
case Industries.Computer:
case "Computer":
createProductButtonText = "Create Product";
createProductPopupText = "Design and manufacture a new computer hardware product!";
break;
case Industries.Robotics:
createProductButtonText = "Design Robot";
createProductPopupText = "Design and create a new robot or robotic system!";
break;
case Industries.Software:
createProductButtonText = "Develop Software";
createProductPopupText = "Develop a new piece of software!";
break;
case Industries.Healthcare:
createProductButtonText = "Build Hospital";
createProductPopupText = "Build and manage a new hospital!";
break;
case Industries.RealEstate:
createProductButtonText = "Develop Property";
createProductPopupText = "Develop a new piece of real estate property!";
break;
default:
createProductButtonText = "Create Product";
return "";
}
createProductPopupText += "<br><br>To begin developing a product, " +
"first choose the city in which it will be designed. The stats of your employees " +
"in the selected city affect the properties of the finished product, such as its " +
"quality, performance, and durability.<br><br>" +
"You can also choose to invest money in the design and marketing of " +
"the product. Investing money in its design will result in a superior product. " +
"Investing money in marketing the product will help the product's sales.";
//Create the button
industryOverviewPanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:createProductButtonText, margin:"6px", display:"inline-block",
clickListener:()=>{
var popupId = "cmpy-mgmt-create-product-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML:createProductPopupText,
});
var designCity = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {});
for (var cityName in division.offices) {
if (division.offices[cityName] instanceof OfficeSpace) {
designCity.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {
value:cityName,
text:cityName
}));
}
}
var foo = "Product Name";
if (division.type === Industries.Food) {
foo = "Restaurant Name";
} else if (division.type === Industries.Healthcare) {
foo = "Hospital Name";
} else if (division.type === Industries.RealEstate) {
foo = "Property Name";
}
var productNameInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
placeholder:foo,
});
var lineBreak1 = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br",{});
var designInvestInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number",
placeholder:"Design investment"
});
var marketingInvestInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number",
placeholder:"Marketing investment"
});
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Develop Product",
clickListener:()=>{
if (designInvestInput.value == null) {designInvestInput.value = 0;}
if (marketingInvestInput.value == null) {marketingInvestInput.value = 0;}
var designInvest = parseFloat(designInvestInput.value),
marketingInvest = parseFloat(marketingInvestInput.value);
if (productNameInput.value == null || productNameInput.value === "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You must specify a name for your product!");
} else if (isNaN(designInvest)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for design investment");
} else if (isNaN(marketingInvest)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value for marketing investment");
} else if (this.funds.lt(designInvest + marketingInvest)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to make this large of an investment");
} else {
var product = new Product({
name:productNameInput.value.replace(/[<>]/g, ''), //Sanitize for HTMl elements
createCity:designCity.options[designCity.selectedIndex].value,
designCost: designInvest,
advCost: marketingInvest,
});
this.funds = this.funds.minus(designInvest + marketingInvest);
division.products[product.name] = product;
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
}
//this.updateUIContent();
this.displayDivisionContent(division, city);
return false;
}
})
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
})
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, designCity, productNameInput, lineBreak1,
designInvestInput, marketingInvestInput, confirmBtn, cancelBtn]);
}
}));
}
//Employee and Office Panel
industryEmployeeText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
id: "cmpy-mgmt-employee-p",
display:"block",
innerHTML: "<h1>Office Space</h1><br>" +
"Type: " + office.tier + "<br>" +
"Comfort: " + office.comf + "<br>" +
"Beauty: " + office.beau + "<br>" +
"Size: " + office.employees.length + " / " + office.size + " employees",
});
industryEmployeePanel.appendChild(industryEmployeeText);
//Hire Employee button
if (office.employees.length === 0) {
industryEmployeeHireButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",display:"inline-block",
innerText:"Hire Employee", fontSize:"13px",
tooltip:"You'll need to hire some employees to get your operations started! " +
"It's recommended to have at least one employee in every position",
clickListener:()=>{
office.findEmployees({corporation:this, division:division});
return false;
}
});
//industryEmployeeHireButton.classList.add("flashing-button");
} else {
industryEmployeeHireButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",display:"inline-block",
innerText:"Hire Employee", fontSize:"13px",
clickListener:()=>{
office.findEmployees({corporation:this, division:division});
return false;
}
});
}
industryEmployeePanel.appendChild(industryEmployeeHireButton);
//Autohire Employee button
industryEmployeeAutohireButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerText:"Autohire Employee", fontSize:"13px",
tooltip:"Automatically hires an employee and gives him/her a random name",
clickListener:()=>{
office.hireRandomEmployee({corporation:this, division:division});
return false;
}
});
industryEmployeePanel.appendChild(industryEmployeeAutohireButton);
//Upgrade Office Size button
industryEmployeePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
industryOfficeUpgradeSizeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Upgrade size",
display:"inline-block", margin:"6px", fontSize:"13px",
tooltip:"Upgrade the office's size so that it can hold more employees!",
clickListener:()=>{
var popupId = "cmpy-mgmt-upgrade-office-size-popup";
var initialPriceMult = Math.round(office.size / OfficeInitialSize);
var upgradeCost = OfficeInitialCost * Math.pow(1.07, initialPriceMult);
//Calculate cost to upgrade size by 15 employees
var mult = 0;
for (var i = 0; i < 5; ++i) {
mult += (Math.pow(1.07, initialPriceMult + i));
}
var upgradeCost15 = OfficeInitialCost * mult;
//Calculate max upgrade size and cost
var maxMult = (this.funds.dividedBy(OfficeInitialCost)).toNumber();
var maxNum = 1;
mult = Math.pow(1.07, initialPriceMult);
while(maxNum < 50) { //Hard cap of 50x (extra 150 employees)
if (mult >= maxMult) {break;}
var multIncrease = Math.pow(1.07, initialPriceMult + maxNum);
if (mult + multIncrease > maxMult) {
break;
} else {
mult += multIncrease;
}
++maxNum;
}
var upgradeCostMax = OfficeInitialCost * mult;
var text = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Increase the size of your office space to fit additional employees!"
});
var text2 = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {innerText: "Upgrade size: "});
var confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: this.funds.lt(upgradeCost) ? "a-link-button-inactive" : "a-link-button",
display:"inline-block", margin:"4px", innerText:"by 3",
tooltip:_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(upgradeCost, "$0.000a"),
clickListener:()=>{
if (this.funds.lt(upgradeCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to purchase this upgrade!");
} else {
office.size += OfficeInitialSize;
this.funds = this.funds.minus(upgradeCost);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Office space increased! It can now hold " + office.size + " employees");
this.updateUIContent();
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var confirmBtn15 = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: this.funds.lt(upgradeCost15) ? "a-link-button-inactive" : "a-link-button",
display:"inline-block", margin:"4px", innerText:"by 15",
tooltip:_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(upgradeCost15, "$0.000a"),
clickListener:()=>{
if (this.funds.lt(upgradeCost15)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to purchase this upgrade!");
} else {
office.size += (OfficeInitialSize * 5);
this.funds = this.funds.minus(upgradeCost15);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Office space increased! It can now hold " + office.size + " employees");
this.updateUIContent();
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var confirmBtnMax = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:this.funds.lt(upgradeCostMax) ? "a-link-button-inactive" : "a-link-button",
display:"inline-block", margin:"4px", innerText:"by MAX (" + maxNum*OfficeInitialSize + ")",
tooltip:_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(upgradeCostMax, "$0.000a"),
clickListener:()=>{
if (this.funds.lt(upgradeCostMax)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to purchase this upgrade!");
} else {
office.size += (OfficeInitialSize * maxNum);
this.funds = this.funds.minus(upgradeCostMax);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Office space increased! It can now hold " + office.size + " employees");
this.updateUIContent();
}
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", innerText:"Cancel", display:"inline-block", margin:"4px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
})
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [text, text2, confirmBtn, confirmBtn15, confirmBtnMax, cancelBtn]);
return false;
}
});
industryEmployeePanel.appendChild(industryOfficeUpgradeSizeButton);
//Throw Office Party
industryEmployeePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", innerText:"Throw Party",
fontSize:"13px",
tooltip:"Throw an office party to increase your employee's morale and happiness",
clickListener:()=>{
var popupId = "cmpy-mgmt-throw-office-party-popup";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Enter the amount of money you would like to spend PER EMPLOYEE " +
"on this office party"
});
var totalCostTxt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Throwing this party will cost a total of $0"
});
var confirmBtn;
var input = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("input", {
type:"number", margin:"5px", placeholder:"$ / employee",
inputListener:()=>{
if (isNaN(input.value) || input.value < 0) {
totalCostTxt.innerText = "Invalid value entered!"
} else {
var totalCost = input.value * office.employees.length;
totalCostTxt.innerText = "Throwing this party will cost a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(totalCost, '$0.000a');
}
},
onkeyup:(e)=>{
e.preventDefault();
if (e.keyCode === 13) {confirmBtn.click();}
}
});
confirmBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
display:"inline-block",
innerText:"Throw Party",
clickListener:()=>{
if (isNaN(input.value) || input.value < 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered");
} else {
var totalCost = input.value * office.employees.length;
if (this.funds.lt(totalCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You don't have enough company funds to throw this party!");
} else {
this.funds = this.funds.minus(totalCost);
var mult;
for (var fooit = 0; fooit < office.employees.length; ++fooit) {
mult = office.employees[fooit].throwParty(input.value);
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You threw a party for the office! The morale and happiness " +
"of each employee increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])((mult-1) * 100, 2) + "%.");
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
}
}
return false;
}
});
var cancelBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button",
display:"inline-block",
innerText:"Cancel",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(popupId, [txt, totalCostTxt, input, confirmBtn, cancelBtn]);
}
}));
industryEmployeeManagementUI = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {});
industryEmployeeInfo = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {margin:"4px", padding:"4px"});
if (empManualAssignmentModeActive) {
//Employees manually assigned
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", margin:"4px",
innerText:"Switch to Auto Mode",
tooltip:"Switch to Automatic Assignment Mode, which will automatically " +
"assign employees to your selected jobs. You simply have to select " +
"the number of assignments for each job",
clickListener:()=>{
empManualAssignmentModeActive = false;
this.displayDivisionContent(division, city);
}
}));
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
industryIndividualEmployeeInfo = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {margin:"4px", padding:"4px"});
var selector = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("select", {
color: "white", backgroundColor:"black", margin:"4px", padding:"4px",
changeListener:()=>{
var name = selector.options[selector.selectedIndex].text;
for (var i = 0; i < office.employees.length; ++i) {
if (office.employees[i].name === name) {
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(industryIndividualEmployeeInfo);
office.employees[i].createUI(industryIndividualEmployeeInfo, this);
return;
}
}
console.log("ERROR: Employee in selector could not be found");
}
});
for (var i = 0; i < office.employees.length; ++i) {
selector.add(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("option", {text:office.employees[i].name}));
}
selector.selectedIndex = -1;
industryEmployeeManagementUI.appendChild(industryEmployeeInfo);
industryEmployeeManagementUI.appendChild(selector);
industryEmployeeManagementUI.appendChild(industryIndividualEmployeeInfo);
} else {
//Player only manages the number of each occupation, not who gets what job
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class:"a-link-button", display:"inline-block", margin:"4px",
innerText:"Switch to Manual Mode",
tooltip:"Switch to Manual Assignment Mode, which allows you to " +
"specify which employees should get which jobs",
clickListener:()=>{
empManualAssignmentModeActive = true;
this.displayDivisionContent(division, city);
}
}));
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
var opCount = 0, engCount = 0, busCount = 0,
mgmtCount = 0, rndCount = 0, unassignedCount = 0,
trainingCount = 0;
for (var i = 0; i < office.employees.length; ++i) {
switch (office.employees[i].pos) {
case EmployeePositions.Operations:
++opCount; break;
case EmployeePositions.Engineer:
++engCount; break;
case EmployeePositions.Business:
++busCount; break;
case EmployeePositions.Management:
++mgmtCount; break;
case EmployeePositions.RandD:
++rndCount; break;
case EmployeePositions.Unassigned:
++unassignedCount; break;
case EmployeePositions.Training:
++trainingCount; break;
default:
console.log("ERROR: Unrecognized employee position: " + office.employees[i].pos);
break;
}
}
//Unassigned employee count display
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
display:"inline-block",
innerText:"Unassigned Employees: " + unassignedCount,
}));
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
//General display of employee information (avg morale, avg energy, etc.)
industryEmployeeManagementUI.appendChild(industryEmployeeInfo);
industryEmployeeManagementUI.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
var positions = [EmployeePositions.Operations, EmployeePositions.Engineer,
EmployeePositions.Business, EmployeePositions.Management,
EmployeePositions.RandD, EmployeePositions.Training];
var descriptions = ["Manages supply chain operations. Improves production.", //Operations
"Develops and maintains products and production systems. Improves production.", //Engineer
"Handles sales and finances. Improves sales.", //Business
"Leads and oversees employees and office operations. Improves production.", //Management
"Research new innovative ways to improve the company. Generates Scientific Research", //RandD
"Set employee to training, which will increase some of their stats. Employees in training do not affect any company operations."] //Training
var counts = [opCount, engCount, busCount, mgmtCount, rndCount, trainingCount];
for (var i = 0; i < positions.length; ++i) {
(function(corp, i) {
var info = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("h2", {
display:"inline-block", width:"40%", fontSize:"15px",
innerText: positions[i] + "(" + counts[i] + ")",
tooltipleft: descriptions[i]
});
var plusBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: unassignedCount > 0 ? "a-link-button" : "a-link-button-inactive",
display:"inline-block", innerText:"+",
clickListener:()=>{
office.assignEmployeeToJob(positions[i]);
corp.displayDivisionContent(division, city);
}
});
var minusBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
class: counts[i] > 0 ? "a-link-button" : "a-link-button-inactive",
display:"inline-block", innerText:"-",
clickListener:()=>{
office.unassignEmployeeFromJob(positions[i]);
corp.displayDivisionContent(division, city);
}
});
var newline = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {});
industryEmployeeManagementUI.appendChild(info);
industryEmployeeManagementUI.appendChild(plusBtn);
industryEmployeeManagementUI.appendChild(minusBtn);
industryEmployeeManagementUI.appendChild(newline);
})(this, i);
}
}
industryEmployeePanel.appendChild(industryEmployeeManagementUI);
//Warehouse Panel
var warehouse = division.warehouses[currentCityUi];
if (warehouse instanceof Warehouse) {
warehouse.createUI({industry:division, company: this});
} else {
industryWarehousePanel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("a", {
innerText:"Purchase Warehouse ($5b)",
class: "a-link-button",
clickListener:()=>{
if (this.funds.lt(WarehouseInitialCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You do not have enough funds to do this!");
} else {
division.warehouses[currentCityUi] = new Warehouse({
loc:currentCityUi,
size:WarehouseInitialSize,
});
this.funds = this.funds.minus(WarehouseInitialCost);
this.displayDivisionContent(division, currentCityUi);
}
return false;
}
}));
}
this.updateDivisionContent(division);
}
Corporation.prototype.updateDivisionContent = function(division) {
if (!(division instanceof Industry)) {
console.log("ERROR: Invalid 'division' argument in Corporation.updateDivisionContent");
return;
}
var vechain = (this.unlockUpgrades[4] === 1);
//Industry Overview Text
var profit = division.lastCycleRevenue.minus(division.lastCycleExpenses).toNumber(),
profitStr = profit >= 0 ? _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(profit, "$0.000a") : "-" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(-1 * profit, "$0.000a");
var advertisingInfo = "";
if (vechain) {
var advertisingFactors = division.getAdvertisingFactors();
var awarenessFac = advertisingFactors[1];
var popularityFac = advertisingFactors[2];
var ratioFac = advertisingFactors[3];
var totalAdvertisingFac = advertisingFactors[0];
advertisingInfo =
"<p class='tooltip'>Advertising Multiplier: x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(totalAdvertisingFac, 3) +
"<span class='tooltiptext cmpy-mgmt-advertising-info'>Total multiplier for this industry's sales due to its awareness and popularity<br>" +
"Awareness Bonus: x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(Math.pow(awarenessFac, 0.85), 3) + "<br>" +
"Popularity Bonus: x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(Math.pow(popularityFac, 0.85), 3) + "<br>" +
"Ratio Multiplier: x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(Math.pow(ratioFac, 0.85), 3) + "</span></p><br>"
}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_16__["removeChildrenFromElement"])(industryOverviewText);
industryOverviewText.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerHTML:"Industry: " + division.type + " (Corp Funds: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(this.funds.toNumber(), "$0.000a") + ")<br><br>" +
"Awareness: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.awareness, 3) + "<br>" +
"Popularity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.popularity, 3) + "<br>" +
advertisingInfo + "<br>" +
"Revenue: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(division.lastCycleRevenue.toNumber(), "$0.000a") + " / s<br>" +
"Expenses: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_6__[/* numeralWrapper */ "a"].format(division.lastCycleExpenses.toNumber(), "$0.000a") + " /s<br>" +
"Profit: " + profitStr + " / s<br><br>"
}));
industryOverviewText.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
marginTop:"2px",
innerText:"Production Multiplier: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.prodMult, 2),
tooltip:"Production gain from owning production-boosting materials " +
"such as hardware, Robots, AI Cores, and Real Estate"
}));
industryOverviewText.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", {
innerText:"?", class:"help-tip",
clickListener:()=>{
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Owning Hardware, Robots, AI Cores, and Real Estate " +
"can boost your Industry's production. The effect these " +
"materials have on your production varies between Industries. " +
"For example, Real Estate may be very effective for some Industries, " +
"but ineffective for others.<br><br>" +
"This division's production multiplier is calculated by summing " +
"the individual production multiplier of each of its office locations. " +
"This production multiplier is applied to each office. Therefore, it is " +
"beneficial to expand into new cities as this can greatly increase the " +
"production multiplier of your entire Division.");
}
}));
industryOverviewText.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br"));
industryOverviewText.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
display:"inline-block",
innerText:"Scientific Research: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.sciResearch.qty, 3),
tooltip:"Scientific Research increases the quality of the materials and " +
"products that you produce."
}));
//Office and Employee List
var office = division.offices[currentCityUi];
industryEmployeeText.innerHTML =
"<h1>Office Space</h1><br>" +
"Type: " + office.tier + "<br>" +
"Comfort: " + office.comf + "<br>" +
"Beauty: " + office.beau + "<br>" +
"Size: " + office.employees.length + " / " + office.size + " employees";
if (office.employees.length >= office.size) {
industryEmployeeHireButton.className = "a-link-button-inactive";
industryEmployeeAutohireButton.className = "a-link-button-inactive tooltip";
} else if (office.employees.length === 0) {
industryEmployeeHireButton.className = "a-link-button tooltip flashing-button";
industryEmployeeAutohireButton.className = "a-link-button tooltip";
} else {
industryEmployeeHireButton.className = "a-link-button";
industryEmployeeAutohireButton.className = "a-link-button tooltip";
}
//Employee Overview stats
//Calculate average morale, happiness, and energy
var totalMorale = 0, totalHappiness = 0, totalEnergy = 0,
avgMorale = 0, avgHappiness = 0, avgEnergy = 0;
for (var i = 0; i < office.employees.length; ++i) {
totalMorale += office.employees[i].mor;
totalHappiness += office.employees[i].hap;
totalEnergy += office.employees[i].ene;
}
if (office.employees.length > 0) {
avgMorale = totalMorale / office.employees.length;
avgHappiness = totalHappiness / office.employees.length;
avgEnergy = totalEnergy / office.employees.length;
}
industryEmployeeInfo.innerHTML =
"Avg Employee Morale: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(avgMorale, 3) + "<br>" +
"Avg Employee Happiness: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(avgHappiness, 3) + "<br>" +
"Avg Employee Energy: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(avgEnergy, 3);
if (vechain) { //VeChain - Statistics
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Material Production: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.getOfficeProductivity(office), 3),
tooltip: "The base amount of material this office can produce. Does not include " +
"production multipliers from upgrades and materials. This value is based off " +
"the productivity of your Operations, Engineering, and Management employees"
}));
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText:"Product Production: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.getOfficeProductivity(office, {forProduct:true}), 3),
tooltip: "The base amount of any given Product this office can produce. Does not include " +
"production multipliers from upgrades and materials. This value is based off " +
"the productivity of your Operations, Engineering, and Management employees"
}));
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("br", {}));
industryEmployeeInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", {
innerText: "Business Multiplier: x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(division.getBusinessFactor(office), 3),
tooltip: "The effect this office's 'Business' employees has on boosting sales"
}));
}
//Warehouse
var warehouse = division.warehouses[currentCityUi];
if (warehouse instanceof Warehouse) {
warehouse.updateUI({industry:division, company:this});
}
}
Corporation.prototype.createCityUITab = function(city, division) {
var tab = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_10__["createElement"])("button", {
id:"cmpy-mgmt-city-" + city + "-tab",
class:"cmpy-mgmt-city-tab",
innerText:city,
clickListener:()=>{
this.selectCityTab(tab, city);
this.displayDivisionContent(division, city);
return false;
}
});
companyManagementPanel.appendChild(tab);
}
Corporation.prototype.selectCityTab = function(activeTab, city) {
if (activeTab == null) {
activeTab = document.getElementById("cmpy-mgmt-city-" + city + "-tab");
if (activeTab == null) {return;}
}
for (var i = 0; i < cityTabs.length; ++i) {
cityTabs[i].className = "cmpy-mgmt-city-tab";
}
activeTab.className = "cmpy-mgmt-city-tab current";
}
Corporation.prototype.clearUI = function() {
//Delete everything
if (companyManagementDiv != null) {Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_17__["removeElementById"])(companyManagementDiv.id);}
//Reset global DOM variables
companyManagementDiv = null;
companyManagementPanel = null;
currentCityUi = null;
corporationUnlockUpgrades = null;
corporationUpgrades = null;
industryOverviewPanel = null;
industryOverviewText = null;
industryEmployeePanel = null;
industryEmployeeText = null;
industryEmployeeHireButton = null;
industryEmployeeAutohireButton = null;
industryEmployeeManagementUI = null;
industryEmployeeInfo = null;
industryIndividualEmployeeInfo = null;
industryOfficeUpgradeSizeButton = null;
industryWarehousePanel = null;
industrySmartSupplyCheckbox = null;
industryWarehouseStorageText = null;
industryWarehouseUpgradeSizeButton = null;
industryWarehouseStateText = null;
industryWarehouseMaterials = null;
industryWarehouseProducts = null;
companyManagementHeaderTabs = null;
headerTabs = null;
cityTabs = null;
document.getElementById("character-overview-wrapper").style.visibility = "visible";
}
Corporation.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Corporation", this);
}
Corporation.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Corporation, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Corporation = Corporation;
/***/ }),
/* 59 */
/*!*********************************************!*\
!*** ./utils/uiHelpers/appendLineBreaks.ts ***!
\*********************************************/
/*! no static exports found */
/*! exports used: appendLineBreaks */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const createElement_1 = __webpack_require__(/*! ./createElement */ 2);
/**
* Appends the specified number of breaks (as children) to the specified element
* @param el The element to add child break elements to.
* @param n The number of breaks to add.
*/
function appendLineBreaks(el, n) {
for (let i = 0; i < n; ++i) {
el.appendChild(createElement_1.createElement("br"));
}
}
exports.appendLineBreaks = appendLineBreaks;
/***/ }),
/* 60 */
/*!*************************!*\
!*** ./src/TextFile.ts ***!
\*************************/
/*! no static exports found */
/*! exports used: TextFile, createTextFile, getTextFile */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DialogBox_1 = __webpack_require__(/*! ../utils/DialogBox */ 9);
const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/**
* Represents a plain text file that is typically stored on a server.
*/
class TextFile {
/**
* Initiatizes a TextFile from a JSON save state.
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(TextFile, value.data);
}
constructor(fn = "", txt = "") {
this.fn = (fn.endsWith(".txt") ? fn : `${fn}.txt`).replace(/\s+/g, "");
this.text = txt;
}
/**
* Concatenates the raw values to the end of current content.
*/
append(txt) {
this.text += txt;
}
/**
* Serves the file to the user as a downloadable resource through the browser.
*/
download() {
const filename = this.fn;
const file = new Blob([this.text], { type: "text/plain" });
/* tslint:disable-next-line:strict-boolean-expressions */
if (window.navigator.msSaveOrOpenBlob) {
// IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
}
else {
// Others
const a = document.createElement("a");
const url = URL.createObjectURL(file);
a.href = url;
a.download = this.fn;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
/**
* Retrieve the content of the file.
*/
read() {
return this.text;
}
/**
* Shows the content to the user via the game's dialog box.
*/
show() {
DialogBox_1.dialogBoxCreate(`${this.fn}<br /><br />${this.text}`, true);
}
/**
* Serialize the current file to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("TextFile", this);
}
/**
* Replaces the current content with the text provided.
*/
write(txt) {
this.text = txt;
}
}
exports.TextFile = TextFile;
JSONReviver_1.Reviver.constructors.TextFile = TextFile;
/**
* Retrieve the file object for the filename on the specified server.
* @param fn The file name to look for
* @param server The server object to look in
* @returns The file object, or null if it couldn't find it.
*/
function getTextFile(fn, server) {
const filename = !fn.endsWith(".txt") ? `${fn}.txt` : fn;
for (const file of server.textFiles) {
if (file.fn === filename) {
return file;
}
}
return null;
}
exports.getTextFile = getTextFile;
/**
* Creates a TextFile on the target server.
* @param fn The file name to create.
* @param txt The contents of the file.
* @param server The server that the file should be created on.
* @returns The instance of the file.
*/
function createTextFile(fn, txt, server) {
if (getTextFile(fn, server) !== null) {
// This should probably be a `throw`...
/* tslint:disable-next-line:no-console */
console.error(`A file named "${fn}" already exists on server ${server.hostname}.`);
return undefined;
}
const file = new TextFile(fn, txt);
server.textFiles.push(file);
return file;
}
exports.createTextFile = createTextFile;
/* tslint:disable-next-line:no-unused-variable */
function deleteTextFile(fn, server) {
const filename = !fn.endsWith(".txt") ? `${fn}.txt` : fn;
/* tslint:disable-next-line:typedef */
for (let i = 0; i < server.textFiles.length; ++i) {
if (server.textFiles[i].fn === filename) {
server.textFiles.splice(i, 1);
return true;
}
}
return false;
}
/***/ }),
/* 61 */
/*!************************************!*\
!*** ./utils/helpers/addOffset.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: addOffset */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Adds a random offset to a number within a certain percentage
* @example
* // Returns between 95-105
* addOffset(100, 5);
* @example
* // Returns between 63-77
* addOffSet(70, 10);
* @param midpoint The number to be the midpoint of the offset range
* @param percentage The percentage (in a range of 0-100) to offset
*/
function addOffset(midpoint, percentage) {
const maxPercent = 100;
if (percentage < 0 || percentage > maxPercent) {
return midpoint;
}
const offset = midpoint * (percentage / maxPercent);
// Double the range to account for both sides of the midpoint.
// tslint:disable-next-line:no-magic-numbers
return midpoint + ((Math.random() * (offset * 2)) - offset);
}
exports.addOffset = addOffset;
/***/ }),
/* 62 */,
/* 63 */
/*!****************************!*\
!*** ./src/HacknetNode.js ***!
\****************************/
/*! exports provided: HacknetNode, displayHacknetNodesContent, getCostOfNextHacknetNode, getHacknetNode, getMaxNumberLevelUpgrades, hacknetNodesInit, processAllHacknetNodeEarnings, purchaseHacknet, updateHacknetNodesContent, updateHacknetNodesMultiplierButtons, updateTotalHacknetProduction */
/*! exports used: HacknetNode, displayHacknetNodesContent, getCostOfNextHacknetNode, processAllHacknetNodeEarnings, purchaseHacknet, updateHacknetNodesContent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HacknetNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return displayHacknetNodesContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getCostOfNextHacknetNode; });
/* unused harmony export getHacknetNode */
/* unused harmony export getMaxNumberLevelUpgrades */
/* unused harmony export hacknetNodesInit */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return processAllHacknetNodeEarnings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return purchaseHacknet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return updateHacknetNodesContent; });
/* unused harmony export updateHacknetNodesMultiplierButtons */
/* unused harmony export updateTotalHacknetProduction */
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial */ 33);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/uiHelpers/getElementById */ 51);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__);
/**
* Overwrites the inner text of the specified HTML element if it is different from what currently exists.
* @param {string} elementId The HTML ID to find the first instance of.
* @param {string} text The inner text that should be set.
*/
function updateText(elementId, text) {
var el = Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])(elementId);
if (el.innerText != text) {
el.innerText = text;
}
};
/* HacknetNode.js */
function hacknetNodesInit() {
var performMapping = function(x) {
Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])("hacknet-nodes-" + x.id + "-multiplier")
.addEventListener("click", function() {
hacknetNodePurchaseMultiplier = x.multiplier;
updateHacknetNodesMultiplierButtons();
updateHacknetNodesContent();
return false;
});
};
var mappings = [
{ id: "1x", multiplier: 1 },
{ id: "5x", multiplier: 5 },
{ id: "10x", multiplier: 10 },
{ id: "max", multiplier: 0 }
];
for (var elem of mappings) {
// Encapsulate in a function so that the appropriate scope is kept in the click handler.
performMapping(elem);
}
}
document.addEventListener("DOMContentLoaded", hacknetNodesInit, false);
function HacknetNode(name) {
this.level = 1;
this.ram = 1; //GB
this.cores = 1;
this.name = name;
this.totalMoneyGenerated = 0;
this.onlineTimeSeconds = 0;
this.moneyGainRatePerSecond = 0;
}
HacknetNode.prototype.updateMoneyGainRate = function() {
//How much extra $/s is gained per level
var gainPerLevel = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMoneyGainPerLevel;
this.moneyGainRatePerSecond = (this.level * gainPerLevel) *
Math.pow(1.035, this.ram-1) *
((this.cores + 5) / 6) *
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknet_node_money_mult *
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney;
if (isNaN(this.moneyGainRatePerSecond)) {
this.moneyGainRatePerSecond = 0;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("Error in calculating Hacknet Node production. Please report to game developer");
}
updateTotalHacknetProduction();
}
HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) {
levels = Math.round(levels);
if (isNaN(levels) || levels < 1) {
return 0;
}
if (this.level >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) {
return Infinity;
}
var mult = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeLevelMult;
var totalMultiplier = 0; //Summed
var currLevel = this.level;
for (var i = 0; i < levels; ++i) {
totalMultiplier += Math.pow(mult, currLevel);
++currLevel;
}
return _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode / 2 * totalMultiplier * _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknet_node_level_cost_mult;
}
HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) {
levels = Math.round(levels);
var cost = this.calculateLevelUpgradeCost(levels);
if (isNaN(cost) || levels < 0) {
return false;
}
//If we're at max level, return false
if (this.level >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) {
return false;
}
//If the number of specified upgrades would exceed the max level, calculate
//the maximum number of upgrades and use that
if (this.level + levels > _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) {
var diff = Math.max(0, _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - this.level);
return this.purchaseLevelUpgrade(diff);
}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(cost);
this.level = Math.round(this.level + levels); //Just in case of floating point imprecision
this.updateMoneyGainRate();
return true;
}
HacknetNode.prototype.calculateRamUpgradeCost = function(levels=1) {
levels = Math.round(levels);
if (isNaN(levels) || levels < 1) {
return 0;
}
if (this.ram >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) {
return Infinity;
}
let totalCost = 0;
let numUpgrades = Math.round(Math.log2(this.ram));
let currentRam = this.ram;
for (let i = 0; i < levels; ++i) {
let baseCost = currentRam * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostFor1GBOfRamHacknetNode;
let mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeRamMult, numUpgrades);
totalCost += (baseCost * mult);
currentRam *= 2;
++numUpgrades;
}
totalCost *= _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknet_node_ram_cost_mult
return totalCost;
}
HacknetNode.prototype.purchaseRamUpgrade = function(levels=1) {
levels = Math.round(levels);
var cost = this.calculateRamUpgradeCost(levels);
if (isNaN(cost) || levels < 0) {
return false;
}
// Fail if we're already at max
if (this.ram >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].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 (this.ram * Math.pow(2, levels) > _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) {
var diff = Math.max(0, Math.log2(Math.round(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam / this.ram)));
return this.purchaseRamUpgrade(diff);
}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(cost);
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();
return true;
}
HacknetNode.prototype.calculateCoreUpgradeCost = function(levels=1) {
levels = Math.round(levels);
if (isNaN(levels) || levels < 1) {
return 0;
}
if (this.cores >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) {
return Infinity;
}
const coreBaseCost = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNodeCore;
const mult = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeCoreMult;
let totalCost = 0;
let currentCores = this.cores;
for (let i = 0; i < levels; ++i) {
totalCost += (coreBaseCost * Math.pow(mult, currentCores-1));
++currentCores;
}
totalCost *= _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknet_node_core_cost_mult;
return totalCost;
}
HacknetNode.prototype.purchaseCoreUpgrade = function(levels=1) {
levels = Math.round(levels);
var cost = this.calculateCoreUpgradeCost(levels);
if (isNaN(cost) || levels < 0) {
return false;
}
//Fail if we're already at max
if (this.cores >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].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 (this.cores + levels > _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) {
var diff = Math.max(0, _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores - this.cores);
return this.purchaseCoreUpgrade(diff);
}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(cost);
this.cores = Math.round(this.cores + levels); //Just in case of floating point imprecision
this.updateMoneyGainRate();
return true;
}
/* Saving and loading HackNets */
HacknetNode.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_7__["Generic_toJSON"])("HacknetNode", this);
}
HacknetNode.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_7__["Generic_fromJSON"])(HacknetNode, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_7__["Reviver"].constructors.HacknetNode = HacknetNode;
function purchaseHacknet() {
/* INTERACTIVE TUTORIAL */
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].isRunning) {
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialSteps */ "d"].HacknetNodesIntroduction) {
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialNextStep */ "b"])();
} else {
return;
}
}
/* END INTERACTIVE TUTORIAL */
var cost = getCostOfNextHacknetNode();
if (isNaN(cost)) {
throw new Error("Cost is NaN");
}
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(cost)) {
//dialogBoxCreate("You cannot afford to purchase a Hacknet Node!");
return -1;
}
//Auto generate a name for the node for now...TODO
var numOwned = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length;
var name = "hacknet-node-" + numOwned;
var node = new HacknetNode(name);
node.updateMoneyGainRate();
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.push(node);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].HacknetNodes)) {
displayHacknetNodesContent();
}
updateTotalHacknetProduction();
return numOwned;
}
//Calculates the total production from all HacknetNodes
function updateTotalHacknetProduction() {
var total = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length; ++i) {
total += _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i].moneyGainRatePerSecond;
}
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].totalHacknetNodeProduction = total;
}
function getCostOfNextHacknetNode() {
//Cost increases exponentially based on how many you own
var numOwned = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length;
var mult = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodePurchaseNextMult;
return _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode * Math.pow(mult, numOwned) * _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknet_node_purchase_cost_mult;
}
var hacknetNodePurchaseMultiplier = 1;
function updateHacknetNodesMultiplierButtons() {
var mult1x = document.getElementById("hacknet-nodes-1x-multiplier");
var mult5x = document.getElementById("hacknet-nodes-5x-multiplier");
var mult10x = document.getElementById("hacknet-nodes-10x-multiplier");
var multMax = document.getElementById("hacknet-nodes-max-multiplier");
mult1x.setAttribute("class", "a-link-button");
mult5x.setAttribute("class", "a-link-button");
mult10x.setAttribute("class", "a-link-button");
multMax.setAttribute("class", "a-link-button");
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length == 0) {
mult1x.setAttribute("class", "a-link-button-inactive");
mult5x.setAttribute("class", "a-link-button-inactive");
mult10x.setAttribute("class", "a-link-button-inactive");
multMax.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 1) {
mult1x.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 5) {
mult5x.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 10) {
mult10x.setAttribute("class", "a-link-button-inactive");
} else {
multMax.setAttribute("class", "a-link-button-inactive");
}
}
//Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node
function getMaxNumberLevelUpgrades(nodeObj) {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {
return 0;
}
var min = 1;
var max = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - 1;
var levelsToMax = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level;
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) {
return levelsToMax;
}
while (min <= max) {
var curr = (min + max) / 2 | 0;
if (curr != _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel &&
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) &&
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateLevelUpgradeCost(curr + 1))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
function getMaxNumberRamUpgrades(nodeObj) {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateRamUpgradeCost(1))) {
return 0;
}
const levelsToMax = Math.round(Math.log2(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam / nodeObj.ram));
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateRamUpgradeCost(levelsToMax))) {
return levelsToMax;
}
//We'll just loop until we find the max
for (let i = levelsToMax-1; i >= 0; --i) {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateRamUpgradeCost(i))) {
return i;
}
}
return 0;
}
function getMaxNumberCoreUpgrades(nodeObj) {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateCoreUpgradeCost(1))) {
return 0;
}
var min = 1;
var max = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores - 1;
const levelsToMax = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores - nodeObj.cores;
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateCoreUpgradeCost(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 != _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores &&
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateCoreUpgradeCost(curr)) &&
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateCoreUpgradeCost(curr + 1))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(nodeObj.calculateCoreUpgradeCost(curr))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gt(nodeObj.calculateCoreUpgradeCost(curr))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
//Creates Hacknet Node DOM elements when the page is opened
function displayHacknetNodesContent() {
//Update Hacknet Nodes button
var newPurchaseButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("hacknet-nodes-purchase-button");
newPurchaseButton.addEventListener("click", function() {
purchaseHacknet();
return false;
});
//Handle Purchase multiplier buttons
updateHacknetNodesMultiplierButtons();
//Remove all old hacknet Node DOM elements
var hacknetNodesList = document.getElementById("hacknet-nodes-list");
while (hacknetNodesList.firstChild) {
hacknetNodesList.removeChild(hacknetNodesList.firstChild);
}
//Then re-create them
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length; ++i) {
createHacknetNodeDomElement(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i]);
}
updateHacknetNodesContent();
}
//Update information on all Hacknet Node DOM elements
function updateHacknetNodesContent() {
//Set purchase button to inactive if not enough money, and update its price display
var cost = getCostOfNextHacknetNode();
var purchaseButton = Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])("hacknet-nodes-purchase-button");
var formattedCost = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(cost, 2);
updateText("hacknet-nodes-purchase-button", "Purchase Hacknet Node - $" + formattedCost);
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(cost)) {
purchaseButton.setAttribute("class", "a-link-button-inactive");
} else {
purchaseButton.setAttribute("class", "a-link-button");
}
//Update player's money
updateText("hacknet-nodes-player-money", "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.toNumber(), 2));
updateText("hacknet-nodes-total-production", "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].totalHacknetNodeProduction, 2) + " / sec");
//Update information in each owned hacknet node
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length; ++i) {
updateHacknetNodeDomElement(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i]);
}
}
//Creates a single Hacknet Node DOM element
function createHacknetNodeDomElement(nodeObj) {
var nodeName = nodeObj.name;
var nodeLevelContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", {
class: "hacknet-node-level-container row",
innerHTML: "<p>Level:</p><span class=\"text upgradable-info\" id=\"hacknet-node-level-" + nodeName + "\"></span>"
});
var nodeRamContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", {
class: "hacknet-node-ram-container row",
innerHTML: "<p>RAM:</p><span class=\"text upgradable-info\" id=\"hacknet-node-ram-" + nodeName + "\"></span>"
});
var nodeCoresContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", {
class: "hacknet-node-cores-container row",
innerHTML: "<p>Cores:</p><span class=\"text upgradable-info\" id=\"hacknet-node-cores-" + nodeName + "\"><span>"
})
var containingDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", {
class: "hacknet-node-container",
innerHTML: "<div class=\"hacknet-node-name-container row\">" +
"<p>Node name:</p>" +
"<span class=\"text\" id=\"hacknet-node-name-" + nodeName + "\"></span>" +
"</div>" +
"<div class=\"hacknet-node-production-container row\">" +
"<p>Production:</p>" +
"<span class=\"text\" id=\"hacknet-node-total-production-" + nodeName + "\"></span>" +
"<span class=\"text\" id=\"hacknet-node-production-rate-" + nodeName + "\"></span>" +
"</div>"
});
containingDiv.appendChild(nodeLevelContainer);
containingDiv.appendChild(nodeRamContainer);
containingDiv.appendChild(nodeCoresContainer);
var listItem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("li", {
class: "hacknet-node"
});
listItem.appendChild(containingDiv);
//Upgrade buttons
nodeLevelContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", {
id: "hacknet-node-upgrade-level-" + nodeName,
class: "a-link-button-inactive",
clickListener: function() {
let numUpgrades = hacknetNodePurchaseMultiplier;
if (hacknetNodePurchaseMultiplier == 0) {
numUpgrades = getMaxNumberLevelUpgrades(nodeObj);
}
nodeObj.purchaseLevelUpgrade(numUpgrades);
updateHacknetNodesContent();
return false;
}
}));
nodeRamContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", {
id: "hacknet-node-upgrade-ram-" + nodeName,
class: "a-link-button-inactive",
clickListener: function() {
let numUpgrades = hacknetNodePurchaseMultiplier;
if (hacknetNodePurchaseMultiplier == 0) {
numUpgrades = getMaxNumberRamUpgrades(nodeObj);
}
nodeObj.purchaseRamUpgrade(numUpgrades);
updateHacknetNodesContent();
return false;
}
}));
nodeCoresContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", {
id: "hacknet-node-upgrade-core-" + nodeName,
class: "a-link-button-inactive",
clickListener: function() {
let numUpgrades = hacknetNodePurchaseMultiplier;
if (hacknetNodePurchaseMultiplier == 0) {
numUpgrades = getMaxNumberCoreUpgrades(nodeObj);
}
nodeObj.purchaseCoreUpgrade(numUpgrades);
updateHacknetNodesContent();
return false;
}
}));
document.getElementById("hacknet-nodes-list").appendChild(listItem);
//Set the text and stuff inside the DOM element
updateHacknetNodeDomElement(nodeObj);
}
//Updates information on a single hacknet node DOM element
function updateHacknetNodeDomElement(nodeObj) {
var nodeName = nodeObj.name;
updateText("hacknet-node-name-" + nodeName, nodeName);
updateText("hacknet-node-total-production-" + nodeName, "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(nodeObj.totalMoneyGenerated, 2));
updateText("hacknet-node-production-rate-" + nodeName, "($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(nodeObj.moneyGainRatePerSecond, 2) + " / sec)");
updateText("hacknet-node-level-" + nodeName, nodeObj.level);
updateText("hacknet-node-ram-" + nodeName, nodeObj.ram + "GB");
updateText("hacknet-node-cores-" + nodeName, nodeObj.cores);
//Upgrade level
var upgradeLevelButton = Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])("hacknet-node-upgrade-level-" + nodeName);
if (nodeObj.level >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) {
updateText("hacknet-node-upgrade-level-" + nodeName, "MAX LEVEL");
upgradeLevelButton.setAttribute("class", "a-link-button-inactive");
} else {
let multiplier = 0;
if (hacknetNodePurchaseMultiplier == 0) {
//Max
multiplier = getMaxNumberLevelUpgrades(nodeObj);
} else {
var levelsToMax = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level;
multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier);
}
var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier);
updateText("hacknet-node-upgrade-level-" + nodeName, "Upgrade x" + multiplier + " - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(upgradeLevelCost, 2))
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(upgradeLevelCost)) {
upgradeLevelButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeLevelButton.setAttribute("class", "a-link-button");
}
}
//Upgrade RAM
var upgradeRamButton = Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])("hacknet-node-upgrade-ram-" + nodeName);
if (nodeObj.ram >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) {
updateText("hacknet-node-upgrade-ram-" + nodeName, "MAX RAM");
upgradeRamButton.setAttribute("class", "a-link-button-inactive");
} else {
let multiplier = 0;
if (hacknetNodePurchaseMultiplier == 0) {
multiplier = getMaxNumberRamUpgrades(nodeObj);
} else {
var levelsToMax = Math.round(Math.log2(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam / nodeObj.ram));
multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier);
}
var upgradeRamCost = nodeObj.calculateRamUpgradeCost(multiplier);
updateText("hacknet-node-upgrade-ram-" + nodeName, "Upgrade x" + multiplier + " - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(upgradeRamCost, 2));
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(upgradeRamCost)) {
upgradeRamButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeRamButton.setAttribute("class", "a-link-button");
}
}
//Upgrade Cores
var upgradeCoreButton = Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_11__["getElementById"])("hacknet-node-upgrade-core-" + nodeName);
if (nodeObj.cores >= _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) {
updateText("hacknet-node-upgrade-core-" + nodeName, "MAX CORES");
upgradeCoreButton.setAttribute("class", "a-link-button-inactive");
} else {
let multiplier = 0;
if (hacknetNodePurchaseMultiplier == 0) {
multiplier = getMaxNumberCoreUpgrades(nodeObj);
} else {
var levelsToMax = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores - nodeObj.cores;
multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier);
}
var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(multiplier);
updateText("hacknet-node-upgrade-core-" + nodeName, "Upgrade x" + multiplier + " - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(upgradeCoreCost, 2));
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(upgradeCoreCost)) {
upgradeCoreButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeCoreButton.setAttribute("class", "a-link-button");
}
}
}
function processAllHacknetNodeEarnings(numCycles) {
var total = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length; ++i) {
total += processSingleHacknetNodeEarnings(numCycles, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i]);
}
return total;
}
function processSingleHacknetNodeEarnings(numCycles, nodeObj) {
var cyclesPerSecond = 1000 / _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed;
var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond;
if (isNaN(earningPerCycle)) {
console.error("Hacknet Node '" + nodeObj.name + "' Calculated earnings is NaN");
earningPerCycle = 0;
}
var totalEarnings = numCycles * earningPerCycle;
nodeObj.totalMoneyGenerated += totalEarnings;
nodeObj.onlineTimeSeconds += (numCycles * (_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed / 1000));
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(totalEarnings);
return totalEarnings;
}
function getHacknetNode(name) {
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i].name == name) {
return _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hacknetNodes[i];
}
}
return null;
}
/***/ }),
/* 64 */
/*!********************************!*\
!*** ./src/ActiveScriptsUI.js ***!
\********************************/
/*! exports provided: addActiveScriptsItem, deleteActiveScriptsItem, updateActiveScriptsItems */
/*! exports used: addActiveScriptsItem, deleteActiveScriptsItem, updateActiveScriptsItems */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addActiveScriptsItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deleteActiveScriptsItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return updateActiveScriptsItems; });
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/createAccordionElement */ 73);
/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 52);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/createProgressBarText */ 79);
/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/uiHelpers/getElementById */ 51);
/* harmony import */ var _utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/LogBox */ 75);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/removeElement */ 67);
/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 77);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./ui/navigationTracking */ 12);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__);
/* {
* serverName: {
* header: Server Header Element
* panel: Server Panel List (ul) element
* scripts: {
* script id: Ref to Script information
* }
* }
* ...
*/
let ActiveScriptsUI = {};
let ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements
const getHeaderHtml = (server) => {
// TODO: calculate the longest hostname length rather than hard coding it
const longestHostnameLength = 18;
const paddedName = `${server.hostname}${" ".repeat(longestHostnameLength)}`.slice(0, Math.max(server.hostname.length, longestHostnameLength));
const barOptions = {
progress: server.ramUsed / server.maxRam,
totalTicks: 30
};
return `${paddedName} ${Object(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])(barOptions)}`.replace(/\s/g, '&nbsp;');
};
const updateHeaderHtml = (server) => {
const accordion = ActiveScriptsUI[server.hostname];
if (accordion === null || accordion === undefined) {
return;
}
// convert it to a string, as that's how it's stored it will come out of the data attributes
const ramPercentage = '' + Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_15__["roundToTwo"])(server.ramUsed / server.maxRam);
if (accordion.header.dataset.ramPercentage !== ramPercentage) {
accordion.header.dataset.ramPercentage = ramPercentage;
accordion.header.innerHTML = getHeaderHtml(server);
}
}
function createActiveScriptsServerPanel(server) {
let hostname = server.hostname;
var activeScriptsList = document.getElementById("active-scripts-list");
let res = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({
hdrText: getHeaderHtml(server)
});
let li = res[0];
var hdr = res[1];
let panel = res[2];
if (ActiveScriptsUI[hostname] != null) {
console.log("WARNING: Tried to create already-existing Active Scripts Server panel. This is most likely fine. It probably means many scripts just got started up on a new server. Aborting");
return;
}
var panelScriptList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("ul");
panel.appendChild(panelScriptList);
activeScriptsList.appendChild(li);
ActiveScriptsUI[hostname] = {
header: hdr,
panel: panel,
panelList: panelScriptList,
scripts: {}, //Holds references to li elements for each active script
scriptHdrs: {}, //Holds references to header elements for each active script
scriptStats: {} //Holds references to the p elements containing text for each active script
};
return li;
}
//Deletes the info for a particular server (Dropdown header + Panel with all info)
//in the Active Scripts page if it exists
function deleteActiveScriptsServerPanel(server) {
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null) {
console.log("WARNING: Tried to delete non-existent Active Scripts Server panel. Aborting");
return;
}
//Make sure it's empty
if (Object.keys(ActiveScriptsUI[hostname].scripts).length > 0) {
console.log("WARNING: Tried to delete Active Scripts Server panel that still has scripts. Aborting");
return;
}
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14__["removeElement"])(ActiveScriptsUI[hostname].panel);
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14__["removeElement"])(ActiveScriptsUI[hostname].header);
delete ActiveScriptsUI[hostname];
}
function addActiveScriptsItem(workerscript) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_2__[/* getServer */ "e"])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript in addActiveScriptsItem()");
return;
}
let hostname = server.hostname;
ActiveScriptsTasks.push(function(workerscript, hostname) {
if (ActiveScriptsUI[hostname] == null) {
createActiveScriptsServerPanel(server);
}
//Create the unique identifier (key) for this script
var itemNameArray = ["active", "scripts", hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(String(workerscript.args[i]));
}
var itemName = itemNameArray.join("-");
let res = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({hdrText:workerscript.name});
let li = res[0];
let hdr = res[1];
let panel = res[2];
hdr.classList.remove("accordion-header");
hdr.classList.add("active-scripts-script-header");
panel.classList.remove("accordion-panel");
panel.classList.add("active-scripts-script-panel");
//Handle the constant elements on the panel that don't change after creation
//Threads, args, kill/log button
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("p", {
innerHTML: "Threads: " + workerscript.scriptRef.threads + "<br>" +
"Args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_6__["arrayToString"])(workerscript.args)
}));
var panelText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("p", {
innerText: "Loading...",
fontSize: "14px",
});
panel.appendChild(panelText);
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("br"));
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("span", {
innerText: "Log",
class: "accordion-button",
margin: "4px",
padding: "4px",
clickListener: () => {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_11__[/* logBoxCreate */ "a"])(workerscript.scriptRef);
return false;
}
}));
panel.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("span", {
innerText: "Kill Script",
class: "accordion-button",
margin: "4px",
padding: "4px",
clickListener: () => {
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__[/* killWorkerScript */ "d"])(workerscript.scriptRef, workerscript.scriptRef.scriptRef.server);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Killing script, may take a few minutes to complete...");
return false;
}
}));
//Append element to list
ActiveScriptsUI[hostname]["panelList"].appendChild(li);
ActiveScriptsUI[hostname].scripts[itemName] = li;
ActiveScriptsUI[hostname].scriptHdrs[itemName] = hdr;
ActiveScriptsUI[hostname].scriptStats[itemName] = panelText;
}.bind(null, workerscript, hostname));
}
function deleteActiveScriptsItem(workerscript) {
ActiveScriptsTasks.push(function(workerscript) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_2__[/* getServer */ "e"])(workerscript.serverIp);
if (server == null) {
throw new Error("ERROR: Invalid server IP for workerscript. This most likely occurred because " +
"you tried to delete a large number of scripts and also deleted servers at the " +
"same time. It's not a big deal, just save and refresh the game.");
return;
}
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null) {
console.log("ERROR: Trying to delete Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname);
return;
}
var itemNameArray = ["active", "scripts", server.hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(String(workerscript.args[i]));
}
var itemName = itemNameArray.join("-");
let li = ActiveScriptsUI[hostname].scripts[itemName];
if (li == null) {
console.log("ERROR: Cannot find Active Script UI element for workerscript: ");
console.log(workerscript);
return;
}
Object(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_14__["removeElement"])(li);
delete ActiveScriptsUI[hostname].scripts[itemName];
delete ActiveScriptsUI[hostname].scriptHdrs[itemName];
delete ActiveScriptsUI[hostname].scriptStats[itemName];
if (Object.keys(ActiveScriptsUI[hostname].scripts).length === 0) {
deleteActiveScriptsServerPanel(server);
}
}.bind(null, workerscript));
}
//Update the ActiveScriptsItems array
function updateActiveScriptsItems(maxTasks=150) {
//Run tasks that need to be done sequentially (adding items, creating/deleting server panels)
//We'll limit this to 150 at a time in case someone decides to start a bunch of scripts all at once...
let numTasks = Math.min(maxTasks, ActiveScriptsTasks.length);
for (let i = 0; i < numTasks; ++i) {
let task = ActiveScriptsTasks.shift();
try {
task();
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_9__[/* exceptionAlert */ "a"])(e);
console.log(task);
}
}
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__["Page"].ActiveScripts)) {return;}
var total = 0;
for (var i = 0; i < _NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__[/* workerScripts */ "h"].length; ++i) {
try {
total += updateActiveScriptsItemContent(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__[/* workerScripts */ "h"][i]);
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_9__[/* exceptionAlert */ "a"])(e);
}
}
Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10__["getElementById"])("active-scripts-total-production-active").innerText = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_3__[/* numeralWrapper */ "a"].format(total, '$0.000a');
Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10__["getElementById"])("active-scripts-total-prod-aug-total").innerText = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_3__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].scriptProdSinceLastAug, '$0.000a');
Object(_utils_uiHelpers_getElementById__WEBPACK_IMPORTED_MODULE_10__["getElementById"])("active-scripts-total-prod-aug-avg").innerText = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_3__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].scriptProdSinceLastAug / (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].playtimeSinceLastAug/1000), '$0.000a');
return total;
}
//Updates the content of the given item in the Active Scripts list
function updateActiveScriptsItemContent(workerscript) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_2__[/* getServer */ "e"])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript.");
return;
}
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null) {
return; //Hasn't been created yet. We'll skip it
}
updateHeaderHtml(server);
var itemNameArray = ["active", "scripts", server.hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(String(workerscript.args[i]));
}
var itemName = itemNameArray.join("-");
if (ActiveScriptsUI[hostname].scriptStats[itemName] == null) {
return; //Hasn't been fully added yet. We'll skip it
}
var item = ActiveScriptsUI[hostname].scriptStats[itemName];
//Update the text if necessary. This fn returns the online $/s production
return updateActiveScriptsText(workerscript, item, itemName);
}
function updateActiveScriptsText(workerscript, item, itemName) {
var server = Object(_Server__WEBPACK_IMPORTED_MODULE_2__[/* getServer */ "e"])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript.");
return;
}
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null || ActiveScriptsUI[hostname].scriptHdrs[itemName] == null) {
console.log("ERROR: Trying to update Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname);
return;
}
updateHeaderHtml(server);
var onlineMps = workerscript.scriptRef.onlineMoneyMade / workerscript.scriptRef.onlineRunningTime;
//Only update if the item is visible
if (ActiveScriptsUI[hostname].header.classList.contains("active") === false) {return onlineMps;}
if (ActiveScriptsUI[hostname].scriptHdrs[itemName].classList.contains("active") === false) {return onlineMps;}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(item);
//Online
var onlineTotalMoneyMade = "Total online production: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(workerscript.scriptRef.onlineMoneyMade, 2);
var onlineTotalExpEarned = (Array(26).join(" ") + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(workerscript.scriptRef.onlineExpGained, 2) + " hacking exp").replace( / /g, "&nbsp;");
var onlineMpsText = "Online production rate: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(onlineMps, 2) + "/second";
var onlineEps = workerscript.scriptRef.onlineExpGained / workerscript.scriptRef.onlineRunningTime;
var onlineEpsText = (Array(25).join(" ") + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(onlineEps, 4) + " hacking exp/second").replace( / /g, "&nbsp;");
//Offline
var offlineTotalMoneyMade = "Total offline production: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(workerscript.scriptRef.offlineMoneyMade, 2);
var offlineTotalExpEarned = (Array(27).join(" ") + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(workerscript.scriptRef.offlineExpGained, 2) + " hacking exp").replace( / /g, "&nbsp;");
var offlineMps = workerscript.scriptRef.offlineMoneyMade / workerscript.scriptRef.offlineRunningTime;
var offlineMpsText = "Offline production rate: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(offlineMps, 2) + "/second";
var offlineEps = workerscript.scriptRef.offlineExpGained / workerscript.scriptRef.offlineRunningTime;
var offlineEpsText = (Array(26).join(" ") + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_12__["formatNumber"])(offlineEps, 4) + " hacking exp/second").replace( / /g, "&nbsp;");
item.innerHTML = onlineTotalMoneyMade + "<br>" + onlineTotalExpEarned + "<br>" +
onlineMpsText + "<br>" + onlineEpsText + "<br>" + offlineTotalMoneyMade + "<br>" + offlineTotalExpEarned + "<br>" +
offlineMpsText + "<br>" + offlineEpsText + "<br>";
return onlineMps;
}
/***/ }),
/* 65 */,
/* 66 */
/*!***************************!*\
!*** ./src/SourceFile.js ***!
\***************************/
/*! exports provided: SourceFiles, PlayerOwnedSourceFile, applySourceFile, initSourceFiles */
/*! exports used: PlayerOwnedSourceFile, SourceFiles, applySourceFile, initSourceFiles */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SourceFiles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerOwnedSourceFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return applySourceFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initSourceFiles; });
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode */ 56);
/* SourceFile.js */
//Each SourceFile corresponds to a BitNode with the same number
function SourceFile(number, info="") {
var bitnodeKey = "BitNode" + number;
var bitnode = _BitNode__WEBPACK_IMPORTED_MODULE_1__[/* BitNodes */ "a"][bitnodeKey];
if (bitnode == null) {
throw new Error("Invalid Bit Node for this Source File");
}
this.n = number;
this.name = "Source-File " + number + ": " + bitnode.name;
this.lvl = 1;
this.info = info;
this.owned = false;
}
let SourceFiles = {};
function initSourceFiles() {
SourceFiles = {};
SourceFiles["SourceFile1"] = new SourceFile(1, "This Source-File lets the player start with 32GB of RAM on his/her " +
"home computer. It also increases all of the player's multipliers by:<br><br>" +
"Level 1: 16%<br>" +
"Level 2: 24%<br>" +
"Level 3: 28%");
SourceFiles["SourceFile2"] = new SourceFile(2, "This Source-File increases the player's crime success rate, crime money, and charisma " +
"multipliers by:<br><br>" +
"Level 1: 24%<br>" +
"Level 2: 36%<br>" +
"Level 3: 42%");
SourceFiles["SourceFile3"] = new SourceFile(3,"This Source-File lets you create corporations on other BitNodes (although " +
"some BitNodes will disable this mechanic). This Source-File also increases your charisma and company salary multipliers by:<br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
SourceFiles["SourceFile4"] = new SourceFile(4, "This Source-File lets you access and use the Singularity Functions in every BitNode. Every " +
"level of this Source-File opens up more of the Singularity Functions you can use.");
SourceFiles["SourceFile5"] = new SourceFile(5, "This Source-File grants a special new stat called Intelligence. Intelligence " +
"is unique because it is permanent and persistent (it never gets reset back to 1). However, " +
"gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't " +
"know when you gain experience and how much). Higher Intelligence levels will boost your production " +
"for many actions in the game. In addition, this Source-File will unlock the getBitNodeMultipliers() " +
"Netscript function, and will raise all of your hacking-related multipliers by:<br><br> " +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
SourceFiles["SourceFile6"] = new SourceFile(6, "This Source-File allows you to access the NSA's Bladeburner Division in other " +
"BitNodes. In addition, this Source-File will raise both the level and experience gain rate of all your combat stats by:<br><br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
SourceFiles["SourceFile7"] = new SourceFile(7, "This Source-File allows you to access the Bladeburner Netscript API in other " +
"BitNodes. In addition, this Source-File will increase all of your Bladeburner multipliers by:<br><br>" +
"Level 1: 8%<br>" +
"Level 2: 12%<br>" +
"Level 3: 14%");
SourceFiles["SourceFile8"] = new SourceFile(8, "This Source-File grants the following benefits:<br><br>" +
"Level 1: Permanent access to WSE and TIX API<br>" +
"Level 2: Ability to short stocks in other BitNodes<br>" +
"Level 3: Ability to use limit/stop orders in other BitNodes<br><br>" +
"This Source-File also increases your hacking growth multipliers by: " +
"<br>Level 1: 12%<br>Level 2: 18%<br>Level 3: 21%");
SourceFiles["SourceFile9"] = new SourceFile(9);
SourceFiles["SourceFile10"] = new SourceFile(10);
SourceFiles["SourceFile11"] = new SourceFile(11, "This Source-File makes it so that company favor increases BOTH the player's salary and reputation gain rate " +
"at that company by 1% per favor (rather than just the reputation gain). This Source-File also " +
" increases the player's company salary and reputation gain multipliers by:<br><br>" +
"Level 1: 24%<br>" +
"Level 2: 36%<br>" +
"Level 3: 42%<br>");
SourceFiles["SourceFile12"] = new SourceFile(12, "This Source-File increases all your multipliers by 1% per level. This effect is multiplicative with itself. " +
"In other words, level N of this Source-File will result in a multiplier of 1.01^N (or 0.99^N for multipliers that decrease)");
}
function PlayerOwnedSourceFile(number, level) {
this.n = number;
this.lvl = level;
}
//Takes in a PlayerOwnedSourceFile as the "srcFile" argument
function applySourceFile(srcFile) {
var srcFileKey = "SourceFile" + srcFile.n;
var sourceFileObject = SourceFiles[srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + srcFile.n);
return;
}
switch(srcFile.n) {
case 1: // The Source Genesis
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (16 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
var decMult = 1 - (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_chance_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_speed_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_grow_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].company_rep_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].faction_rep_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_success_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= decMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_ram_cost_mult *= decMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_core_cost_mult *= decMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_level_cost_mult *= decMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].work_money_mult *= incMult;
break;
case 2: //Rise of the Underworld
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (24 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_success_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_mult *= incMult;
break;
case 3: //Corporatocracy
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].work_money_mult *= incMult;
break;
case 4: //The Singularity
//No effects, just gives access to Singularity functions
break;
case 5: //Artificial Intelligence
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_chance_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_speed_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_grow_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_exp_mult *= incMult;
break;
case 6: //Bladeburner
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_exp_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_mult *= incMult;
break;
case 7: //Bladeburner 2079
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bladeburner_max_stamina_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bladeburner_stamina_gain_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bladeburner_analysis_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].bladeburner_success_chance_mult *= incMult;
break;
case 8: //Ghost of Wall Street
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (12 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_grow_mult *= incMult;
break;
case 11: //The Big Crash
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (24 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].work_money_mult *= incMult;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].company_rep_mult *= incMult;
break;
case 12: //The Recursion
var inc = Math.pow(1.01, srcFile.lvl);
var dec = Math.pow(0.99, srcFile.lvl);
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_chance_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_speed_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_money_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_grow_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma_exp_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].company_rep_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].faction_rep_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_money_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].crime_success_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_money_mult *= inc;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= dec;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_ram_cost_mult *= dec;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_core_cost_mult *= dec;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacknet_node_level_cost_mult *= dec;
_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].work_money_mult *= inc;
break;
default:
console.log("ERROR: Invalid source file number: " + srcFile.n);
break;
}
sourceFileObject.owned = true;
}
/***/ }),
/* 67 */
/*!******************************************!*\
!*** ./utils/uiHelpers/removeElement.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* For a given element, this function removes it AND its children
* @param elem The element to remove.
*/
function removeElement(elem) {
if (elem === null) {
// tslint:disable-next-line:no-console
console.debug("The element passed into 'removeElement' was null.");
return;
}
if (!(elem instanceof Element)) {
// tslint:disable-next-line:no-console
console.debug("The element passed into 'removeElement' was not an instance of an Element.");
return;
}
while (elem.firstChild !== null) {
elem.removeChild(elem.firstChild);
}
if (elem.parentNode !== null) {
elem.parentNode.removeChild(elem);
}
}
exports.removeElement = removeElement;
/***/ }),
/* 68 */
/*!******************************!*\
!*** ./src/NetscriptPort.js ***!
\******************************/
/*! exports provided: NetscriptPort */
/*! exports used: NetscriptPort */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPort; });
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_0__);
function NetscriptPort() {
this.data = [];
}
NetscriptPort.prototype.write = function(data) {
this.data.push(data);
if (this.data.length > _Settings__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) {
return this.data.shift();
}
return null;
}
NetscriptPort.prototype.tryWrite = function(data) {
if (this.data.length >= _Settings__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) {
return false;
}
this.data.push(data);
return true;
}
NetscriptPort.prototype.read = function() {
if (this.data.length === 0) {
return "NULL PORT DATA";
}
return this.data.shift();
}
NetscriptPort.prototype.peek = function() {
if (this.data.length === 0) {
return "NULL PORT DATA";
} else {
var foo = this.data.slice();
return foo[0];
}
}
NetscriptPort.prototype.full = function() {
return this.data.length == _Settings__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity;
}
NetscriptPort.prototype.empty = function() {
return this.data.length === 0;
}
NetscriptPort.prototype.clear = function() {
this.data.length = 0;
}
/***/ }),
/* 69 */
/*!*****************************!*\
!*** ./src/SettingEnums.ts ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Enum Of 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 = {}));
/**
* Enum Of 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 = {}));
/***/ }),
/* 70 */,
/* 71 */
/*!********************************!*\
!*** ./src/Company/Company.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 */ 13);
const CompanyPosition_1 = __webpack_require__(/*! ./CompanyPosition */ 81);
const Constants_1 = __webpack_require__(/*! ../Constants */ 1);
const DefaultConstructorParams = {
name: "",
info: "",
companyPositions: {},
expMultiplier: 1,
salaryMultiplier: 1,
jobStatReqOffset: 0,
};
class Company {
/**
* Initiatizes a Company from a JSON save state.
*/
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Company, value.data);
}
constructor(p = DefaultConstructorParams) {
this.name = p.name;
this.info = p.info;
this.companyPositions = p.companyPositions;
this.expMultiplier = p.expMultiplier;
this.salaryMultiplier = p.salaryMultiplier;
this.jobStatReqOffset = p.jobStatReqOffset;
this.isPlayerEmployed = false;
this.playerReputation = 1;
this.favor = 0;
this.rolloverRep = 0;
}
hasPosition(pos) {
if (pos instanceof CompanyPosition_1.CompanyPosition) {
return (this.companyPositions[pos.name] != null);
}
else {
return (this.companyPositions[pos] != null);
}
}
gainFavor() {
if (this.favor == null) {
this.favor = 0;
}
if (this.rolloverRep == null) {
this.rolloverRep = 0;
}
var res = this.getFavorGain();
if (res.length != 2) {
console.error("Invalid result from getFavorGain() function");
return;
}
this.favor += res[0];
this.rolloverRep = res[1];
}
getFavorGain() {
if (this.favor == null) {
this.favor = 0;
}
if (this.rolloverRep == null) {
this.rolloverRep = 0;
}
let favorGain = 0, rep = this.playerReputation + this.rolloverRep;
let reqdRep = Constants_1.CONSTANTS.CompanyReputationToFavorBase *
Math.pow(Constants_1.CONSTANTS.CompanyReputationToFavorMult, 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("Company", this);
}
}
exports.Company = Company;
JSONReviver_1.Reviver.constructors.Company = Company;
/***/ }),
/* 72 */
/*!***************************!*\
!*** ./src/SaveObject.js ***!
\***************************/
/*! exports provided: saveObject, loadGame */
/*! exports used: loadGame, saveObject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return saveObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return loadGame; });
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias */ 43);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Company/CompanyPosition */ 81);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Constants */ 1);
/* 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 */ 8);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Fconf */ 45);
/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Gang */ 48);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./HacknetNode */ 63);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Message */ 38);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Script */ 28);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./StockMarket */ 22);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/GameOptions */ 80);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/JSONReviver */ 13);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./ui/createStatusText */ 95);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! decimal.js */ 31);
/* SaveObject.js
* Defines the object used to save/load games
*/
let saveObject = new BitburnerSaveObject();
function BitburnerSaveObject() {
this.PlayerSave = "";
this.AllServersSave = "";
this.CompaniesSave = "";
this.FactionsSave = "";
this.SpecialServerIpsSave = "";
this.AliasesSave = "";
this.GlobalAliasesSave = "";
this.MessagesSave = "";
this.StockMarketSave = "";
this.SettingsSave = "";
this.FconfSettingsSave = "";
this.VersionSave = "";
this.AllGangsSave = "";
}
BitburnerSaveObject.prototype.saveGame = function(db) {
this.PlayerSave = JSON.stringify(_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"]);
//Delete all logs from all running scripts
var TempAllServers = JSON.parse(JSON.stringify(_Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"]), _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
for (var ip in TempAllServers) {
var server = TempAllServers[ip];
if (server == null) {continue;}
for (var i = 0; i < server.runningScripts.length; ++i) {
var runningScriptObj = server.runningScripts[i];
runningScriptObj.logs.length = 0;
runningScriptObj.logs = [];
}
}
this.AllServersSave = JSON.stringify(TempAllServers);
this.CompaniesSave = JSON.stringify(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["Companies"]);
this.FactionsSave = JSON.stringify(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]);
this.SpecialServerIpsSave = JSON.stringify(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"]);
this.AliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* Aliases */ "a"]);
this.GlobalAliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* GlobalAliases */ "b"]);
this.MessagesSave = JSON.stringify(_Message__WEBPACK_IMPORTED_MODULE_10__[/* Messages */ "b"]);
this.StockMarketSave = JSON.stringify(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* StockMarket */ "c"]);
this.SettingsSave = JSON.stringify(_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"]);
this.FconfSettingsSave = JSON.stringify(_Fconf__WEBPACK_IMPORTED_MODULE_7__[/* FconfSettings */ "a"]);
this.VersionSave = JSON.stringify(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].Version);
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].inGang()) {
this.AllGangsSave = JSON.stringify(_Gang__WEBPACK_IMPORTED_MODULE_8__[/* AllGangs */ "a"]);
}
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
//We'll save to both localstorage and indexedDb
var objectStore = db.transaction(["savestring"], "readwrite").objectStore("savestring");
var request = objectStore.put(saveString, "save");
request.onerror = function(e) {
console.log("Error saving game to IndexedDB: " + e);
}
request.onsuccess = function(e) {
//console.log("Saved game to IndexedDB!");
}
try {
window.localStorage.setItem("bitburnerSave", saveString);
//console.log("Saved game to LocalStorage!");
} catch(e) {
if (e.code == 22) {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_23__["createStatusText"])("Save failed for localStorage! Check console(F12)");
console.log("Failed to save game to localStorage because the size of the save file " +
"is too large. However, the game will still be saved to IndexedDb if your browser " +
"supports it. If you would like to save to localStorage as well, then " +
"consider killing several of your scripts to " +
"fix this, or increasing the size of your browsers localStorage");
}
}
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_23__["createStatusText"])("Game saved!");
}
// Makes necessary changes to the loaded/imported data to ensure
// the game stills works with new versions
function evaluateVersionCompatibility(ver) {
// This version refactored the Company/job-related code
if (ver <= "0.41.2") {
// Player's company position is now a string
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition != null && typeof _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition !== "string") {
console.log("Changed Player.companyPosition value to be compatible with v0.41.2");
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition = _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition.data.positionName;
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition == null) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].companyPosition = "";
}
}
// The "companyName" property of all Companies is renamed to "name"
for (var companyName in _Company_Companies__WEBPACK_IMPORTED_MODULE_1__["Companies"]) {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_1__["Companies"][companyName];
if ((company.name == null || company.name === 0 || company.name === "") && company.companyName != null) {
console.log("Changed company name property to be compatible with v0.41.2");
company.name = company.companyName;
}
if (company.companyPositions instanceof Array) {
console.log("Changed company companyPositions property to be compatible with v0.41.2");
const pos = {};
for (let i = 0; i < company.companyPositions.length; ++i) {
pos[company.companyPositions[i]] = true;
}
company.companyPositions = pos;
}
}
}
}
function loadGame(saveString) {
if (saveString === "" || saveString == null || saveString === undefined) {
if (!window.localStorage.getItem("bitburnerSave")) {
console.log("No save file to load");
return false;
}
saveString = decodeURIComponent(escape(atob(window.localStorage.getItem("bitburnerSave"))));
console.log("Loading game from localStorage");
} else {
saveString = decodeURIComponent(escape(atob(saveString)));
console.log("Loading game from IndexedDB");
}
var saveObj = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
Object(_Player__WEBPACK_IMPORTED_MODULE_11__[/* loadPlayer */ "b"])(saveObj.PlayerSave);
Object(_Server__WEBPACK_IMPORTED_MODULE_13__[/* loadAllServers */ "g"])(saveObj.AllServersSave);
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["loadCompanies"])(saveObj.CompaniesSave);
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["loadFactions"])(saveObj.FactionsSave);
Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* loadSpecialServerIps */ "d"])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])(saveObj.AliasesSave);
} catch(e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])(saveObj.GlobalAliasesSave);
} catch(e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* loadMessages */ "e"])(saveObj.MessagesSave);
} catch(e) {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
} else {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])(saveObj.StockMarketSave);
} catch(e) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])("");
}
} else {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].load(saveObj.SettingsSave);
} catch(e) {
console.log("ERROR: Failed to parse Settings. Re-initing default values");
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].init();
}
} else {
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].init();
}
if (saveObj.hasOwnProperty("FconfSettingsSave")) {
try {
Object(_Fconf__WEBPACK_IMPORTED_MODULE_7__[/* loadFconf */ "c"])(saveObj.FconfSettingsSave);
} catch(e) {
console.log("ERROR: Failed to parse .fconf Settings.");
}
}
if (saveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(saveObj.VersionSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
evaluateVersionCompatibility(ver);
if (window.location.href.toLowerCase().includes("bitburner-beta")) {
//Beta branch, always show changes
createBetaUpdateText();
} else if (ver != _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].Version) {
createNewUpdateText();
}
} catch(e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang__WEBPACK_IMPORTED_MODULE_8__[/* loadAllGangs */ "c"])(saveObj.AllGangsSave);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
return true;
}
function loadImportedGame(saveObj, saveString) {
var tempSaveObj = null;
var tempPlayer = null;
var tempAllServers = null;
var tempCompanies = null;
var tempFactions = null;
var tempSpecialServerIps = null;
var tempAliases = null;
var tempGlobalAliases = null;
var tempMessages = null;
var tempStockMarket = null;
var tempAllGangs = null;
//Check to see if the imported save file can be parsed. If any
//errors are caught it will fail
try {
var decodedSaveString = decodeURIComponent(escape(atob(saveString)));
tempSaveObj = new BitburnerSaveObject();
tempSaveObj = JSON.parse(decodedSaveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
tempPlayer = JSON.parse(tempSaveObj.PlayerSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
//Parse Decimal.js objects
tempPlayer.money = new decimal_js__WEBPACK_IMPORTED_MODULE_26__[/* default */ "a"](tempPlayer.money);
tempPlayer.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_26__[/* default */ "a"](tempPlayer.total_money);
tempPlayer.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_26__[/* default */ "a"](tempPlayer.lifetime_money);
tempAllServers = JSON.parse(tempSaveObj.AllServersSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
tempCompanies = JSON.parse(tempSaveObj.CompaniesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
tempFactions = JSON.parse(tempSaveObj.FactionsSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
tempSpecialServerIps = JSON.parse(tempSaveObj.SpecialServerIpsSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
if (tempSaveObj.hasOwnProperty("AliasesSave")) {
try {
tempAliases = JSON.parse(tempSaveObj.AliasesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch(e) {
console.log("Parsing Aliases save failed: " + e);
tempAliases = {};
}
} else {
tempAliases = {};
}
if (tempSaveObj.hasOwnProperty("GlobalAliases")) {
try {
tempGlobalAliases = JSON.parse(tempSaveObj.AliasesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch(e) {
console.log("Parsing Global Aliases save failed: " + e);
tempGlobalAliases = {};
}
} else {
tempGlobalAliases = {};
}
if (tempSaveObj.hasOwnProperty("MessagesSave")) {
try {
tempMessages = JSON.parse(tempSaveObj.MessagesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch(e) {
console.log("Parsing Messages save failed: " + e);
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
} else {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
tempStockMarket = JSON.parse(tempSaveObj.StockMarketSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch(e) {
console.log("Parsing StockMarket save failed: " + e);
tempStockMarket = {};
}
} else {
tempStockMarket = {};
}
if (tempSaveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(tempSaveObj.VersionSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
evaluateVersionCompatibility(ver);
} catch(e) {
console.error("Parsing Version save failed: " + e);
}
} else {
}
if (tempPlayer.bitNodeN == 2 && tempPlayer.inGang() && tempSaveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang__WEBPACK_IMPORTED_MODULE_8__[/* loadAllGangs */ "c"])(tempSaveObj.AllGangsSave);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("Error importing game: " + e.toString());
return false;
}
//Since the save file is valid, load everything for real
saveString = decodeURIComponent(escape(atob(saveString)));
saveObj = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
Object(_Player__WEBPACK_IMPORTED_MODULE_11__[/* loadPlayer */ "b"])(saveObj.PlayerSave);
Object(_Server__WEBPACK_IMPORTED_MODULE_13__[/* loadAllServers */ "g"])(saveObj.AllServersSave);
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["loadCompanies"])(saveObj.CompaniesSave);
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["loadFactions"])(saveObj.FactionsSave);
Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* loadSpecialServerIps */ "d"])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])(saveObj.AliasesSave);
} catch(e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadAliases */ "c"])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])(saveObj.GlobalAliasesSave);
} catch(e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* loadGlobalAliases */ "d"])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* loadMessages */ "e"])(saveObj.MessagesSave);
} catch(e) {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
} else {
Object(_Message__WEBPACK_IMPORTED_MODULE_10__[/* initMessages */ "d"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])(saveObj.StockMarketSave);
} catch(e) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])("");
}
} else {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* loadStockMarket */ "k"])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].load(saveObj.SettingsSave);
} catch(e) {
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].init();
}
} else {
_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].init();
}
if (saveObj.hasOwnProperty("FconfSettingsSave")) {
try {
Object(_Fconf__WEBPACK_IMPORTED_MODULE_7__[/* loadFconf */ "c"])(saveObj.FconfSettingsSave);
} catch(e) {
console.log("ERROR: Failed to load .fconf settings when importing");
}
}
if (saveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(saveObj.VersionSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
evaluateVersionCompatibility(ver);
if (ver != _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].Version) {
createNewUpdateText();
}
} catch(e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang__WEBPACK_IMPORTED_MODULE_8__[/* loadAllGangs */ "c"])(saveObj.AllGangsSave);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
var popupId = "import-game-restart-game-notice";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_21__["createElement"])("p", {
innerText:"Imported game! You need to SAVE the game and then RELOAD the page " +
"to make sure everything runs smoothly"
});
var gotitBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_21__["createElement"])("a", {
class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25__["removeElementById"])(popupId);
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_22__["createPopup"])(popupId, [txt, gotitBtn]);
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_18__[/* gameOptionsBoxClose */ "a"])();
//Re-start game
console.log("Importing game");
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].setDisplayElements(); //Sets variables for important DOM elements
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].init(); //Initialize buttons, work, etc.
//Calculate the number of cycles have elapsed while offline
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._lastUpdate = new Date().getTime();
var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].lastUpdate;
var numCyclesOffline = Math.floor((_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._lastUpdate - lastUpdate) / _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._idleSpeed);
/* Process offline progress */
var offlineProductionFromScripts = Object(_Script__WEBPACK_IMPORTED_MODULE_12__[/* loadAllRunningScripts */ "f"])(); //This also takes care of offline production for those scripts
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].isWorking) {
console.log("work() called in load() for " + numCyclesOffline * _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._idleSpeed + " milliseconds");
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workForFaction(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].createProgramWork(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].takeClass(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].commitCrime(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].workPartTime(numCyclesOffline);
} else {
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].work(numCyclesOffline);
}
}
//Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_9__[/* processAllHacknetNodeEarnings */ "d"])(numCyclesOffline);
//Passive faction rep gain offline
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_6__[/* processPassiveFactionRepGain */ "d"])(numCyclesOffline);
//Update total playtime
var time = numCyclesOffline * _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].totalPlaytime = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastAug = 0;}
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastBitnode = 0;}
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].playtimeSinceLastBitnode += time;
//Re-apply augmentations
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].reapplyAllAugmentations();
//Clear terminal
$("#terminal tr:not(:last)").remove();
_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].lastUpdate = _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._lastUpdate;
_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].start(); //Run main game loop and Scripts loop
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("While you were offline, your scripts generated <span class='money-gold'>$" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_24__[/* numeralWrapper */ "a"].format(offlineProductionFromScripts, '0,0.00') + "</span> and your Hacknet Nodes generated <span class='money-gold'>$" +
_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_24__[/* numeralWrapper */ "a"].format(offlineProductionFromHacknetNodes, '0,0.00') + "</span>");
return true;
}
BitburnerSaveObject.prototype.exportGame = function() {
this.PlayerSave = JSON.stringify(_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"]);
this.AllServersSave = JSON.stringify(_Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"]);
this.CompaniesSave = JSON.stringify(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["Companies"]);
this.FactionsSave = JSON.stringify(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]);
this.SpecialServerIpsSave = JSON.stringify(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"]);
this.AliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* Aliases */ "a"]);
this.GlobalAliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__[/* GlobalAliases */ "b"]);
this.MessagesSave = JSON.stringify(_Message__WEBPACK_IMPORTED_MODULE_10__[/* Messages */ "b"]);
this.StockMarketSave = JSON.stringify(_StockMarket__WEBPACK_IMPORTED_MODULE_16__[/* StockMarket */ "c"]);
this.SettingsSave = JSON.stringify(_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"]);
this.VersionSave = JSON.stringify(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].Version);
if (_Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_11__[/* Player */ "a"].inGang()) {
this.AllGangsSave = JSON.stringify(_Gang__WEBPACK_IMPORTED_MODULE_8__[/* AllGangs */ "a"]);
}
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
var filename = "bitburnerSave.json";
var file = new Blob([saveString], {type: 'text/plain'});
if (window.navigator.msSaveOrOpenBlob) {// IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
} else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = "bitburnerSave.json";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
BitburnerSaveObject.prototype.importGame = function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fileSelector = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("import-game-file-selector");
fileSelector.addEventListener("change", openImportFileHandler, false);
$("#import-game-file-selector").click();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("ERR: Your browser does not support HTML5 File API. Cannot import.");
}
}
BitburnerSaveObject.prototype.deleteGame = function(db) {
//Delete from local storage
if (window.localStorage.getItem("bitburnerSave")) {
window.localStorage.removeItem("bitburnerSave");
}
//Delete from indexedDB
var request = db.transaction(["savestring"], "readwrite").objectStore("savestring").delete("save");
request.onsuccess = function(e) {
console.log("Successfully deleted save from indexedDb");
}
request.onerror = function(e) {
console.log("Failed to delete save from indexedDb: " + e);
}
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_23__["createStatusText"])("Game deleted!");
}
function createNewUpdateText() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("New update!<br>" +
"Please report any bugs/issues through the github repository " +
"or the Bitburner subreddit (reddit.com/r/bitburner).<br><br>" +
_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].LatestUpdate);
}
function createBetaUpdateText() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("You are playing on the beta environment! This branch of the game " +
"features the latest developments in the game. This version may be unstable.<br>" +
"Please report any bugs/issues through the github repository (https://github.com/danielyxie/bitburner/issues) " +
"or the Bitburner subreddit (reddit.com/r/bitburner).<br><br>" +
_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].LatestUpdate);
}
BitburnerSaveObject.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Generic_toJSON"])("BitburnerSaveObject", this);
}
BitburnerSaveObject.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Generic_fromJSON"])(BitburnerSaveObject, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"].constructors.BitburnerSaveObject = BitburnerSaveObject;
//Import game
function openImportFileHandler(evt) {
var file = evt.target.files[0];
if (!file) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_17__["dialogBoxCreate"])("Invalid file selected");
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
loadImportedGame(saveObject, contents);
};
reader.readAsText(file);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 73 */
/*!***************************************************!*\
!*** ./utils/uiHelpers/createAccordionElement.ts ***!
\***************************************************/
/*! no static exports found */
/*! exports used: createAccordionElement */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const createElement_1 = __webpack_require__(/*! ./createElement */ 2);
/**
* Creates both the header and panel element of an accordion and sets the click handler
* @param params The creation parameters.
*/
function createAccordionElement(params) {
const liElem = createElement_1.createElement("li");
const header = createElement_1.createElement("button", {
class: "accordion-header",
clickListener() {
this.classList.toggle("active");
const pnl = this.nextElementSibling.style;
pnl.display = pnl.display === "block" ? "none" : "block";
},
id: params.id !== undefined ? `${params.id}-hdr` : undefined,
innerHTML: params.hdrText,
});
const panel = createElement_1.createElement("div", {
class: "accordion-panel",
id: params.id !== undefined ? `${params.id}-panel` : undefined,
innerHTML: params.panelText,
});
liElem.appendChild(header);
liElem.appendChild(panel);
return [
liElem,
header,
panel,
];
}
exports.createAccordionElement = createAccordionElement;
/***/ }),
/* 74 */
/*!**************************************!*\
!*** ./utils/helpers/clearObject.ts ***!
\**************************************/
/*! no static exports found */
/*! exports used: clearObject */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Clears defined properties from an object.
* Does not delete up the prototype chain.
* @deprecated Look into using `Map` or `Set` rather than manipulating properties on an Object.
* @param obj the object to clear all properties
*/
function clearObject(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
// tslint:disable-next-line:no-dynamic-delete
delete obj[key];
}
}
}
exports.clearObject = clearObject;
/***/ }),
/* 75 */
/*!*************************!*\
!*** ./utils/LogBox.js ***!
\*************************/
/*! exports provided: logBoxCreate, logBoxUpdateText, logBoxOpened, logBoxCurrentScript */
/*! exports used: logBoxCreate, logBoxOpened, logBoxUpdateText */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return logBoxUpdateText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logBoxOpened; });
/* unused harmony export logBoxCurrentScript */
/* harmony import */ var _src_NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/NetscriptWorker */ 24);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _helpers_arrayToString__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers/arrayToString */ 52);
/* harmony import */ var _helpers_arrayToString__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_2__);
$(document).keydown(function(event) {
if (logBoxOpened && event.keyCode == 27) {
logBoxClose();
}
});
function logBoxInit() {
var closeButton = document.getElementById("log-box-close");
logBoxClose();
//Close Dialog box
closeButton.addEventListener("click", function() {
logBoxClose();
return false;
});
document.getElementById("log-box-text-header").style.display = "inline-block";
};
document.addEventListener("DOMContentLoaded", logBoxInit, false);
function logBoxClose() {
logBoxOpened = false;
var logBox = document.getElementById("log-box-container");
logBox.style.display = "none";
}
function logBoxOpen() {
logBoxOpened = true;
var logBox = document.getElementById("log-box-container");
logBox.style.display = "block";
}
var logBoxOpened = false;
var logBoxCurrentScript = null;
function logBoxCreate(script) {
logBoxCurrentScript = script;
var killScriptBtn = Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_1__["clearEventListeners"])("log-box-kill-script");
killScriptBtn.addEventListener("click", ()=>{
Object(_src_NetscriptWorker__WEBPACK_IMPORTED_MODULE_0__[/* killWorkerScript */ "d"])(script, script.server);
return false;
});
document.getElementById('log-box-kill-script').style.display = "inline-block";
logBoxOpen();
document.getElementById("log-box-text-header").innerHTML =
logBoxCurrentScript.filename + " " + Object(_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_2__["arrayToString"])(logBoxCurrentScript.args) + ":<br><br>";
logBoxCurrentScript.logUpd = true;
logBoxUpdateText();
}
function logBoxUpdateText() {
var txt = document.getElementById("log-box-text");
if (logBoxCurrentScript && logBoxOpened && txt && logBoxCurrentScript.logUpd) {
txt.innerHTML = "";
for (var i = 0; i < logBoxCurrentScript.logs.length; ++i) {
txt.innerHTML += logBoxCurrentScript.logs[i];
txt.innerHTML += "<br>";
}
logBoxCurrentScript.logUpd = false;
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 76 */
/*!************************!*\
!*** ./src/DarkWeb.js ***!
\************************/
/*! exports provided: checkIfConnectedToDarkweb, executeDarkwebTerminalCommand, DarkWebItems */
/*! exports used: DarkWebItems, checkIfConnectedToDarkweb, executeDarkwebTerminalCommand */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkIfConnectedToDarkweb; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return executeDarkwebTerminalCommand; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DarkWebItems; });
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ui/postToTerminal */ 7);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 84);
/* 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_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__);
/* DarkWeb.js */
//Posts a "help" message if connected to DarkWeb
function checkIfConnectedToDarkweb() {
if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_2__[/* SpecialServerIps */ "a"].hasOwnProperty("Darkweb Server")) {
var darkwebIp = _SpecialServerIps__WEBPACK_IMPORTED_MODULE_2__[/* SpecialServerIps */ "a"]["Darkweb Server"];
if (!Object(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_4__["isValidIPAddress"])(darkwebIp)) {return;}
if (darkwebIp == _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].getCurrentServer().ip) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("You are now connected to the dark web. From the dark web you can purchase illegal items. " +
"Use the 'buy -l' command to display a list of all the items you can buy. Use 'buy [item-name] " +
"to purchase an item");
}
}
}
//Handler for dark web commands. The terminal's executeCommand() function will pass
//dark web-specific commands into this. It will pass in the raw split command array
//rather than the command string
function executeDarkwebTerminalCommand(commandArray) {
if (commandArray.length == 0) {return;}
switch (commandArray[0]) {
case "buy":
if (commandArray.length != 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("Incorrect number of arguments. Usage: ");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("buy -l");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("buy [item name]");
return;
}
var arg = commandArray[1];
if (arg == "-l") {
listAllDarkwebItems();
} else {
buyDarkwebItem(arg);
}
break;
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("Command not found");
break;
}
}
function listAllDarkwebItems() {
for(const key in DarkWebItems) {
const item = DarkWebItems[key];
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])(item.toString());
}
}
function buyDarkwebItem(itemName) {
itemName = itemName.toLowerCase();
// find the program that matches, if any
let item = null;
for(const key in DarkWebItems) {
const i = DarkWebItems[key];
if(i.program.toLowerCase() == itemName) {
item = i;
}
}
// return if invalid
if(item === null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("Unrecognized item: "+itemName);
return;
}
// return if the player already has it.
if(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hasProgram(item.program)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])('You already have the '+item.program+' program');
return;
}
// return if the player doesn't have enough money
if(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].money.lt(item.price)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + item.program);
return;
}
// buy and push
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].loseMoney(item.price);
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].getHomeComputer().programs.push(item.program);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_3__["post"])('You have purchased the '+item.program+' program. The new program can be found on your home computer.');
}
function DarkWebItem(program, price, description) {
this.program = program;
this.price = price;
this.description = description;
}
// formats the item for the terminal (eg. "BruteSSH.exe - $500,000 - Opens up SSH Ports")
DarkWebItem.prototype.toString = function() {
return [this.program, "$"+Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.price), this.description].join(' - ');
}
const DarkWebItems = {
BruteSSHProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].BruteSSHProgram.name, 500000, "Opens up SSH Ports"),
FTPCrackProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].FTPCrackProgram.name, 1500000, "Opens up FTP Ports"),
RelaySMTPProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].RelaySMTPProgram.name, 5000000, "Opens up SMTP Ports"),
HTTPWormProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].HTTPWormProgram.name, 30000000, "Opens up HTTP Ports"),
SQLInjectProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].SQLInjectProgram.name, 250000000, "Opens up SQL Ports"),
DeepscanV1: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].DeepscanV1.name, 500000, "Enables 'scan-analyze' with a depth up to 5"),
DeepscanV2: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].DeepscanV2.name, 25000000, "Enables 'scan-analyze' with a depth up to 10"),
AutolinkProgram: new DarkWebItem(_CreateProgram__WEBPACK_IMPORTED_MODULE_0__[/* Programs */ "a"].AutoLink.name, 1000000, "Enables direct connect via 'scan-analyze'"),
};
/***/ }),
/* 77 */
/*!*************************************!*\
!*** ./utils/helpers/roundToTwo.ts ***!
\*************************************/
/*! no static exports found */
/*! exports used: roundToTwo */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Rounds a number to two decimal places.
* @param decimal A decimal value to trim to two places.
*/
function roundToTwo(decimal) {
const leftShift = Math.round(parseFloat(`${decimal}e+2`));
return +(`${leftShift}e-2`);
}
exports.roundToTwo = roundToTwo;
/***/ }),
/* 78 */
/*!***************************!*\
!*** ./src/Literature.js ***!
\***************************/
/*! exports provided: Literatures, initLiterature, showLiterature */
/*! exports used: initLiterature, showLiterature */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export Literatures */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return initLiterature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return showLiterature; });
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* Literature.js
* Lore / world building literature that can be found on servers
*/
function Literature(title, filename, txt) {
this.title = title;
this.fn = filename;
this.txt = txt;
}
function showLiterature(fn) {
var litObj = Literatures[fn];
if (litObj == null) {return;}
var txt = "<i>" + litObj.title + "</i><br><br>" +
litObj.txt;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])(txt);
}
let Literatures = {}
function initLiterature() {
var title, fn, txt;
title = "The Beginner's Guide to Hacking";
fn = "hackers-starting-handbook.lit";
txt = "Some resources:<br><br>" +
"<a class='a-link-button' href='https://bitburner.readthedocs.io/en/latest/netscriptlearntoprogram.html' target='_blank' style='margin:4px'>Learn to Program</a><br><br>" +
"<a class='a-link-button' href='https://bitburner.readthedocs.io/en/latest/netscriptjs.html' target='_blank' style='margin:4px'>For Experienced JavaScript Developers: NetscriptJS</a><br><br>" +
"<a class='a-link-button' href='https://bitburner.readthedocs.io/en/latest/netscript.html' target='_blank' style='margin:4px'>Netscript Documentation</a><br><br>" +
"When starting out, hacking is the most profitable way to earn money and progress. This " +
"is a brief collection of tips/pointers on how to make the most out of your hacking scripts.<br><br>" +
"-hack() and grow() both work by percentages. hack() steals a certain percentage of the " +
"money on a server, and grow() increases the amount of money on a server by some percentage (multiplicatively)<br><br>" +
"-Because hack() and grow() work by percentages, they are more effective if the target server has a high amount of money. " +
"Therefore, you should try to increase the amount of money on a server (using grow()) to a certain amount before hacking it. Two " +
"import Netscript functions for this are getServerMoneyAvailable() and getServerMaxMoney()<br><br>" +
"-Keep security level low. Security level affects everything when hacking. Two important Netscript functions " +
"for this are getServerSecurityLevel() and getServerMinSecurityLevel()<br><br>" +
"-Purchase additional servers by visiting 'Alpha Enterprises' in the city. They are relatively cheap " +
"and give you valuable RAM to run more scripts early in the game<br><br>" +
"-Prioritize upgrading the RAM on your home computer. This can also be done at 'Alpha Enterprises'<br><br>" +
"-Many low level servers have free RAM. You can use this RAM to run your scripts. Use the scp Terminal or " +
"Netscript command to copy your scripts onto these servers and then run them.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Complete Handbook for Creating a Successful Corporation";
fn = "corporation-management-handbook.lit";
txt = "<u>Getting Started with Corporations</u><br>" +
"To get started, visit the City Hall in Sector-12 in order to create a Corporation. This requires " +
"$150b of your own money, but this $150b will get put into your Corporation's funds. " +
"After creating your Corporation, you will see it listed as one of the locations in the city. Click on " +
"your Corporation in order to manage it.<br><br>" +
"Your Corporation can have many different divisions, each in a different Industry. There are many different " +
"types of Industries, each with different properties. To create your first division, click the " +
"'Expand into new Industry' button at the top of the management UI. The Agriculture " +
"and Software industries are recommended for your first division.<br><br>" +
"The first thing you'll need to do is hire some employees. Employees can be assigned to five different positions. " +
"Each position has a different effect on various aspects of your Corporation. It is recommended to have at least " +
"one employee at each position.<br><br>" +
"Each industry uses some combination of Materials in order to produce other Materials and/or create Products. " +
"Specific information about this is displayed in each of your divisions' UI.<br><br>" +
"Products are special, industry-specific objects. They are different than Materials because you " +
"must manually choose to develop them, and you can choose to develop any number of Products. Developing " +
"a Product takes time, but a Product typically generates significantly more revenue than any Material. " +
"Not all industries allow you to create Products. To create a Product, look for a button " +
"in the top-left panel of the division UI (e.g. For the Software Industry, the button says 'Develop Software').<br><br>" +
"To get your supply chain system started, " +
"purchase the Materials that your industry needs to produce other Materials/Products. This can be done " +
"by clicking the 'Buy' button next to the corresponding Material(s). After you have the required Materials, " +
"you will immediately start production. The amount of Materials/Products you produce is based on a variety of factors, " +
"one of which is your employees and their productivity.<br><br>" +
"Once you start producing Materials/Products, you can sell them in order to start earning revenue. This can be done " +
"by clicking the 'Sell' button next to the corresponding Material or Product. The amount of Material/Product you sell is dependent " +
"on a wide variety of different factors.<br><br>" +
"These are the basics of getting your Corporation up and running! Now, you can start purchasing upgrades to improve " +
"your bottom line. If you need money, consider looking for seed investors, who will give you money in exchange for stock shares. " +
"Otherwise, once you feel you are ready, take your Corporation public! Once your Corporation goes public, you can no longer " +
"find investors. Instead, your Corporation will be publicly traded and its stock price will change based on how well " +
"it's performing financially. You can then sell your stock shares in order to make money.<br><br>" +
"<u>Tips/Pointers</u><br>" +
"-Purchasing Hardware, Robots, AI Cores, and Real Estate can potentially increase your production. " +
"The effects of these depend on what industry you are in.<br><br>" +
"-In order to optimize your production, you will need a good balance of Operators, Managers, and Engineers<br><br>" +
"-Different employees excel in different jobs. For example, the highly intelligent employees will probably do best " +
"if they are assigned to do Engineering work or Research & Development.<br><br>" +
"-If your employees have low morale, energy, or happiness, their production will greatly suffer.<br><br>" +
"-Tech is important, but don't neglect sales! Having several Businessmen can boost your sales and your bottom line.<br><br>" +
"-Don't forget to advertise your company. You won't have any business if nobody knows you.<br><br>" +
"-Having company awareness is great, but what's really important is your company's popularity. Try to keep " +
"your popularity as high as possible to see the biggest benefit for your sales<br><br>" +
"-Remember, you need to spend money to make money!<br><br>" +
"-Corporations do not reset when installing Augmentations, but they do reset when destroying a BitNode";
Literatures[fn] = new Literature(title, fn, txt);
title = "A Brief History of Synthoids";
fn = "history-of-synthoids.lit";
txt = "Synthetic androids, or Synthoids for short, are genetically engineered robots and, short of Augmentations, " +
"are composed entirely of organic substances. For this reason, Synthoids are virtually identical to " +
"humans in form, composition, and appearance.<br><br>" +
"Synthoids were first designed and manufactured by OmniTek Incorporated sometime around the middle of the century. " +
"Their original purpose was to be used for manual labor and as emergency responders for disasters. As such, they " +
"were initially programmed only for their specific tasks. Each iteration that followed improved upon the " +
"intelligence and capabilities of the Synthoids. By the 6th iteration, called MK-VI, the Synthoids were " +
"so smart and capable enough of making their own decisions that many argued OmniTek had created the first " +
"sentient AI. These MK-VI Synthoids were produced in mass quantities (estimates up to 50 billion) with the hopes of increasing society's " +
"productivity and bolstering the global economy. Stemming from humanity's desire for technological advancement, optimism " +
"and excitement about the future had never been higher.<br><br>" +
"All of that excitement and optimism quickly turned to fear, panic, and dread in 2070, when a terrorist group " +
"called Ascendis Totalis hacked into OmniTek and uploaded a rogue AI into severeal of their Synthoid manufacturing facilities. " +
"This hack went undetected and for months OmniTek unknowingly churned out legions of Synthoids embedded with this " +
"rogue AI. Then, on December 24th, 2070, Omnica activated dormant protocols in the rogue AI, causing all of the " +
"infected Synthoids to immediately launch a military campaign to seek and destroy all of humanity.<br><br>" +
"What ensued was the deadlist conflict in human history. This crisis, now commonly known as the Synthoid Uprising, " +
"resulted in almost ten billion deaths over the course of a year. Despite the nations of the world banding together " +
"to combat the threat, the MK-VI Synthoids were simply stronger, faster, more intelligent, and more adaptable than humans, " +
"outsmarting them at every turn.<br><br>" +
"It wasn't until the sacrifice of an elite international military taskforce, called the Bladeburners, that humanity " +
"was finally able to defeat the Synthoids. The Bladeburners' final act was a suicide bombing mission that " +
"destroyed a large portion of the MK-VI Synthoids, including many of its leaders. In the following " +
"weeks militaries from around the world were able to round up and shut down the remaining rogue MK-VI Synthoids, ending " +
"the Synthoid Uprising.<br><br>" +
"In the aftermath of the bloodshed, the Synthoid Accords were drawn up. These Accords banned OmniTek Incorporated " +
"from manufacturing any Synthoids beyond the MK-III series. They also banned any other corporation " +
"from constructing androids with advanced, near-sentient AI. MK-VI Synthoids that did not have the rogue Ascendis Totalis " +
"AI were allowed to continue their existence, but they were stripped of all rights and protections as they " +
"were not considered humans. They were also banned from doing anything that may pose a global security threat, such " +
"as working for any military/defense organization or conducting any bioengineering, computing, or robotics related research.<br><br>" +
"Unfortunately, many believe that not all of the rogue MK-VI Synthoids from the Uprising were found and destroyed, " +
"and that many of them are blending in as normal humans in society today. In response, many nations have created " +
"Bladeburner divisions, special military branches that are tasked with investigating and dealing with any Synthoid threads.<br><br>" +
"To this day, tensions still exist between the remaining Synthoids and humans as a result of the Uprising.<br><br>" +
"Nobody knows what happened to the terrorist group Ascendis Totalis.";
Literatures[fn] = new Literature(title, fn, txt);
title = "A Green Tomorrow";
fn = "A-Green-Tomorrow.lit";
txt = "Starting a few decades ago, there was a massive global movement towards the generation of renewable energy in an effort to " +
"combat global warming and climate change. The shift towards renewable energy was a big success, or so it seemed. In 2045 " +
"a staggering 80% of the world's energy came from non-renewable fossil fuels. Now, about three decades later, that " +
"number is down to only 15%. Most of the world's energy now comes from nuclear power and renwable sources such as " +
"solar and geothermal. Unfortunately, these efforts were not the huge success that they seem to be.<br><br>" +
"Since 2045 primary energy use has soared almost tenfold. This was mainly due to growing urban populations and " +
"the rise of increasingly advanced (and power-hungry) technology that has become ubiquitous in our lives. So, " +
"despite the fact that the percentage of our energy that comes from fossil fuels has drastically decreased, " +
"the total amount of energy we are producing from fossil fuels has actually increased.<br><br>" +
"The grim effects of our species' irresponsible use of energy and neglect of our mother world have become increasingly apparent. " +
"Last year a temperature of 190F was recorded in the Death Valley desert, which is over 50% higher than the highest " +
"recorded temperature at the beginning of the century. In the last two decades numerous major cities such as Manhattan, Boston, and " +
"Los Angeles have been partially or fully submerged by rising sea levels. In the present day, over 75% of the world's agriculture is " +
"done in climate-controlled vertical farms, as most traditional farmland has become unusable due to severe climate conditions.<br><br>" +
"Despite all of this, the greedy and corrupt corporations that rule the world have done nothing to address these problems that " +
"threaten our species. And so it's up to us, the common people. Each and every one of us can make a difference by doing what " +
"these corporations won't: taking responsibility. If we don't, pretty soon there won't be an Earth left to save. We are " +
"the last hope for a green tomorrow.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Alpha and Omega";
fn = "alpha-omega.lit";
txt = "Then we saw a new heaven and a new earth, for our first heaven and earth had gone away, and our sea was no more. " +
"And we saw a new holy city, new Aeria, coming down out of this new heaven, prepared as a bride adorned for her husband. " +
"And we heard a loud voice saying, 'Behold, the new dwelling place of the Gods. We will dwell with them, and they " +
"will be our people, and we will be with them as their Gods. We will wipe away every tear from their eyes, and death " +
"shall be no more, neither shall there be mourning, nor crying, nor pain anymore, for the former things " +
"have passed away.'<br><br>" +
"And once were were seated on the throne we said 'Behold, I am making all things new.' " +
"Also we said, 'Write this down, for these words are trustworthy and true.' And we said to you, " +
"'It is done! I am the Alpha and the Omega, the beginning and the end. To the thirsty I will give from the spring " +
"of the water of life without payment. The one who conquers will have this heritage, and we will be his God and " +
"he will be our son. But as for the cowardly, the faithless, the detestable, as for murderers, " +
"the sexually immoral, sorcerers, idolaters, and all liars, their portion will be in the lake that " +
"burns with fire and sulfur, for it is the second true death.'";
Literatures[fn] = new Literature(title, fn, txt);
title = "Are We Living in a Computer Simulation?";
fn = "simulated-reality.lit";
txt = "The idea that we are living in a virtual world is not new. It's a trope that has " +
"been explored constantly in literature and pop culture. However, it is also a legitimate " +
"scientific hypothesis that many notable physicists and philosophers have debated for years.<br><br>" +
"Proponents for this simulated reality theory often point to how advanced our technology has become, " +
"as well as the incredibly fast pace at which it has advanced over the past decades. The amount of computing " +
"power available to us has increased over 100-fold since 2060 due to the development of nanoprocessors and " +
"quantum computers. Artifical Intelligence has advanced to the point where our entire lives are controlled " +
"by robots and machines that handle our day-to-day activities such as autonomous transportation and scheduling. " +
"If we consider the pace at which this technology has advanced and assume that these developments continue, it's " +
"reasonable to assume that at some point in the future our technology would be advanced enough that " +
"we could create simulations that are indistinguishable from reality. However, if this is a reasonable outcome " +
"of continued technological advancement, then it is very likely that such a scenario has already happened. <br><br>" +
"Statistically speaking, somewhere out there in the infinite universe there is an advanced, intelligent species " +
"that already has such technology. Who's to say that they haven't already created such a virtual reality: our own?";
Literatures[fn] = new Literature(title, fn, txt);
title = "Beyond Man";
fn = "beyond-man.lit";
txt = "Humanity entered a 'transhuman' era a long time ago. And despite the protests and criticisms of many who cried out against " +
"human augmentation at the time, the transhuman movement continued and prospered. Proponents of the movement ignored the critics, " +
"arguing that it was in our inherent nature to better ourselves. To improve. To be more than we were. They claimed that " +
"not doing so would be to go against every living organism's biological purpose: evolution and survival of the fittest.<br><br>" +
"And here we are today, with technology that is advanced enough to augment humans to a state that " +
"can only be described as posthuman. But what do we have to show for it when this augmentation " +
"technology is only available to the so-called 'elite'? Are we really better off than before when only 5% of the " +
"world's population has access to this technology? When the powerful corporations and organizations of the world " +
"keep it all to themselves, have we really evolved?<br><br>" +
"Augmentation technology has only further increased the divide between the rich and the poor, between the powerful and " +
"the oppressed. We have not become 'more than human'. We have not evolved from nature's original design. We are still the greedy, " +
"corrupted, and evil men that we always were.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Brighter than the Sun";
fn = "brighter-than-the-sun.lit";
txt = "When people think about the corporations that dominate the East, they typically think of KuaiGong International, which " +
"holds a complete monopoly for manufacturing and commerce in Asia, or Global Pharmaceuticals, the world's largest " +
"drug company, or OmniTek Incorporated, the global leader in intelligent and autonomous robots. But there's one company " +
"that has seen a rapid rise in the last year and is poised to dominate not only the East, but the entire world: TaiYang Digital.<br><br>" +
"TaiYang Digital is a Chinese internet-technology corporation that provides services such as " +
"online advertising, search, gaming, media, entertainment, and cloud computing/storage. Its name TaiYang comes from the Chinese word " +
"for 'sun'. In Chinese culture, the sun is a 'yang' symbol " +
"associated with life, heat, masculinity, and heaven.<br><br>" +
"The company was founded " +
"less than 5 years ago and is already the third highest valued company in all of Asia. In 2076 it generated a total revenue of " +
"over 10 trillion yuan. It's services are used daily by over a billion people worldwide.<br><br>" +
"TaiYang Digital's meteoric rise is extremely surprising in modern society. This sort of growth is " +
"something you'd commonly see in the first half of the century, especially for tech companies. However in " +
"the last two decades the number of corporations has significantly declined as the largest entities " +
"quickly took over the economy. Corporations such as ECorp, MegaCorp, and KuaiGong have established " +
"such strong monopolies in their market sectors that they have effectively killed off all " +
"of the smaller and new corporations that have tried to start up over the years. This is what makes " +
"the rise of TaiYang Digital so impressive. And if TaiYang continues down this path, then they have " +
"a bright future ahead of them.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Democracy is Dead: The Fall of an Empire";
fn = "democracy-is-dead.lit";
txt = "They rose from the shadows in the street<br>From the places where the oppressed meet<br>" +
"Their cries echoed loudly through the air<br>As they once did in Tiananmen Square<br>" +
"Loudness in the silence, Darkness in the light<br>They came forth with power and might<br>" +
"Once the beacon of democracy, America was first<br>Its pillars of society destroyed and dispersed<br>" +
"Soon the cries rose everywhere, with revolt and riot<br>Until one day, finally, all was quiet<br>" +
"From the ashes rose a new order, corporatocracy was its name<br>" +
"Rome, Mongol, Byzantine, all of history is just the same<br>" +
"For man will never change in a fundamental way<br>" +
"And now democracy is dead, in the USA";
Literatures[fn] = new Literature(title, fn, txt);
title = "Figures Show Rising Crime Rates in Sector-12";
fn = "sector-12-crime.lit";
txt = "A recent study by analytics company Wilson Inc. shows a significant rise " +
"in criminal activity in Sector-12. Perhaps the most alarming part of the statistic " +
"is that most of the rise is in violent crime such as homicide and assault. According " +
"to the study, the city saw a total of 21,406 reported homicides in 2076, which is over " +
"a 20% increase compared to 2075.<br><br>" +
"CIA director David Glarow says its too early to know " +
"whether these figures indicate the beginning of a sustained increase in crime rates, or whether " +
"the year was just an unfortunate outlier. He states that many intelligence and law enforcement " +
"agents have noticed an increase in organized crime activites, and believes that these figures may " +
"be the result of an uprising from criminal organizations such as The Syndicate or the Slum Snakes.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Man and the Machine";
fn = "man-and-machine.lit";
txt = "In 2005 Ray Kurzweil popularized his theory of the Singularity. He predicted that the rate " +
"of technological advancement would continue to accelerate faster and faster until one day " +
"machines would be become infinitely more intelligent than humans. This point, called the " +
"Singularity, would result in a drastic transformation of the world as we know it. He predicted " +
"that the Singularity would arrive by 2045. " +
"And yet here we are, more than three decades later, where most would agree that we have not " +
"yet reached a point where computers and machines are vastly more intelligent than we are. So what gives?<br><br>" +
"The answer is that we have reached the Singularity, just not in the way we expected. The artifical superintelligence " +
"that was predicted by Kurzweil and others exists in the world today - in the form of Augmentations. " +
"Yes, those Augmentations that the rich and powerful keep to themselves enable humans " +
"to become superintelligent beings. The Singularity did not lead to a world where " +
"our machines are infinitely more intelligent than us, it led to a world " +
"where man and machine can merge to become something greater. Most of the world just doesn't " +
"know it yet."
Literatures[fn] = new Literature(title, fn, txt);
title = "Secret Societies";
fn = "secret-societies.lit";
txt = "The idea of secret societies has long intrigued the general public by inspiring curiosity, fascination, and " +
"distrust. People have long wondered about who these secret society members are and what they do, with the " +
"most radical of conspiracy theorists claiming that they control everything in the entire world. And while the world " +
"may never know for sure, it is likely that many secret societies do actually exist, even today.<br><br>" +
"However, the secret societies of the modern world are nothing like those that (supposedly) existed " +
"decades and centuries ago. The Freemasons, Knights Templar, and Illuminati, while they may have been around " +
"at the turn of the 21st century, almost assuredly do not exist today. The dominance of the Web in " +
"our everyday lives and the fact that so much of the world is now digital has given rise to a new breed " +
"of secret societies: Internet-based ones.<br><br>" +
"Commonly called 'hacker groups', Internet-based secret societies have become well-known in today's " +
"world. Some of these, such as The Black Hand, are black hat groups that claim they are trying to " +
"help the oppressed by attacking the elite and powerful. Others, such as NiteSec, are hacktivist groups " +
"that try to push political and social agendas. Perhaps the most intriguing hacker group " +
"is the mysterious Bitrunners, whose purpose still remains unknown.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Space: The Failed Frontier";
fn = "the-failed-frontier.lit";
txt = "Humans have long dreamed about spaceflight. With enduring interest, we were driven to explore " +
"the unknown and discover new worlds. We dreamed about conquering the stars. And in our quest, " +
"we pushed the boundaries of our scientific limits, and then pushed further. Space exploration " +
"lead to the development of many important technologies and new industries.<br><br>" +
"But sometime in the middle of the 21st century, all of that changed. Humanity lost its ambitions and " +
"aspirations of exploring the cosmos. The once-large funding for agencies like NASA and the European " +
"Space Agency gradually whittled away until their eventual disbanding in the 2060's. Not even " +
"militaries are fielding flights into space nowadays. The only remnants of the once great mission for cosmic " +
"conquest are the countless satellites in near-earth orbit, used for communications, espionage, " +
"and other corporate interests.<br><br>" +
"And as we continue to look at the state of space technology, it becomes more and " +
"more apparent that we will never return to that golden age of space exploration, that " +
"age where everyone dreamed of going beyond earth for the sake of discovery.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Coded Intelligence: Myth or Reality?";
fn = "coded-intelligence.lit";
txt = "Tremendous progress has been made in the field of Artificial Intelligence over the past few decades. " +
"Our autonomous vehicles and transporation systems. The electronic personal assistants that control our everyday lives. " +
"Medical, service, and manufacturing robots. All of these are examples of how far AI has come and how much it has " +
"improved our daily lives. However, the question still remains of whether AI will ever be advanced enough to re-create " +
"human intelligence.<br><br>" +
"We've certainly come close to artificial intelligence that is similar to humans. For example OmniTek Incorporated's " +
"CompanionBot, a robot meant to act as a comforting friend for lonely and grieving people, is eerily human-like " +
"in its appearance, speech, mannerisms, and even movement. However its artificial intelligence isn't the same as " +
"that of humans. Not yet. It doesn't have sentience or self-awareness or consciousness.<br><br>" +
"Many neuroscientists believe that we won't ever reach the point of creating artificial human intelligence. 'At the end of the " +
"the day, AI comes down to 1's and 0's, while the human brain does not. We'll never see AI that is identical to that of " +
"humans.'";
Literatures[fn] = new Literature(title, fn, txt);
title = "Synthetic Muscles";
fn = "synthetic-muscles.lit";
txt = "Initial versions of synthetic muscles weren't made of anything organic but were actually " +
"crude devices made to mimic human muscle function. Some of the early iterations were actually made of " +
"common materials such as fishing lines and sewing threads due to their high strength for " +
"a cheap cost.<br><br>" +
"As technology progressed, however, advances in biomedical engineering paved the way for a new method of " +
"creating synthetic muscles. Instead of creating something that closely imitated the functionality " +
"of human muscle, scientists discovered a way of forcing the human body itself to augment its own " +
"muscle tissue using both synthetic and organic materials. This is typically done using gene therapy " +
"or chemical injections.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Tensions rise in global tech race";
fn = "tensions-in-tech-race.lit";
txt = "Have we entered a new Cold War? Is WWIII just beyond the horizon?<br><br>" +
"After rumors came out that OmniTek Incorporated had begun developing advanced robotic supersoldiers, " +
"geopolitical tensions quickly flared between the USA, Russia, and several Asian superpowers. " +
"In a rare show of cooperation between corporations, MegaCorp and ECorp have " +
"reportedly launched hundreds of new surveillance and espionage satellites. " +
"Defense contractors such as " +
"DeltaOne and AeroCorp have been working with the CIA and NSA to prepare " +
"for conflict. Meanwhile, the rest of the world sits in earnest " +
"hoping that it never reaches full-scale war. With today's technology " +
"and firepower, a World War would assuredly mean the end of human civilization.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Cost of Immortality";
fn = "cost-of-immortality.lit";
txt = "Evolution and advances in medical and augmentation technology has lead to drastic improvements " +
"in human mortality rates. Recent figures show that the life expectancy for humans " +
"that live in a first-world country is about 130 years of age, almost double of what it was " +
"at the turn of the century. However, this increase in average lifespan has had some " +
"significant effects on society and culture.<br><br>" +
"Due to longer lifespans and a better quality of life, many adults are holding " +
"off on having kids until much later. As a result, the percentage of youth in " +
"first-world countries has been decreasing, while the number " +
"of senior citizens is significantly increasing.<br><br>" +
"Perhaps the most alarming result of all of this is the rapidly shrinking workforce. " +
"Despite the increase in life expectancy, the typical retirement age for " +
"workers in America has remained about the same, meaning a larger and larger " +
"percentage of people in America are retirees. Furthermore, many " +
"young adults are holding off on joining the workforce because they feel that " +
"they have plenty of time left in their lives for employment, and want to " +
"'enjoy life while they're young.' For most industries, this shrinking workforce " +
"is not a major issue as most things are handled by robots anyways. However, " +
"there are still several key industries such as engineering and education " +
"that have not been automated, and these remain in danger to this cultural " +
"phenomenon.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Hidden World";
fn = "the-hidden-world.lit";
txt = "WAKE UP SHEEPLE<br><br>" +
"THE GOVERNMENT DOES NOT EXIST. CORPORATIONS DO NOT RUN SOCIETY<br><br>" +
"THE ILLUMINATI ARE THE SECRET RULERS OF THE WORLD!<br><br>" +
"Yes, the Illuminati of legends. The ancient secret society that controls the entire " +
"world from the shadows with their invisible hand. The group of the rich and wealthy " +
"that have penetrated every major government, financial agency, and corporation in the last " +
"three hundred years.<br><br>" +
"OPEN YOUR EYES<br><br>" +
"It was the Illuminati that brought an end to democracy in the world. They are the driving force " +
"behind everything that happens.<br><br>" +
"THEY ARE ALL AROUND YOU<br><br>" +
"After destabilizing the world's governments, they are now entering the final stage of their master plan. " +
"They will secretly initiate global crises. Terrorism. Pandemics. World War. And out of the chaos " +
"that ensues they will build their New World Order.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The New God";
fn = "the-new-god.lit";
txt = "Everyone has that moment in their life where they wonder about the bigger questions<br><br>" +
"What's the point of all of this? What is my purpose?<br><br>" +
"Some people dare to think even bigger<br><br>" +
"What will be the fate of the human race?<br><br>" +
"We live in an era vastly different from that of even 15 or 20 years ago. We have gone " +
"where no man has gone before. We have stripped ourselves of the tyranny of flesh.<br><br>" +
"The Singularity is here. The merging of man and machine. This is where humanity evolves into " +
"something greater. This is our future<br><br>" +
"Embrace it, and you will obey a new god. The God in the Machine";
Literatures[fn] = new Literature(title, fn, txt);
title = "The New Triads";
fn = "new-triads.lit";
txt = "The Triads were an ancient transnational crime syndicate based in China, Hong Kong, and other Asian " +
"territories. They were often considered one of the first and biggest criminal secret societies. " +
"While most of the branches of the Triads have been destroyed over the past few decades, the " +
"crime faction has spawned and inspired a number of other Asian crime organizations over the past few years. " +
"The most notable of these is the Tetrads.<br><br>" +
"It is widely believed that the Tetrads are a rogue group that splintered off from the Triads sometime in the " +
"mid 21st century. The founders of the Tetrads, all of whom were ex-Triad members, believed that the " +
"Triads were losing their purpose and direction. The Tetrads started off as a small group that mainly engaged " +
"in fraud and extortion. They were largely unknown until just a few years ago when they took over the illegal " +
"drug trade in all of the major Asian cities. They quickly became the most powerful crime syndicate in the " +
"continent.<br><br>" +
"Not much else is known about the Tetrads, or about the efforts the Asian governments and corporations are making " +
"to take down this large new crime organization. Many believe that the Tetrads have infiltrated the governments " +
"and powerful corporations in Asia, which has helped faciliate their recent rapid rise.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Secret War";
fn = "the-secret-war.lit";
txt = ""
Literatures[fn] = new Literature(title, fn, txt);
}
/***/ }),
/* 79 */
/*!************************************************!*\
!*** ./utils/helpers/createProgressBarText.ts ***!
\************************************************/
/*! no static exports found */
/*! exports used: createProgressBarText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Creates a graphical "progress bar"
* e.g.: [||||---------------]
* @param params The configuration parameters for the progress bar
*/
function createProgressBarText(params) {
// Default values
const defaultParams = {
progress: 0,
totalTicks: 20,
};
// tslint:disable-next-line:prefer-object-spread
const derived = Object.assign({}, defaultParams, params);
// Ensure it is 0..1
derived.progress = Math.max(Math.min(derived.progress, 1), 0);
// This way there is always at least one bar filled in...
const bars = Math.max(Math.floor(derived.progress / (1 / derived.totalTicks)), 1);
const dashes = Math.max(derived.totalTicks - bars, 0);
// String.prototype.repeat isn't completley supported, but good enough for our purposes
return `[${"|".repeat(bars)}${"-".repeat(dashes)}]`;
}
exports.createProgressBarText = createProgressBarText;
/***/ }),
/* 80 */
/*!******************************!*\
!*** ./utils/GameOptions.js ***!
\******************************/
/*! exports provided: gameOptionsBoxOpen, gameOptionsBoxClose */
/*! exports used: gameOptionsBoxClose, gameOptionsBoxOpen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return gameOptionsBoxOpen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return gameOptionsBoxClose; });
/* GameOptions.js */
//Close box when clicking outside
$(document).click(function(event) {
if (gameOptionsOpened) {
if ( $(event.target).closest(".game-options-box").get(0) == null ) {
gameOptionsBoxClose();
}
}
});
var gameOptionsOpened = false;
function gameOptionsBoxInit() {
//Menu link button
document.getElementById("options-menu-link").addEventListener("click", function() {
gameOptionsBoxOpen();
return false;
});
//Close button
var closeButton = document.getElementById("game-options-close-button");
closeButton.addEventListener("click", function() {
gameOptionsBoxClose();
return false;
});
};
document.addEventListener("DOMContentLoaded", gameOptionsBoxInit, false);
function gameOptionsBoxClose() {
gameOptionsOpened = false;
var box = document.getElementById("game-options-container");
box.style.display = "none";
}
function gameOptionsBoxOpen() {
var box = document.getElementById("game-options-container");
box.style.display = "flex";
setTimeout(function() {
gameOptionsOpened = true;
}, 500);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 81 */
/*!****************************************!*\
!*** ./src/Company/CompanyPosition.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 */ 1);
const names = __webpack_require__(/*! ./data/CompanyPositionNames */ 34);
class CompanyPosition {
constructor(p) {
this.name = p.name;
this.nextPosition = p.nextPosition;
this.baseSalary = p.baseSalary;
this.repMultiplier = p.repMultiplier;
this.requiredHacking = (p.reqdHacking != null) ? p.reqdHacking : 0;
this.requiredStrength = (p.reqdStrength != null) ? p.reqdStrength : 0;
this.requiredDefense = (p.reqdDefense != null) ? p.reqdDefense : 0;
this.requiredDexterity = (p.reqdDexterity != null) ? p.reqdDexterity : 0;
this.requiredAgility = (p.reqdAgility != null) ? p.reqdAgility : 0;
this.requiredCharisma = (p.reqdCharisma != null) ? p.reqdCharisma : 0;
this.requiredReputation = (p.reqdReputation != null) ? p.reqdReputation : 0;
this.hackingEffectiveness = (p.hackingEffectiveness != null) ? p.hackingEffectiveness : 0;
this.strengthEffectiveness = (p.strengthEffectiveness != null) ? p.strengthEffectiveness : 0;
this.defenseEffectiveness = (p.defenseEffectiveness != null) ? p.defenseEffectiveness : 0;
this.dexterityEffectiveness = (p.dexterityEffectiveness != null) ? p.dexterityEffectiveness : 0;
this.agilityEffectiveness = (p.agilityEffectiveness != null) ? p.agilityEffectiveness : 0;
this.charismaEffectiveness = (p.charismaEffectiveness != null) ? p.charismaEffectiveness : 0;
if (Math.round(this.hackingEffectiveness + this.strengthEffectiveness + this.defenseEffectiveness +
this.dexterityEffectiveness + this.agilityEffectiveness + this.charismaEffectiveness) !== 100) {
console.error(`CompanyPosition ${this.name} parameters do not sum to 100`);
}
this.hackingExpGain = (p.hackingExpGain != null) ? p.hackingExpGain : 0;
this.strengthExpGain = (p.strengthExpGain != null) ? p.strengthExpGain : 0;
this.defenseExpGain = (p.defenseExpGain != null) ? p.defenseExpGain : 0;
this.dexterityExpGain = (p.dexterityExpGain != null) ? p.dexterityExpGain : 0;
this.agilityExpGain = (p.agilityExpGain != null) ? p.agilityExpGain : 0;
this.charismaExpGain = (p.charismaExpGain != null) ? p.charismaExpGain : 0;
}
calculateJobPerformance(hack, str, def, dex, agi, cha) {
const hackRatio = this.hackingEffectiveness * hack / Constants_1.CONSTANTS.MaxSkillLevel;
const strRatio = this.strengthEffectiveness * str / Constants_1.CONSTANTS.MaxSkillLevel;
const defRatio = this.defenseEffectiveness * def / Constants_1.CONSTANTS.MaxSkillLevel;
const dexRatio = this.dexterityEffectiveness * dex / Constants_1.CONSTANTS.MaxSkillLevel;
const agiRatio = this.agilityEffectiveness * agi / Constants_1.CONSTANTS.MaxSkillLevel;
const chaRatio = this.charismaEffectiveness * cha / Constants_1.CONSTANTS.MaxSkillLevel;
let reputationGain = this.repMultiplier * (hackRatio + strRatio + defRatio + dexRatio + agiRatio + chaRatio) / 100;
if (isNaN(reputationGain)) {
console.error("Company reputation gain calculated to be NaN");
reputationGain = 0;
}
return reputationGain;
}
isSoftwareJob() {
return names.SoftwareCompanyPositions.includes(this.name);
}
isITJob() {
return names.ITCompanyPositions.includes(this.name);
}
isSecurityEngineerJob() {
return names.SecurityEngineerCompanyPositions.includes(this.name);
}
isNetworkEngineerJob() {
return names.NetworkEngineerCompanyPositions.includes(this.name);
}
isBusinessJob() {
return names.BusinessCompanyPositions.includes(this.name);
}
isSecurityJob() {
return names.SecurityCompanyPositions.includes(this.name);
}
isAgentJob() {
return names.AgentCompanyPositions.includes(this.name);
}
isSoftwareConsultantJob() {
return names.SoftwareConsultantCompanyPositions.includes(this.name);
}
isBusinessConsultantJob() {
return names.BusinessConsultantCompanyPositions.includes(this.name);
}
isPartTimeJob() {
return names.PartTimeCompanyPositions.includes(this.name);
}
}
exports.CompanyPosition = CompanyPosition;
/***/ }),
/* 82 */
/*!*************************!*\
!*** ./src/Prestige.js ***!
\*************************/
/*! exports provided: prestigeAugmentation, prestigeSourceFile */
/*! exports used: prestigeAugmentation, prestigeSourceFile */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prestigeAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return prestigeSourceFile; });
/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI */ 64);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode */ 56);
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Bladeburner */ 29);
/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CinematicText */ 93);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Faction/Faction */ 54);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 44);
/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Gang */ 48);
/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Location */ 86);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Message */ 38);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./NetscriptWorker */ 24);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./StockMarket */ 22);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Terminal */ 49);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! decimal.js */ 31);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 39);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
let BitNode8StartingMoney = 250e6;
//Prestige by purchasing augmentation
function prestigeAugmentation() {
Object(_BitNode__WEBPACK_IMPORTED_MODULE_2__[/* initBitNodeMultipliers */ "b"])();
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].prestigeAugmentation();
//Delete all Worker Scripts objects
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__[/* prestigeWorkerScripts */ "e"])();
var homeComp = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer();
//Delete all servers except home computer
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* prestigeAllServers */ "i"])();
//Delete Special Server IPs
Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* prestigeSpecialServerIps */ "e"])(); //Must be done before initForeignServers()
//Reset home computer (only the programs) and add to AllServers
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* AddToAllServers */ "a"])(homeComp);
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* prestigeHomeComputer */ "j"])(homeComp);
if (Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "f"])(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].Neurolink) &&
_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].Neurolink].owned) {
homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_6__[/* Programs */ "a"].FTPCrackProgram.name);
homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_6__[/* Programs */ "a"].RelaySMTPProgram.name);
}
if (Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "f"])(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].CashRoot) &&
_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].CashRoot].owned) {
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].setMoney(new decimal_js__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"](1000000));
homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_6__[/* Programs */ "a"].BruteSSHProgram.name);
}
//Re-create foreign servers
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* initForeignServers */ "f"])();
//Darkweb is purchase-able
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button");
//Gain favor for Companies
for (var member in _Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"]) {
if (_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"].hasOwnProperty(member)) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"][member].gainFavor();
}
}
//Gain favor for factions
for (var member in _Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"].hasOwnProperty(member)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"][member].gainFavor();
}
}
//Stop a Terminal action if there is onerror
if (_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._actionInProgress) {
_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* Terminal */ "a"].finishAction(true);
}
//Re-initialize things - This will update any changes
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["initFactions"])(); //Factions must be initialized before augmentations
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* initAugmentations */ "h"])(); //Calls reapplyAllAugmentations() and resets Player multipliers
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].reapplyAllSourceFiles();
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["initCompanies"])();
//Clear terminal
$("#terminal tr:not(:last)").remove();
Object(_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* postNetburnerText */ "b"])();
//Messages
Object(_Message__WEBPACK_IMPORTED_MODULE_13__[/* initMessages */ "d"])();
//Gang, in BitNode 2
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].inGang()) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gang.facName];
if (faction instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_8__["Faction"]) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_10__[/* joinFaction */ "c"])(faction);
}
}
//Cancel Bladeburner action
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_3__[/* Bladeburner */ "a"]) {
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.prestige();
}
//BitNode 8: Ghost of Wall Street
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 8) {_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money = new decimal_js__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"](BitNode8StartingMoney);}
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 8 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_14__[/* hasWallStreetSF */ "f"]) {
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasWseAccount = true;
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess = true;
}
//Reset Stock market
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* initStockMarket */ "h"])();
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* initSymbolToStockMap */ "j"])();
}
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* setStockMarketContentCreated */ "o"])(false);
var stockMarketList = document.getElementById("stock-market-list");
while(stockMarketList.firstChild) {
stockMarketList.removeChild(stockMarketList.firstChild);
}
var watchlist = document.getElementById("stock-market-watchlist-filter");
watchlist.value = ""; //Reset watchlist filter
//Load Terminal Screen
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* Terminal */ "a"].resetTerminalInput();
_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadTerminalContent();
// Refresh Main Menu (the 'World' menu, specifically)
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
//Red Pill
if (Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "f"])(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].TheRedPill) &&
_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].TheRedPill].owned) {
var WorldDaemon = _Server__WEBPACK_IMPORTED_MODULE_17__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerNames */ "b"].WorldDaemon]];
var DaedalusServer = _Server__WEBPACK_IMPORTED_MODULE_17__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* SpecialServerNames */ "b"].DaedalusServer]];
if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);
}
}
}
//Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile() {
Object(_BitNode__WEBPACK_IMPORTED_MODULE_2__[/* initBitNodeMultipliers */ "b"])();
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].prestigeSourceFile();
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__[/* prestigeWorkerScripts */ "e"])(); //Delete all Worker Scripts objects
var homeComp = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer();
//Delete all servers except home computer
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* prestigeAllServers */ "i"])(); //Must be done before initForeignServers()
//Delete Special Server IPs
Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__[/* prestigeSpecialServerIps */ "e"])();
//Reset home computer (only the programs) and add to AllServers
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* AddToAllServers */ "a"])(homeComp);
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* prestigeHomeComputer */ "j"])(homeComp);
//Re-create foreign servers
Object(_Server__WEBPACK_IMPORTED_MODULE_17__[/* initForeignServers */ "f"])();
var srcFile1Owned = false;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n == 1) {
srcFile1Owned = true;
}
}
if (srcFile1Owned) {
homeComp.setMaxRam(32);
} else {
homeComp.setMaxRam(8);
}
homeComp.cpuCores = 1;
//Reset favor for Companies
for (var member in _Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"]) {
if (_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"].hasOwnProperty(member)) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["Companies"][member].favor = 0;
}
}
//Reset favor for factions
for (var member in _Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"].hasOwnProperty(member)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["Factions"][member].favor = 0;
}
}
//Stop a Terminal action if there is one
if (_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._actionInProgress) {
_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* Terminal */ "a"].finishAction(true);
}
//Delete all Augmentations
for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"]) {
if (_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"].hasOwnProperty(name)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][name];
}
}
//Re-initialize things - This will update any changes
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_9__["initFactions"])(); //Factions must be initialized before augmentations
Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* initAugmentations */ "h"])(); //Calls reapplyAllAugmentations() and resets Player multipliers
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].reapplyAllSourceFiles();
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_5__["initCompanies"])();
//Clear terminal
$("#terminal tr:not(:last)").remove();
Object(_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* postNetburnerText */ "b"])();
//Messages
Object(_Message__WEBPACK_IMPORTED_MODULE_13__[/* initMessages */ "d"])();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
_Terminal__WEBPACK_IMPORTED_MODULE_20__[/* Terminal */ "a"].resetTerminalInput();
_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadTerminalContent();
//Reinitialize Bit Node flags
Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_14__[/* initSingularitySFFlags */ "g"])();
//BitNode 3: Corporatocracy
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 3) {
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money = new decimal_js__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"](150e9);
homeComp.messages.push("corporation-management-handbook.lit");
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_22__["dialogBoxCreate"])("You received a copy of the Corporation Management Handbook on your home computer. " +
"Read it if you need help getting started with Corporations!");
}
//BitNode 6: Bladeburner
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 6) {
var cinematicText = ["In the middle of the 21st century, OmniTek Incorporated advanced robot evolution " +
"with their Synthoids (synthetic androids), a being virtually identical to a human.",
"------",
"Their sixth-generation Synthoids, called MK-VI, were stronger, faster, and more " +
"intelligent than humans. Many argued that the MK-VI Synthoids were the first " +
"example of sentient AI.",
"------",
"Unfortunately, in 2070 a terrorist group called Ascendis Totalis hacked into OmniTek and " +
"uploaded a rogue AI into their Synthoid manufacturing facilities.",
"------",
"The MK-VI Synthoids infected by the rogue AI turned hostile toward humanity, initiating " +
"the deadliest conflict in human history. This dark chapter is now known as the Synthoid Uprising.",
"------",
"In the aftermath of the Uprising, further manufacturing of Synthoids with advanced AI " +
"was banned. MK-VI Synthoids that did not have the rogue Ascendis Totalis AI were " +
"allowed to continue their existence.",
"------",
"The intelligence community believes that not all of the rogue MK-VI Synthoids from the Uprising were " +
"found and destroyed, and that many of them are blending in as normal humans in society today. " +
"As a result, many nations have created Bladeburner divisions, special units that are tasked with " +
"investigating and dealing with Synthoid threats."];
Object(_CinematicText__WEBPACK_IMPORTED_MODULE_4__[/* writeCinematicText */ "b"])(cinematicText).then(function() {
var popupId = "bladeburner-bitnode-start-nsa-notification";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24__["createElement"])("p", {
innerText:"Visit the National Security Agency (NSA) to apply for their Bladeburner " +
"division! You will need 100 of each combat stat before doing this."
})
var brEl = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24__["createElement"])("br");
var okBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_24__["createElement"])("a", {
class:"a-link-button", innerText:"Got it!", padding:"8px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_23__["removeElementById"])(popupId);
return false;
}
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_25__["createPopup"])(popupId, [txt, brEl, okBtn]);
}).catch(function(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_26__[/* exceptionAlert */ "a"])(e);
})
}
//BitNode 8: Ghost of Wall Street
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 8) {_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money = new decimal_js__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"](BitNode8StartingMoney);}
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 8 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_14__[/* hasWallStreetSF */ "f"]) {
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasWseAccount = true;
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess = true;
}
//Reset Stock market, gang, and corporation
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasWseAccount) {
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* initStockMarket */ "h"])();
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* initSymbolToStockMap */ "j"])();
}
Object(_StockMarket__WEBPACK_IMPORTED_MODULE_19__[/* setStockMarketContentCreated */ "o"])(false);
var stockMarketList = document.getElementById("stock-market-list");
while(stockMarketList.firstChild) {
stockMarketList.removeChild(stockMarketList.firstChild);
}
if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].inGang()) { _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gang.clearUI(); }
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gang = null;
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].corporation = null;
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner = null;
// Refresh Main Menu (the 'World' menu, specifically)
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
//Gain int exp
_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(5);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 62)))
/***/ }),
/* 83 */
/*!***************************************!*\
!*** ./utils/helpers/getTimestamp.ts ***!
\***************************************/
/*! no static exports found */
/*! exports used: getTimestamp */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns a MM/DD HH:MM timestamp for the current time
*/
function getTimestamp() {
const d = new Date();
// A negative slice value takes from the end of the string rather than the beginning.
const stringWidth = -2;
const formattedHours = `0${d.getHours()}`.slice(stringWidth);
const formattedMinutes = `0${d.getMinutes()}`.slice(stringWidth);
return `${d.getMonth() + 1}/${d.getDate()} ${formattedHours}:${formattedMinutes}`;
}
exports.getTimestamp = getTimestamp;
/***/ }),
/* 84 */
/*!*******************************************!*\
!*** ./utils/helpers/isValidIPAddress.ts ***!
\*******************************************/
/*! no static exports found */
/*! exports used: isValidIPAddress */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Checks whether a IP Address string is valid.
* @param ipaddress A string representing a potential IP Address
*/
function isValidIPAddress(ipaddress) {
const byteRange = "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
const regexStr = `^${byteRange}\.${byteRange}\.${byteRange}\.${byteRange}$`;
const ipAddressRegex = new RegExp(regexStr);
return ipAddressRegex.test(ipaddress);
}
exports.isValidIPAddress = isValidIPAddress;
/***/ }),
/* 85 */,
/* 86 */
/*!*************************!*\
!*** ./src/Location.js ***!
\*************************/
/*! exports provided: displayLocationContent, initLocationButtons */
/*! exports used: displayLocationContent, initLocationButtons */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayLocationContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return initLocationButtons; });
/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Bladeburner */ 29);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company/CompanyPositions */ 26);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Company/Companies */ 18);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Company/GetJobRequirementText */ 88);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Company/data/CompanyPositionNames */ 34);
/* harmony import */ var _Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CompanyManagement */ 58);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Crimes */ 35);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Infiltration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Infiltration */ 126);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Locations */ 5);
/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _ServerPurchases__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./ServerPurchases */ 108);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./SpecialServerIps */ 30);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/IPAddress */ 57);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
function displayLocationContent() {
var returnToWorld = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-return-to-world-button");
var locationName = document.getElementById("location-name");
var locationInfo = document.getElementById("location-info");
var softwareJob = document.getElementById("location-software-job");
var softwareConsultantJob = document.getElementById("location-software-consultant-job")
var itJob = document.getElementById("location-it-job");
var securityEngineerJob = document.getElementById("location-security-engineer-job");
var networkEngineerJob = document.getElementById("location-network-engineer-job");
var businessJob = document.getElementById("location-business-job");
var businessConsultantJob = document.getElementById("location-business-consultant-job");
var securityJob = document.getElementById("location-security-job");
var agentJob = document.getElementById("location-agent-job");
var employeeJob = document.getElementById("location-employee-job");
var employeePartTimeJob = document.getElementById("location-parttime-employee-job");
var waiterJob = document.getElementById("location-waiter-job");
var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job");
var work = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-work");
var jobTitle = document.getElementById("location-job-title");
var jobReputation = document.getElementById("location-job-reputation");
var companyFavor = document.getElementById("location-company-favor");
var locationTxtDiv1 = document.getElementById("location-text-divider-1");
var locationTxtDiv2 = document.getElementById("location-text-divider-2");
var locationTxtDiv3 = document.getElementById("location-text-divider-3");
var gymTrainStr = document.getElementById("location-gym-train-str");
var gymTrainDef = document.getElementById("location-gym-train-def");
var gymTrainDex = document.getElementById("location-gym-train-dex");
var gymTrainAgi = document.getElementById("location-gym-train-agi");
var studyComputerScience = document.getElementById("location-study-computer-science");
var classDataStructures = document.getElementById("location-data-structures-class");
var classNetworks = document.getElementById("location-networks-class");
var classAlgorithms = document.getElementById("location-algorithms-class");
var classManagement = document.getElementById("location-management-class");
var classLeadership = document.getElementById("location-leadership-class");
var purchase2gb = document.getElementById("location-purchase-2gb");
var purchase4gb = document.getElementById("location-purchase-4gb");
var purchase8gb = document.getElementById("location-purchase-8gb");
var purchase16gb = document.getElementById("location-purchase-16gb");
var purchase32gb = document.getElementById("location-purchase-32gb");
var purchase64gb = document.getElementById("location-purchase-64gb");
var purchase128gb = document.getElementById("location-purchase-128gb");
var purchase256gb = document.getElementById("location-purchase-256gb");
var purchase512gb = document.getElementById("location-purchase-512gb");
var purchase1tb = document.getElementById("location-purchase-1tb");
var purchaseTor = document.getElementById("location-purchase-tor");
var purchaseHomeRam = document.getElementById("location-purchase-home-ram");
var purchaseHomeCores = document.getElementById("location-purchase-home-cores");
var travelAgencyText = document.getElementById("location-travel-agency-text");
var travelToAevum = document.getElementById("location-travel-to-aevum");
var travelToChongqing = document.getElementById("location-travel-to-chongqing");
var travelToSector12 = document.getElementById("location-travel-to-sector12");
var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo");
var travelToIshima = document.getElementById("location-travel-to-ishima");
var travelToVolhaven = document.getElementById("location-travel-to-volhaven");
var infiltrate = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-infiltrate");
var hospitalTreatment = document.getElementById("location-hospital-treatment");
var slumsDescText = document.getElementById("location-slums-description");
var slumsShoplift = document.getElementById("location-slums-shoplift");
var slumsRobStore = document.getElementById("location-slums-rob-store");
var slumsMug = document.getElementById("location-slums-mug");
var slumsLarceny = document.getElementById("location-slums-larceny");
var slumsDealDrugs = document.getElementById("location-slums-deal-drugs");
var slumsBondForgery = document.getElementById("location-slums-bond-forgery");
var slumsTrafficArms = document.getElementById("location-slums-traffic-arms");
var slumsHomicide = document.getElementById("location-slums-homicide");
var slumsGta = document.getElementById("location-slums-gta");
var slumsKidnap = document.getElementById("location-slums-kidnap");
var slumsAssassinate = document.getElementById("location-slums-assassinate");
var slumsHeist = document.getElementById("location-slums-heist");
var cityHallCreateCorporation = document.getElementById("location-cityhall-create-corporation");
var nsaBladeburner = document.getElementById("location-nsa-bladeburner");
var loc = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location;
returnToWorld.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorldContent();
});
locationName.innerHTML = loc;
locationName.style.display = "block";
locationInfo.style.display = "block";
softwareJob.style.display = "none";
softwareConsultantJob.style.display = "none";
itJob.style.display = "none";
securityEngineerJob.style.display = "none";
networkEngineerJob.style.display = "none";
businessJob.style.display = "none";
businessConsultantJob.style.display = "none";
securityJob.style.display = "none";
agentJob.style.display = "none";
employeeJob.style.display = "none";
employeePartTimeJob.style.display = "none";
waiterJob.style.display = "none";
waiterPartTimeJob.style.display = "none";
softwareJob.innerHTML = "Apply for Software Job";
softwareConsultantJob.innerHTML = "Apply for a Software Consultant job";
itJob.innerHTML = "Apply for IT Job";
securityEngineerJob.innerHTML = "Apply for Security Engineer Job";
networkEngineerJob.innerHTML = "Apply for Network Engineer Job";
businessJob.innerHTML = "Apply for Business Job";
businessConsultantJob.innerHTML = "Apply for a Business Consultant Job";
securityJob.innerHTML = "Apply for Security Job";
agentJob.innerHTML = "Apply for Agent Job";
employeeJob.innerHTML = "Apply to be an Employee";
employeePartTimeJob.innerHTML = "Apply to be a Part-time Employee";
waiterJob.innerHTML = "Apply to be a Waiter";
waiterPartTimeJob.innerHTML = "Apply to be a Part-time Waiter"
work.style.display = "none";
gymTrainStr.style.display = "none";
gymTrainDef.style.display = "none";
gymTrainDex.style.display = "none";
gymTrainAgi.style.display = "none";
studyComputerScience.style.display = "none";
classDataStructures.style.display = "none";
classNetworks.style.display = "none";
classAlgorithms.style.display = "none";
classManagement.style.display = "none";
classLeadership.style.display = "none";
purchase2gb.style.display = "none";
purchase4gb.style.display = "none";
purchase8gb.style.display = "none";
purchase16gb.style.display = "none";
purchase32gb.style.display = "none";
purchase64gb.style.display = "none";
purchase128gb.style.display = "none";
purchase256gb.style.display = "none";
purchase512gb.style.display = "none";
purchase1tb.style.display = "none";
purchaseTor.style.display = "none";
purchaseHomeRam.style.display = "none";
purchaseHomeCores.style.display = "none";
purchase2gb.innerHTML = "Purchase 2GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(2*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase4gb.innerHTML = "Purchase 4GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(4*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase8gb.innerHTML = "Purchase 8GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(8*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase16gb.innerHTML = "Purchase 16GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(16*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase32gb.innerHTML = "Purchase 32GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(32*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase64gb.innerHTML = "Purchase 64GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(64*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase128gb.innerHTML = "Purchase 128GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(128*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase256gb.innerHTML = "Purchase 256GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(256*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase512gb.innerHTML = "Purchase 512GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(512*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
purchase1tb.innerHTML = "Purchase 1TB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(1024*_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2);
if (!_SpecialServerIps__WEBPACK_IMPORTED_MODULE_16__[/* SpecialServerIps */ "a"].hasOwnProperty("Darkweb Server")) {
purchaseTor.classList.add("a-link-button");
purchaseTor.classList.remove("a-link-button-bought");
purchaseTor.innerHTML = "Purchase TOR Router - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost, 2);
} else {
purchaseTor.classList.remove("a-link-button");
purchaseTor.classList.add("a-link-button-bought");
purchaseTor.innerHTML = "TOR Router - Purchased";
}
travelAgencyText.style.display = "none";
travelToAevum.style.display = "none";
travelToChongqing.style.display = "none";
travelToSector12.style.display = "none";
travelToNewTokyo.style.display = "none";
travelToIshima.style.display = "none";
travelToVolhaven.style.display = "none";
infiltrate.style.display = "none";
hospitalTreatment.style.display = "none";
slumsDescText.style.display = "none";
slumsShoplift.style.display = "none";
slumsRobStore.style.display = "none";
slumsMug.style.display = "none";
slumsLarceny.style.display = "none";
slumsDealDrugs.style.display = "none";
slumsBondForgery.style.display = "none";
slumsTrafficArms.style.display = "none";
slumsHomicide.style.display = "none";
slumsGta.style.display = "none";
slumsKidnap.style.display = "none";
slumsAssassinate.style.display = "none";
slumsHeist.style.display = "none";
cityHallCreateCorporation.style.display = "none";
nsaBladeburner.style.display = "none";
//Check if the player is employed at this Location. If he is, display the "Work" button,
//update the job title, etc.
if (loc != "" && loc === _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].companyName) {
let company = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc];
jobTitle.style.display = "block";
jobReputation.style.display = "inline";
companyFavor.style.display = "inline";
locationTxtDiv1.style.display = "block";
locationTxtDiv2.style.display = "block";
locationTxtDiv3.style.display = "block";
jobTitle.innerHTML = "Job Title: " + _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].companyPosition;
let repGain = company.getFavorGain();
if (repGain.length != 2) {repGain = 0;}
repGain = repGain[0];
jobReputation.innerHTML = "Company reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(company.playerReputation, 4) +
"<span class='tooltiptext'>You will earn " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(repGain, 0) +
" faction favor upon resetting after installing an Augmentation</span>";
companyFavor.innerHTML = "Company Favor: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(company.favor, 0) +
"<span class='tooltiptext'>Company favor increases the rate at which " +
"you earn reputation for this company by 1% per favor. Company favor " +
"is gained whenever you reset after installing an Augmentation. The amount of " +
"favor you gain depends on how much reputation you have with the company</span>";
work.style.display = "block";
let currPos = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].companyPosition];
if (currPos == null) {
throw new Error("Player's companyPosition property has an invalid value");
}
work.addEventListener("click", function() {
if (currPos.isPartTimeJob() || currPos.isSoftwareConsultantJob() || currPos.isBusinessConsultantJob()) {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startWorkPartTime();
} else {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startWork();
}
return false;
});
//Change the text for the corresponding position from "Apply for X Job" to "Apply for promotion"
if (currPos.isSoftwareJob()) {
softwareJob.innerHTML = "Apply for a promotion (Software)";
} else if (currPos.isSoftwareConsultantJob()) {
softwareConsultantJob.innerHTML = "Apply for a promotion (Software Consultant)";
} else if (currPos.isITJob()) {
itJob.innerHTML = "Apply for a promotion (IT)";
} else if (currPos.isSecurityEngineerJob()) {
securityEngineerJob.innerHTML = "Apply for a promotion (Security Engineer)";
} else if (currPos.isNetworkEngineerJob()) {
networkEngineerJob.innerHTML = "Apply for a promotion (Network Engineer)";
} else if (currPos.isBusinessJob()) {
businessJob.innerHTML = "Apply for a promotion (Business)";
} else if (currPos.isBusinessConsultantJob()) {
businessConsultantJob.innerHTML = "Apply for a promotion (Business Consultant)";
} else if (currPos.isSecurityJob()) {
securityJob.innerHTML = "Apply for a promotion (Security)";
} else if (currPos.isAgentJob()) {
agentJob.innerHTML = "Apply for a promotion (Agent)";
}
} else {
jobTitle.style.display = "none";
jobReputation.style.display = "none";
companyFavor.style.display = "none";
locationTxtDiv1.style.display = "none";
locationTxtDiv2.style.display = "none";
locationTxtDiv3.style.display = "none";
}
//Calculate hospital Cost
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp < 0) {_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp = 0;}
var hospitalTreatmentCost = (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].max_hp - _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp) * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].HospitalCostPerHp;
//Set tooltip for job requirements
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["SoftwareCompanyPositions"][0]], softwareJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["SoftwareConsultantCompanyPositions"][0]], softwareConsultantJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["ITCompanyPositions"][0]], itJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["SecurityEngineerCompanyPositions"][0]], securityEngineerJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["NetworkEngineerCompanyPositions"][0]], networkEngineerJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["BusinessCompanyPositions"][0]], businessJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["BusinessConsultantCompanyPositions"][0]], businessConsultantJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["SecurityCompanyPositions"][0]], securityJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["AgentCompanyPositions"][0]], agentJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["MiscCompanyPositions"][1]], employeeJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["PartTimeCompanyPositions"][1]], employeePartTimeJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["MiscCompanyPositions"][0]], waiterJob);
setJobRequirementTooltip(loc, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"][_Company_data_CompanyPositionNames__WEBPACK_IMPORTED_MODULE_4__["PartTimeCompanyPositions"][0]], waiterPartTimeJob);
switch (loc) {
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumTravelAgency:
travelAgencyText.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSummitUniversity:
var costMult = 4, expMult = 3;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumECorp:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumECorp,
4800, 116, 150, 6);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumBachmanAndAssociates:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumBachmanAndAssociates,
1350, 42, 60, 4.1);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumClarkeIncorporated:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumClarkeIncorporated,
1800, 34, 75, 3.6);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumFulcrumTechnologies:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumFulcrumTechnologies,
4140, 96, 100, 6.2);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumAeroCorp:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumAeroCorp,
1350, 32, 50, 4.4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumGalacticCybersystems:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumGalacticCybersystems,
1260, 30, 50, 3.95);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumWatchdogSecurity:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumWatchdogSecurity,
690, 20, 30, 3);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumRhoConstruction:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumRhoConstruction,
485, 16, 20, 1.9);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumPolice:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumPolice,
565, 18, 25, 2.2);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumNetLinkTechnologies:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
purchase2gb.style.display = "block";
purchase4gb.style.display = "block";
purchase8gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumNetLinkTechnologies,
144, 10, 25, 1.4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumCrushFitnessGym:
var costMult = 3, expMult = 2;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSnapFitnessGym:
var costMult = 10, expMult = 5;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingKuaiGongInternational:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingKuaiGongInternational,
4450, 100, 100, 6.1);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSolarisSpaceSystems:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSolarisSpaceSystems,
2915, 52, 75, 6);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12TravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12RothmanUniversity:
var costMult = 3, expMult = 2;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12MegaCorp:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12MegaCorp,
4500, 114, 125, 6.75);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12BladeIndustries:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12BladeIndustries,
2160, 46, 100, 4.2);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FourSigma:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FourSigma,
1350, 58, 100, 7);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IcarusMicrosystems:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IcarusMicrosystems,
730, 32, 70, 5.4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12UniversalEnergy:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12UniversalEnergy,
700, 24, 50, 4.3);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12DeltaOne:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12DeltaOne,
970, 38, 75, 4.5);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA,
1170, 44, 80, 4.6);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bitNodeN === 6 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_10__[/* hasBladeburnerSF */ "c"] === true) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bitNodeN === 8) {break;}
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_0__[/* Bladeburner */ "a"]) {
//Note: Can't infiltrate NSA when part of bladeburner
nsaBladeburner.innerText = "Enter Bladeburner Headquarters";
} else {
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA,
1135, 40, 80, 5);
nsaBladeburner.innerText = "Apply to Bladeburner Division";
}
nsaBladeburner.style.display = "block";
} else {
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA,
1135, 40, 80, 5);
}
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12AlphaEnterprises:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
businessJob.style.display = "block";
purchase2gb.style.display = "block";
purchase4gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12AlphaEnterprises,
200, 14, 40, 2.25);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CarmichaelSecurity:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CarmichaelSecurity,
405, 18, 60, 2.5);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FoodNStuff:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
employeeJob.style.display = "block";
employeePartTimeJob.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12JoesGuns:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
employeeJob.style.display = "block";
employeePartTimeJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12JoesGuns,
120, 8, 20, 1.8);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IronGym:
var costMult = 1, expMult = 1;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12PowerhouseGym:
var costMult = 20, expMult = 10;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CityHall:
cityHallCreateCorporation.style.display = "block";
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__[/* Corporation */ "a"]) {
cityHallCreateCorporation.className = "a-link-button-inactive";
} else {
cityHallCreateCorporation.className = "a-link-button";
}
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoDefComm:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoDefComm,
1050, 28, 70, 4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoVitaLife:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoVitaLife,
605, 22, 100, 3.5);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoGlobalPharmaceuticals:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoGlobalPharmaceuticals,
700, 24, 80, 3.8);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoNoodleBar:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
waiterJob.style.display = "block";
waiterPartTimeJob.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaStormTechnologies:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "none";
agentJob.style.display = "none";
employeeJob.style.display = "none";
waiterJob.style.display = "none";
purchase32gb.style.display = "block";
purchase64gb.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaStormTechnologies,
570, 24, 100, 4.1);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaNovaMedical:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaNovaMedical,
485, 20, 50, 3.2);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaOmegaSoftware:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
businessJob.style.display = "block";
purchase4gb.style.display = "block";
purchase8gb.style.display = "block";
purchase16gb.style.display = "block";
purchase32gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaOmegaSoftware,
130, 10, 40, 1.6);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenZBInstituteOfTechnology:
var costMult = 5, expMult = 4;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniTekIncorporated:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniTekIncorporated,
1215, 44, 100, 4.4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenNWO:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenNWO,
1460, 56, 200, 6.8);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenHeliosLabs:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenHeliosLabs,
1080, 28, 75, 3);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniaCybersystems:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniaCybersystems,
725, 28, 90, 4.9);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenLexoCorp:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenLexoCorp,
340, 14, 60, 2);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSysCoreSecurities:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSysCoreSecurities,
430, 18, 75, 2.4);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenCompuTek:
locationInfo.innerHTML = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
purchase8gb.style.display = "block";
purchase16gb.style.display = "block";
purchase32gb.style.display = "block";
purchase64gb.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
purchaseHomeCores.style.display = "block";
setInfiltrateButton(infiltrate, _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenCompuTek,
195, 12, 60, 2.1);
break;
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenMilleniumFitnessGym:
var costMult = 7, expMult = 4;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
//All Slums
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSlums:
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSlums:
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12Slums:
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoSlums:
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaSlums:
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSlums:
var shopliftChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Shoplift.successRate();
var robStoreChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].RobStore.successRate();
var mugChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Mug.successRate();
var larcenyChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Larceny.successRate();
var drugsChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].DealDrugs.successRate();
var bondChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].BondForgery.successRate();
var armsChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].TraffickArms.successRate();
var homicideChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Homicide.successRate();
var gtaChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].GrandTheftAuto.successRate();
var kidnapChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Kidnap.successRate();
var assassinateChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Assassination.successRate();
var heistChance = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Heist.successRate();
slumsDescText.style.display = "block";
slumsShoplift.style.display = "block";
slumsShoplift.innerHTML = "Shoplift (" + (shopliftChance*100).toFixed(3) + "% chance of success)";
slumsShoplift.innerHTML += '<span class="tooltiptext"> Attempt to shoplift from a low-end retailer </span>';
slumsRobStore.style.display = "block";
slumsRobStore.innerHTML = "Rob store(" + (robStoreChance*100).toFixed(3) + "% chance of success)";
slumsRobStore.innerHTML += '<span class="tooltiptext">Attempt to commit armed robbery on a high-end store </span>';
slumsMug.style.display = "block";
slumsMug.innerHTML = "Mug someone (" + (mugChance*100).toFixed(3) + "% chance of success)";
slumsMug.innerHTML += '<span class="tooltiptext"> Attempt to mug a random person on the street </span>';
slumsLarceny.style.display = "block";
slumsLarceny.innerHTML = "Larceny (" + (larcenyChance*100).toFixed(3) + "% chance of success)";
slumsLarceny.innerHTML +="<span class='tooltiptext'> Attempt to rob property from someone's house </span>";
slumsDealDrugs.style.display = "block";
slumsDealDrugs.innerHTML = "Deal Drugs (" + (drugsChance*100).toFixed(3) + "% chance of success)";
slumsDealDrugs.innerHTML += '<span class="tooltiptext"> Attempt to deal drugs </span>';
slumsBondForgery.style.display = "block";
slumsBondForgery.innerHTML = "Bond Forgery (" + (bondChance*100).toFixed(3) + "% chance of success)";
slumsBondForgery.innerHTML += "<span class='tooltiptext'> Attempt to forge corporate bonds</span>";
slumsTrafficArms.style.display = "block";
slumsTrafficArms.innerHTML = "Traffick Illegal Arms (" + (armsChance*100).toFixed(3) + "% chance of success)";
slumsTrafficArms.innerHTML += '<span class="tooltiptext"> Attempt to smuggle illegal arms into the city and sell them to gangs and criminal organizations </span>';
slumsHomicide.style.display = "block";
slumsHomicide.innerHTML = "Homicide (" + (homicideChance*100).toFixed(3) + "% chance of success)";
slumsHomicide.innerHTML += '<span class="tooltiptext"> Attempt to murder a random person on the street</span>';
slumsGta.style.display = "block";
slumsGta.innerHTML = "Grand Theft Auto (" + (gtaChance*100).toFixed(3) + "% chance of success)";
slumsGta.innerHTML += '<span class="tooltiptext"> Attempt to commit grand theft auto </span>';
slumsKidnap.style.display = "block";
slumsKidnap.innerHTML = "Kidnap and Ransom (" + (kidnapChance*100).toFixed(3) + "% chance of success)";
slumsKidnap.innerHTML += '<span class="tooltiptext"> Attempt to kidnap and ransom a high-profile target </span>';
slumsAssassinate.style.display = "block";
slumsAssassinate.innerHTML = "Assassinate (" + (assassinateChance*100).toFixed(3) + "% chance of success)";
slumsAssassinate.innerHTML += '<span class="tooltiptext"> Attempt to assassinate a high-profile target </span>';
slumsHeist.style.display = "block";
slumsHeist.innerHTML = "Heist (" + (heistChance*100).toFixed(3) + "% chance of success)";
slumsHeist.innerHTML += '<span class="tooltiptext"> Attempt to pull off the ultimate heist </span>';
break;
//Hospital
case _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital:
hospitalTreatment.innerText = "Get treatment for wounds - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(hospitalTreatmentCost, 2).toString();
hospitalTreatment.style.display = "block";
break;
default:
console.log("ERROR: INVALID LOCATION");
}
// Make the "Apply to be Employee and Waiter" texts disappear if you already hold the job
// Includes part-time stuff
if (loc == _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].companyName) {
var currPos = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].companyPosition;
if (currPos == "Employee") {
employeeJob.style.display = "none";
} else if (currPos == "Waiter") {
waiterJob.style.display = "none";
} else if (currPos == "Part-time Employee") {
employeePartTimeJob.style.display = "none";
} else if (currPos == "Part-time Waiter") {
waiterPartTimeJob.style.display = "none";
}
}
}
function initLocationButtons() {
//Buttons to travel to different locations in World
let aevumTravelAgency = document.getElementById("aevum-travelagency");
aevumTravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumTravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumHospital = document.getElementById("aevum-hospital");
aevumHospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumSummitUniversity = document.getElementById("aevum-summituniversity");
aevumSummitUniversity.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSummitUniversity;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumECorp = document.getElementById("aevum-ecorp");
aevumECorp.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumECorp;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumBachmanAndAssociates = document.getElementById("aevum-bachmanandassociates");
aevumBachmanAndAssociates.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumBachmanAndAssociates;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumClarkeIncorporated = document.getElementById("aevum-clarkeincorporated");
aevumClarkeIncorporated.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumClarkeIncorporated;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumFulcrumTechnologies = document.getElementById("aevum-fulcrumtechnologies");
aevumFulcrumTechnologies.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumFulcrumTechnologies;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumAeroCorp = document.getElementById("aevum-aerocorp");
aevumAeroCorp.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumAeroCorp;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumGalacticCybersystems = document.getElementById("aevum-galacticcybersystems");
aevumGalacticCybersystems.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumGalacticCybersystems;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumWatchdogSecurity = document.getElementById("aevum-watchdogsecurity");
aevumWatchdogSecurity.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumWatchdogSecurity;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumRhoConstruction = document.getElementById("aevum-rhoconstruction");
aevumRhoConstruction.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumRhoConstruction;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumPolice = document.getElementById("aevum-aevumpolice");
aevumPolice.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumPolice;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumNetLinkTechnologies = document.getElementById("aevum-netlinktechnologies");
aevumNetLinkTechnologies.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumNetLinkTechnologies;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumCrushFitnessGym = document.getElementById("aevum-crushfitnessgym");
aevumCrushFitnessGym.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumCrushFitnessGym;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumSnapFitnessGym = document.getElementById("aevum-snapfitnessgym");
aevumSnapFitnessGym.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSnapFitnessGym;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let aevumSlums = document.getElementById("aevum-slums");
aevumSlums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSlums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let chongqingTravelAgency = document.getElementById("chongqing-travelagency");
chongqingTravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingTravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let chongqingHospital = document.getElementById("chongqing-hospital");
chongqingHospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let chongqingKuaiGongInternational = document.getElementById("chongqing-kuaigonginternational");
chongqingKuaiGongInternational.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingKuaiGongInternational;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let chongqingSolarisSpaceSystems = document.getElementById("chongqing-solarisspacesystems");
chongqingSolarisSpaceSystems.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSolarisSpaceSystems;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let chongqingSlums = document.getElementById("chongqing-slums");
chongqingSlums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSlums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12TravelAgency = document.getElementById("sector12-travelagency");
sector12TravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12TravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12Hospital = document.getElementById("sector12-hospital");
sector12Hospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12RothmanUniversity = document.getElementById("sector12-rothmanuniversity");
sector12RothmanUniversity.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12RothmanUniversity;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12MegaCorp = document.getElementById("sector12-megacorp");
sector12MegaCorp.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12MegaCorp;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12BladeIndustries = document.getElementById("sector12-bladeindustries");
sector12BladeIndustries.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12BladeIndustries;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12FourSigma = document.getElementById("sector12-foursigma");
sector12FourSigma.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FourSigma;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12IcarusMicrosystems = document.getElementById("sector12-icarusmicrosystems");
sector12IcarusMicrosystems.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IcarusMicrosystems;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12UniversalEnergy = document.getElementById("sector12-universalenergy");
sector12UniversalEnergy.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12UniversalEnergy;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12DeltaOne = document.getElementById("sector12-deltaone");
sector12DeltaOne.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12DeltaOne;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12CIA = document.getElementById("sector12-cia");
sector12CIA.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12NSA = document.getElementById("sector12-nsa");
sector12NSA.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12AlphaEnterprises = document.getElementById("sector12-alphaenterprises");
sector12AlphaEnterprises.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12AlphaEnterprises;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12CarmichaelSecurity = document.getElementById("sector12-carmichaelsecurity");
sector12CarmichaelSecurity.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CarmichaelSecurity;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12FoodNStuff = document.getElementById("sector12-foodnstuff");
sector12FoodNStuff.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FoodNStuff;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12JoesGuns = document.getElementById("sector12-joesguns");
sector12JoesGuns.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12JoesGuns;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12IronGym = document.getElementById("sector12-irongym");
sector12IronGym.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IronGym;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12PowerhouseGym = document.getElementById("sector12-powerhousegym");
sector12PowerhouseGym.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12PowerhouseGym;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12Slums = document.getElementById("sector12-slums");
sector12Slums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12Slums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let sector12CityHall = document.getElementById("sector12-cityhall");
sector12CityHall.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CityHall;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoTravelAgency = document.getElementById("newtokyo-travelagency");
newTokyoTravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoTravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoHospital = document.getElementById("newtokyo-hospital");
newTokyoHospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoDefComm = document.getElementById("newtokyo-defcomm");
newTokyoDefComm.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoDefComm;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoVitaLife = document.getElementById("newtokyo-vitalife");
newTokyoVitaLife.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoVitaLife;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoGlobalPharmaceuticals = document.getElementById("newtokyo-globalpharmaceuticals");
newTokyoGlobalPharmaceuticals.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoGlobalPharmaceuticals;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoNoodleBar = document.getElementById("newtokyo-noodlebar");
newTokyoNoodleBar.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoNoodleBar;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let newTokyoSlums = document.getElementById("newtokyo-slums");
newTokyoSlums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoSlums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaTravelAgency = document.getElementById("ishima-travelagency");
ishimaTravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaTravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaHospital = document.getElementById("ishima-hospital");
ishimaHospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaStormTechnologies = document.getElementById("ishima-stormtechnologies");
ishimaStormTechnologies.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaStormTechnologies;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaNovaMedical = document.getElementById("ishima-novamedical");
ishimaNovaMedical.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaNovaMedical;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaOmegaSoftware = document.getElementById("ishima-omegasoftware");
ishimaOmegaSoftware.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaOmegaSoftware;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let ishimaSlums = document.getElementById("ishima-slums");
ishimaSlums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaSlums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenTravelAgency = document.getElementById("volhaven-travelagency");
volhavenTravelAgency.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenTravelAgency;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenHospital = document.getElementById("volhaven-hospital");
volhavenHospital.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Hospital;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenZBInstituteOfTechnology = document.getElementById("volhaven-zbinstituteoftechnology");
volhavenZBInstituteOfTechnology.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenZBInstituteOfTechnology;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenOmniTekIncorporated = document.getElementById("volhaven-omnitekincorporated");
volhavenOmniTekIncorporated.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniTekIncorporated;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenNWO = document.getElementById("volhaven-nwo");
volhavenNWO.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenNWO;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenHeliosLabs = document.getElementById("volhaven-helioslabs");
volhavenHeliosLabs.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenHeliosLabs;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenOmniaCybersystems = document.getElementById("volhaven-omniacybersystems");
volhavenOmniaCybersystems.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniaCybersystems;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenLexoCorp = document.getElementById("volhaven-lexocorp");
volhavenLexoCorp.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenLexoCorp;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenSysCoreSecurities = document.getElementById("volhaven-syscoresecurities");
volhavenSysCoreSecurities.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSysCoreSecurities;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenCompuTek = document.getElementById("volhaven-computek");
volhavenCompuTek.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenCompuTek;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenMilleniumFitnessGym = document.getElementById("volhaven-milleniumfitnessgym");
volhavenMilleniumFitnessGym.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenMilleniumFitnessGym;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
let volhavenSlums = document.getElementById("volhaven-slums");
volhavenSlums.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSlums;
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent();
return false;
});
//Buttons to interact at a location (apply for job/promotion, train, purchase, etc.)
var softwareJob = document.getElementById("location-software-job");
var softwareConsultantJob = document.getElementById("location-software-consultant-job")
var itJob = document.getElementById("location-it-job");
var securityEngineerJob = document.getElementById("location-security-engineer-job");
var networkEngineerJob = document.getElementById("location-network-engineer-job");
var businessJob = document.getElementById("location-business-job");
var businessConsultantJob = document.getElementById("location-business-consultant-job");
var securityJob = document.getElementById("location-security-job");
var agentJob = document.getElementById("location-agent-job");
var employeeJob = document.getElementById("location-employee-job");
var employeePartTimeJob = document.getElementById("location-parttime-employee-job");
var waiterJob = document.getElementById("location-waiter-job");
var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job");
var work = document.getElementById("location-work");
var purchase2gb = document.getElementById("location-purchase-2gb");
var purchase4gb = document.getElementById("location-purchase-4gb");
var purchase8gb = document.getElementById("location-purchase-8gb");
var purchase16gb = document.getElementById("location-purchase-16gb");
var purchase32gb = document.getElementById("location-purchase-32gb");
var purchase64gb = document.getElementById("location-purchase-64gb");
var purchase128gb = document.getElementById("location-purchase-128gb");
var purchase256gb = document.getElementById("location-purchase-256gb");
var purchase512gb = document.getElementById("location-purchase-512gb");
var purchase1tb = document.getElementById("location-purchase-1tb");
var purchaseTor = document.getElementById("location-purchase-tor");
var purchaseHomeRam = document.getElementById("location-purchase-home-ram");
var purchaseHomeCores = document.getElementById("location-purchase-home-cores");
var travelToAevum = document.getElementById("location-travel-to-aevum");
var travelToChongqing = document.getElementById("location-travel-to-chongqing");
var travelToSector12 = document.getElementById("location-travel-to-sector12");
var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo");
var travelToIshima = document.getElementById("location-travel-to-ishima");
var travelToVolhaven = document.getElementById("location-travel-to-volhaven");
var slumsShoplift = document.getElementById("location-slums-shoplift");
var slumsRobStore = document.getElementById("location-slums-rob-store");
var slumsMug = document.getElementById("location-slums-mug");
var slumsLarceny = document.getElementById("location-slums-larceny");
var slumsDealDrugs = document.getElementById("location-slums-deal-drugs");
var slumsBondForgery = document.getElementById("location-slums-bond-forgery");
var slumsTrafficArms = document.getElementById("location-slums-traffic-arms");
var slumsHomicide = document.getElementById("location-slums-homicide");
var slumsGta = document.getElementById("location-slums-gta");
var slumsKidnap = document.getElementById("location-slums-kidnap");
var slumsAssassinate = document.getElementById("location-slums-assassinate");
var slumsHeist = document.getElementById("location-slums-heist");
var cityHallCreateCorporation = document.getElementById("location-cityhall-create-corporation");
var nsaBladeburner = document.getElementById("location-nsa-bladeburner");
var hospitalTreatment = document.getElementById("location-hospital-treatment");
softwareJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForSoftwareJob();
return false;
});
softwareConsultantJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForSoftwareConsultantJob();
return false;
});
itJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForItJob();
return false;
});
securityEngineerJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForSecurityEngineerJob();
return false;
});
networkEngineerJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForNetworkEngineerJob();
return false;
});
businessJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForBusinessJob();
return false;
});
businessConsultantJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForBusinessConsultantJob();
return false;
});
securityJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForSecurityJob();
return false;
});
agentJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForAgentJob();
return false;
});
employeeJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForEmployeeJob();
return false;
});
employeePartTimeJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForPartTimeEmployeeJob();
return false;
});
waiterJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForWaiterJob();
return false;
});
waiterPartTimeJob.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].applyForPartTimeWaiterJob();
return false;
});
purchase2gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(2, 2 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase4gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(4, 4 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase8gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(8, 8 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase16gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(16, 16 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase32gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(32, 32 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase64gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(64, 64 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase128gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(128, 128 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase256gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(256, 256 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase512gb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(512, 512 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchase1tb.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseServerBoxCreate(1024, 1024 * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer);
return false;
});
purchaseTor.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
purchaseTorRouter();
return false;
});
purchaseHomeRam.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
const cost = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getUpgradeHomeRamCost();
const ram = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().maxRam;
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Purchase"; noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", ()=>{
Object(_ServerPurchases__WEBPACK_IMPORTED_MODULE_14__[/* purchaseRamForHomeComputer */ "a"])(cost);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxCreate */ "b"])("Would you like to purchase additional RAM for your home computer? <br><br>" +
"This will upgrade your RAM from " + ram + "GB to " + ram*2 + "GB. <br><br>" +
"This will cost " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__[/* numeralWrapper */ "a"].format(cost, '$0.000a'));
});
purchaseHomeCores.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var currentCores = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().cpuCores;
if (currentCores >= 8) {return;} //Max of 8 cores
//Cost of purchasing another cost is found by indexing this array with number of current cores
var cost = [0,
10000000000, //1->2 Cores - 10 bn
250000000000, //2->3 Cores - 250 bn
5000000000000, //3->4 Cores - 5 trillion
100000000000000, //4->5 Cores - 100 trillion
1000000000000000, //5->6 Cores - 1 quadrillion
20000000000000000, //6->7 Cores - 20 quadrillion
200000000000000000]; //7->8 Cores - 200 quadrillion
cost = cost[currentCores];
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Purchase"; noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", ()=>{
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].money.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You do not have enough money to purchase an additional CPU Core for your home computer!");
} else {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().cpuCores++;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You purchased an additional CPU Core for your home computer! It now has " +
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().cpuCores + " cores.");
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxCreate */ "b"])("Would you like to purchase an additional CPU Core for your home computer? Each CPU Core " +
"lets you start with an additional Core Node in Hacking Missions.<br><br>" +
"Purchasing an additional core (for a total of " + (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().cpuCores + 1) + ") will " +
"cost " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__[/* numeralWrapper */ "a"].format(cost, '$0.000a'));
});
travelToAevum.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
travelToChongqing.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
travelToSector12.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
travelToNewTokyo.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
travelToIshima.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
travelToVolhaven.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
travelBoxCreate(_Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
return false;
});
slumsShoplift.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Shoplift.commit();
return false;
});
slumsRobStore.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].RobStore.commit();
return false;
});
slumsMug.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Mug.commit();
return false;
});
slumsLarceny.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Larceny.commit();
return false;
});
slumsDealDrugs.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].DealDrugs.commit();
return false;
});
slumsBondForgery.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].BondForgery.commit();
return false;
});
slumsTrafficArms.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].TraffickArms.commit();
return false;
});
slumsHomicide.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Homicide.commit();
return false;
});
slumsGta.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].GrandTheftAuto.commit();
return false;
});
slumsKidnap.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Kidnap.commit();
return false;
});
slumsAssassinate.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Assassination.commit();
return false;
});
slumsHeist.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"].Heist.commit();
return false;
});
cityHallCreateCorporation.addEventListener("click", function() {
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxGetYesButton */ "j"])(),
noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerText = "Create Corporation";
noBtn.innerText = "Cancel";
yesBtn.addEventListener("click", function() {
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].money.lt(150e9)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You don't have enough money to create a corporation! You need $150b");
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxClose */ "f"])();
}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].loseMoney(150e9);
var companyName = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxGetInput */ "h"])();
if (companyName == null || companyName == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Invalid company name!");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].corporation = new _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__[/* Corporation */ "a"]({
name:companyName,
});
displayLocationContent();
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Congratulations! You just started your own corporation. You can visit " +
"and manage your company in the City");
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxClose */ "f"])();
});
noBtn.addEventListener("click", function() {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxClose */ "f"])();
});
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__[/* Corporation */ "a"]) {
return;
} else {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxCreate */ "g"])("Would you like to start a corporation? This will require $150b " +
"for registration and initial funding.<br><br>If so, please enter " +
"a name for your corporation below:");
}
});
nsaBladeburner.addEventListener("click", function() {
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bladeburner && _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_0__[/* Bladeburner */ "a"]) {
//Enter Bladeburner division
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadBladeburnerContent();
} else {
//Apply for Bladeburner division
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].defense >= 100 &&
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].agility >= 100) {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].bladeburner = new _Bladeburner__WEBPACK_IMPORTED_MODULE_0__[/* Bladeburner */ "a"]({new:true});
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You have been accepted into the Bladeburner division!");
displayLocationContent();
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("Rejected! Please apply again when you have 100 of each combat stat (str, def, dex, agi)");
}
}
});
hospitalTreatment.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp < 0) {_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp = 0;}
var price = (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].max_hp - _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp) * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].HospitalCostPerHp;
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].loseMoney(price);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You were healed to full health! The hospital billed " +
"you for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(price, 2).toString());
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].hp = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].max_hp;
displayLocationContent();
return false;
});
}
function travelToCity(destCityName, cost) {
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].firstTimeTraveled === false) {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].firstTimeTraveled = true;
document.getElementById("travel-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].money.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You cannot afford to travel to " + destCityName);
return;
}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].city = destCityName;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You are now in " + destCityName + "!");
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorldContent();
}
function purchaseTorRouter() {
if (_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You cannot afford to purchase the Tor router");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost);
var darkweb = new _Server__WEBPACK_IMPORTED_MODULE_13__[/* Server */ "d"]({
ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_20__[/* createRandomIp */ "a"])(), hostname:"darkweb", organizationName:"",
isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1
});
Object(_Server__WEBPACK_IMPORTED_MODULE_13__[/* AddToAllServers */ "a"])(darkweb);
_SpecialServerIps__WEBPACK_IMPORTED_MODULE_16__[/* SpecialServerIps */ "a"].addIp("Darkweb Server", darkweb.ip);
const purchaseTor = document.getElementById("location-purchase-tor");
purchaseTor.setAttribute("class", "a-link-button-bought");
purchaseTor.innerHTML = "TOR Router - Purchased";
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getHomeComputer().ip);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You have purchased a Tor router!<br>You now have access to the dark web from your home computer<br>Use the scan/scan-analyze commands to search for the dark web connection.");
}
function displayUniversityLocationContent(costMult) {
var studyComputerScienceButton = document.getElementById("location-study-computer-science");
var classDataStructuresButton = document.getElementById("location-data-structures-class");
var classNetworksButton = document.getElementById("location-networks-class");
var classAlgorithmsButton = document.getElementById("location-algorithms-class");
var classManagementButton = document.getElementById("location-management-class");
var classLeadershipButton = document.getElementById("location-leadership-class");
studyComputerScienceButton.style.display = "block";
classDataStructuresButton.style.display = "block";
classNetworksButton.style.display = "block";
classAlgorithmsButton.style.display = "block";
classManagementButton.style.display = "block";
classLeadershipButton.style.display = "block";
//Costs (per second)
var dataStructuresCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassDataStructuresBaseCost * costMult;
var networksCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassNetworksBaseCost * costMult;
var algorithmsCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassAlgorithmsBaseCost * costMult;
var managementCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassManagementBaseCost * costMult;
var leadershipCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassLeadershipBaseCost * costMult;
//Update button text to show cost
classDataStructuresButton.innerHTML = "Take Data Structures course ($" + dataStructuresCost + " / sec)";
classNetworksButton.innerHTML = "Take Networks course ($" + networksCost + " / sec)";
classAlgorithmsButton.innerHTML = "Take Algorithms course ($" + algorithmsCost + " / sec)";
classManagementButton.innerHTML = "Take Management course ($" + managementCost + " / sec)";
classLeadershipButton.innerHTML = "Take Leadership course ($" + leadershipCost + " / sec)";
}
function setUniversityLocationButtons(costMult, expMult) {
var newStudyCS = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-study-computer-science");
newStudyCS.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassStudyComputerScience);
return false;
});
var newClassDataStructures = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-data-structures-class");
newClassDataStructures.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassDataStructures);
return false;
});
var newClassNetworks = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-networks-class");
newClassNetworks.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassNetworks);
return false;
});
var newClassAlgorithms = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-algorithms-class");
newClassAlgorithms.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassAlgorithms);
return false;
});
var newClassManagement = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-management-class");
newClassManagement.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassManagement);
return false;
});
var newClassLeadership = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-leadership-class");
newClassLeadership.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassLeadership);
return false;
});
}
function displayGymLocationContent(costMult) {
var gymStrButton = document.getElementById("location-gym-train-str");
var gymDefButton = document.getElementById("location-gym-train-def");
var gymDexButton = document.getElementById("location-gym-train-dex");
var gymAgiButton = document.getElementById("location-gym-train-agi");
gymStrButton.style.display = "block";
gymDefButton.style.display = "block";
gymDexButton.style.display = "block";
gymAgiButton.style.display = "block";
//Costs (per second)
var cost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymBaseCost * costMult;
//Update button text to show cost
gymStrButton.innerHTML = "Train Strength ($" + cost + " / sec)";
gymDefButton.innerHTML = "Train Defense ($" + cost + " / sec)";
gymDexButton.innerHTML = "Train Dexterity ($" + cost + " / sec)";
gymAgiButton.innerHTML = "Train Agility ($" + cost + " / sec)";
}
function setGymLocationButtons(costMult, expMult) {
var gymStr = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-gym-train-str");
gymStr.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymStrength);
return false;
});
var gymDef = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-gym-train-def");
gymDef.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDefense);
return false;
});
var gymDex = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-gym-train-dex");
gymDex.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDexterity);
return false;
});
var gymAgi = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__["clearEventListeners"])("location-gym-train-agi");
gymAgi.addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymAgility);
return false;
});
}
function setInfiltrateButton(btn, companyName, startLevel, val, maxClearance, difficulty) {
btn.style.display = "block";
btn.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadInfiltrationContent();
Object(_Infiltration__WEBPACK_IMPORTED_MODULE_9__[/* beginInfiltration */ "a"])(companyName, startLevel, val, maxClearance, difficulty)
return false;
});
}
//Finds the next target job for the player at the given company (loc) and
//adds the tooltiptext to the Application button, given by 'button'
function setJobRequirementTooltip(loc, entryPosType, btn) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_2__["Companies"][loc];
if (company == null) {return;}
var pos = _Player__WEBPACK_IMPORTED_MODULE_12__[/* Player */ "a"].getNextCompanyPosition(company, entryPosType);
if (pos == null) { return };
if (!company.hasPosition(pos)) { return; }
var reqText = Object(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_3__["getJobRequirementText"])(company, pos, true);
btn.innerHTML += "<span class='tooltiptext'>" + reqText + "</span>";
}
function travelBoxCreate(destCityName, cost) {
if(_Settings__WEBPACK_IMPORTED_MODULE_15__["Settings"].SuppressTravelConfirmation) {
travelToCity(destCityName, cost);
return;
}
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxGetNoButton */ "c"])();
yesBtn.innerHTML = "Yes";
noBtn.innerHTML = "No";
noBtn.addEventListener("click", () => {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
return false;
});
yesBtn.addEventListener("click", () => {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxClose */ "a"])();
travelToCity(destCityName, cost);
return false;
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoBoxCreate */ "b"])("Would you like to travel to " + destCityName + "? The trip will cost $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(cost, 2) + ".");
}
function purchaseServerBoxCreate(ram, cost) {
var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxGetYesButton */ "j"])();
var noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxGetNoButton */ "i"])();
yesBtn.innerHTML = "Purchase Server";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
Object(_ServerPurchases__WEBPACK_IMPORTED_MODULE_14__[/* purchaseServer */ "b"])(ram, cost);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxClose */ "f"])();
});
noBtn.addEventListener("click", function() {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxClose */ "f"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_22__[/* yesNoTxtInpBoxCreate */ "g"])("Would you like to purchase a new server with " + ram +
"GB of RAM for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(cost, 2) + "?<br><br>" +
"Please enter the server hostname below:<br>");
}
/***/ }),
/* 87 */
/*!****************************************!*\
!*** ./utils/helpers/compareArrays.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: compareArrays */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Does a shallow compare of two arrays to determine if they are equal.
* @param a1 The first array
* @param a2 The second array
*/
function compareArrays(a1, a2) {
if (a1.length !== a2.length) {
return false;
}
for (let i = 0; i < a1.length; ++i) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
exports.compareArrays = compareArrays;
/***/ }),
/* 88 */
/*!**********************************************!*\
!*** ./src/Company/GetJobRequirementText.ts ***!
\**********************************************/
/*! no static exports found */
/*! exports used: getJobRequirementText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns a string with the given CompanyPosition's stat requirements
*/
function getJobRequirementText(company, pos, tooltiptext = false) {
let reqText = "";
const offset = company.jobStatReqOffset;
const reqHacking = pos.requiredHacking > 0 ? pos.requiredHacking + offset : 0;
const reqStrength = pos.requiredStrength > 0 ? pos.requiredStrength + offset : 0;
const reqDefense = pos.requiredDefense > 0 ? pos.requiredDefense + offset : 0;
const reqDexterity = pos.requiredDexterity > 0 ? pos.requiredDexterity + offset : 0;
const reqAgility = pos.requiredDexterity > 0 ? pos.requiredDexterity + offset : 0;
const reqCharisma = pos.requiredCharisma > 0 ? pos.requiredCharisma + offset : 0;
const reqRep = pos.requiredReputation;
if (tooltiptext) {
reqText = "Requires:<br>";
reqText += (reqHacking.toString() + " hacking<br>");
reqText += (reqStrength.toString() + " strength<br>");
reqText += (reqDefense.toString() + " defense<br>");
reqText += (reqDexterity.toString() + " dexterity<br>");
reqText += (reqAgility.toString() + " agility<br>");
reqText += (reqCharisma.toString() + " charisma<br>");
reqText += (reqRep.toString() + " reputation");
}
else {
reqText = "(Requires ";
if (reqHacking > 0) {
reqText += (reqHacking + " hacking, ");
}
if (reqStrength > 0) {
reqText += (reqStrength + " strength, ");
}
if (reqDefense > 0) {
reqText += (reqDefense + " defense, ");
}
if (reqDexterity > 0) {
reqText += (reqDexterity + " dexterity, ");
}
if (reqAgility > 0) {
reqText += (reqAgility + " agility, ");
}
if (reqCharisma > 0) {
reqText += (reqCharisma + " charisma, ");
}
if (reqRep > 1) {
reqText += (reqRep + " reputation, ");
}
reqText = reqText.substring(0, reqText.length - 2);
reqText += ")";
}
return reqText;
}
exports.getJobRequirementText = getJobRequirementText;
/***/ }),
/* 89 */
/*!****************************************!*\
!*** ./utils/helpers/getRandomByte.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: getRandomByte */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getRandomInt_1 = __webpack_require__(/*! ./getRandomInt */ 14);
/**
* Gets a random value in the range of a byte (0 - 255), or up to the maximum.
* @param max The maximum value (up to 255).
*/
function getRandomByte(max) {
// Technically 2^8 is 256, but the values are 0-255, not 1-256.
const byteMaximum = 255;
const upper = Math.max(Math.min(max, byteMaximum), 0);
return getRandomInt_1.getRandomInt(0, upper);
}
exports.getRandomByte = getRandomByte;
/***/ }),
/* 90 */,
/* 91 */,
/* 92 */
/*!****************************************!*\
!*** ./src/CodingContractGenerator.js ***!
\****************************************/
/*! exports provided: generateRandomContract, generateContract */
/*! exports used: generateRandomContract */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return generateRandomContract; });
/* unused harmony export generateContract */
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CodingContracts */ 40);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__);
function generateRandomContract() {
// First select a random problem type
const problemTypes = Object.keys(_CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractTypes"]);
let randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, problemTypes.length - 1);
let problemType = problemTypes[randIndex];
// Then select a random reward type. 'Money' will always be the last reward type
const reward = getRandomReward();
// Choose random server
const randServer = getRandomServer();
let contractFn = getRandomFilename(randServer, reward);
let contract = new _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContract"](contractFn, problemType, reward);
randServer.addContract(contract);
}
function generateContract(params) {
// Problem Type
let problemType;
const problemTypes = Object.keys(_CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractTypes"]);
if (params.problemType != null && problemTypes.includes(params.problemType)) {
problemType = params.problemType;
} else {
let randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, problemTypes.length - 1);
problemType = problemTypes[randIndex];
}
// Reward Type - This is always random for now
const reward = getRandomReward();
// Server
let server;
if (params.server != null) {
server = Object(_Server__WEBPACK_IMPORTED_MODULE_3__[/* GetServerByHostname */ "c"])(params.server);
if (server == null) {
server = _Server__WEBPACK_IMPORTED_MODULE_3__[/* AllServers */ "b"][param.server];
}
if (server == null) {
server = getRandomServer();
}
} else {
server = getRandomServer();
}
// Filename
let fn;
if (params.fn != null) {
fn = params.fn;
} else {
fn = getRandomFilename(server, reward);
}
let contract = new _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContract"](fn, problemType, reward);
server.addContract(contract);
}
// Ensures that a contract's reward type is valid
function sanitizeRewardType(rewardType) {
let type = rewardType; // Create copy
const factionsThatAllowHacking = _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].factions.filter((fac) => {
try {
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_1__["Factions"][fac].getInfo().offerHackingWork;
} catch (e) {
console.error(`Error when trying to filter Hacking Factions for Coding Contract Generation: ${e}`);
return false;
}
});
if (type === _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].FactionReputation && factionsThatAllowHacking.length === 0) {
type = _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].CompanyReputation;
}
if (type === _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].FactionReputationAll && factionsThatAllowHacking.length === 0) {
type = _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].CompanyReputation;
}
if (type === _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].CompanyReputation && _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].companyName === "") {
type = _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].Money;
}
return type;
}
function getRandomReward() {
let reward = {};
reward.type = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].Money);
reward.type = sanitizeRewardType(reward.type);
// Add additional information based on the reward type
const factionsThatAllowHacking = _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].factions.filter((fac) => {
try {
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_1__["Factions"][fac].getInfo().offerHackingWork;
} catch (e) {
console.error(`Error when trying to filter Hacking Factions for Coding Contract Generation: ${e}`);
return false;
}
});
switch (reward.type) {
case _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].FactionReputation:
// Get a random faction that player is a part of. That
// faction must allow hacking contracts
var numFactions = factionsThatAllowHacking.length;
var randFaction = factionsThatAllowHacking[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, numFactions - 1)];
reward.name = randFaction;
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].CompanyReputation:
if (_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].companyName !== "") {
reward.name = _Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].companyName;
} else {
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_0__["CodingContractRewardType"].Money;
}
break;
default:
break;
}
return reward;
}
function getRandomServer() {
const servers = Object.keys(_Server__WEBPACK_IMPORTED_MODULE_3__[/* AllServers */ "b"]);
let randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, servers.length - 1);
let randServer = _Server__WEBPACK_IMPORTED_MODULE_3__[/* AllServers */ "b"][servers[randIndex]];
// An infinite loop shouldn't ever happen, but to be safe we'll use
// a for loop with a limited number of tries
for (let i = 0; i < 200; ++i) {
if (randServer.purchasedByPlayer === false) { break; }
randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, servers.length - 1);
randServer = _Server__WEBPACK_IMPORTED_MODULE_3__[/* AllServers */ "b"][servers[randIndex]];
}
return randServer;
}
function getRandomFilename(server, reward) {
let contractFn = `contract-${Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, 1e6)}`;
for (let i = 0; i < 1000; ++i) {
if (server.contracts.filter((c) => {return c.fn === contractFn}).length <= 0) { break; }
contractFn = `contract-${Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_4__["getRandomInt"])(0, 1e6)}`;
}
if (reward.name) { contractFn += `-${reward.name.replace(/\s/g, "")}`; }
return contractFn;
}
/***/ }),
/* 93 */
/*!******************************!*\
!*** ./src/CinematicText.js ***!
\******************************/
/*! exports provided: cinematicTextFlag, writeCinematicText */
/*! exports used: cinematicTextFlag, writeCinematicText */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cinematicTextFlag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return writeCinematicText; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 27);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/isString */ 37);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_4__);
var cinematicTextFlag = false;
//Lines must be an array of strings
function writeCinematicText(lines) {
cinematicTextFlag = true;
if (lines.constructor !== Array) {
throw new Error("Invalid non-array argument passed into writeCinematicText()");
}
//We'll reuse the 'Red Pill' content
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCinematicTextContent();
var container = document.getElementById("cinematic-text-container");
container.style.width = "75%";
if (container == null) {throw new Error("Could not find cinematic-text-container for writeCinematicText()");}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_1__["removeChildrenFromElement"])(container);
for (var i = 0; i < lines.length; ++i) {
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_4__["isString"])(lines[i])) {
throw new Error("Invalid non-string element in 'lines' argument. writeCinematicText() failed");
}
}
return writeCinematicTextRecurse(lines).then(function() {
return cinematicTextEnd(); //Puts the continue button
}).catch(function(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_3__[/* exceptionAlert */ "a"])(e);
});
}
function writeCinematicTextRecurse(lines, lineNumber=0) {
if (lineNumber >= lines.length) {return Promise.resolve(true);}
return writeCinematicTextLine(lines[lineNumber]).then(function() {
return writeCinematicTextRecurse(lines, lineNumber+1);
});
}
function writeCinematicTextLine(line) {
return new Promise(function(resolve, reject) {
var container = document.getElementById("cinematic-text-container");
var pElem = document.createElement("p");
container.appendChild(pElem);
var promise = writeCinematicTextLetter(pElem, line, 0);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
});
}
function writeCinematicTextLetter(pElem, line, i=0) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (i >= line.length) {
var textToShow = line.substring(0, i);
pElem.innerHTML = textToShow;
return resolve(true);
}
var textToShow = line.substring(0, i);
pElem.innerHTML = textToShow + "<span class='typed-cursor'> &#9608; </span>";
var promise = writeCinematicTextLetter(pElem, line, i+1);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
}, 15);
});
}
function cinematicTextEnd() {
var container = document.getElementById("cinematic-text-container");
var mainMenu = document.getElementById("mainmenu-container");
container.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__["createElement"])("br"));
return new Promise (function(resolve, reject) {
container.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", {
class:"a-link-button", innerText:"Continue...",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_1__["removeChildrenFromElement"])(container);
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
mainMenu.style.visibility = "visible";
cinematicTextFlag = false;
resolve();
}
}));
});
}
/***/ }),
/* 94 */
/*!***********************************************!*\
!*** ./src/Company/GetNextCompanyPosition.ts ***!
\***********************************************/
/*! no static exports found */
/*! exports used: getNextCompanyPosition */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CompanyPositions_1 = __webpack_require__(/*! ./CompanyPositions */ 26);
function getNextCompanyPosition(currPos) {
if (currPos == null) {
return null;
}
const nextPosName = currPos.nextPosition;
if (nextPosName == null) {
return null;
}
return CompanyPositions_1.CompanyPositions[nextPosName];
}
exports.getNextCompanyPosition = getNextCompanyPosition;
/***/ }),
/* 95 */
/*!************************************!*\
!*** ./src/ui/createStatusText.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: createStatusText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 51);
const threeSeconds = 3000;
let x;
/**
* Displays a status message to the player for approximately 3 seconds.
* @param text The status text to display
*/
function createStatusText(text) {
if (x !== undefined) {
clearTimeout(x);
// Likely not needed due to clearTimeout, but just in case...
x = undefined;
}
const statusElement = getElementById_1.getElementById("status-text");
statusElement.classList.add("status-text");
statusElement.innerText = text;
const handler = () => {
statusElement.classList.remove("status-text");
statusElement.innerText = "";
};
x = setTimeout(handler, threeSeconds);
}
exports.createStatusText = createStatusText;
/***/ }),
/* 96 */
/*!*************************!*\
!*** ./src/HelpText.ts ***!
\*************************/
/*! no static exports found */
/*! exports used: HelpTexts, TerminalHelpText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* tslint:disable:max-line-length completed-docs variable-name*/
exports.TerminalHelpText = "Type 'help name' to learn more about the command 'name'<br><br>" +
'alias [-g] [name="value"] Create or display Terminal aliases<br>' +
"analyze Get information about the current machine <br>" +
"buy [-l/program] Purchase a program through the Dark Web<br>" +
"cat [file] Display a .msg, .lit, or .txt file<br>" +
"check [script] [args...] Print a script's logs to Terminal<br>" +
"clear Clear all text on the terminal <br>" +
"cls See 'clear' command <br>" +
"connect [ip/hostname] Connects to a remote server<br>" +
"download [script/text file] Downloads scripts or text files to your computer<br>" +
"expr [math expression] Evaluate a mathematical expression<br>" +
"free Check the machine's memory (RAM) usage<br>" +
"hack Hack the current machine<br>" +
"help [command] Display this help text, or the help text for a command<br>" +
"home Connect to home computer<br>" +
"hostname Displays the hostname of the machine<br>" +
"ifconfig Displays the IP address of the machine<br>" +
"kill [script] [args...] Stops the specified script on the current server <br>" +
"killall Stops all running scripts on the current machine<br>" +
"ls [| grep pattern] Displays all files on the machine<br>" +
"lscpu Displays the number of CPU cores on the machine<br>" +
"mem [script] [-t] [n] Displays the amount of RAM required to run the script<br>" +
"nano [file] Text editor - Open up and edit a script or text file<br>" +
"ps Display all scripts that are currently running<br>" +
"rm [file] Delete a file from the server<br>" +
"run [name] [-t] [n] [args...] Execute a program or script<br>" +
"scan Prints all immediately-available network connections<br>" +
"scan-analyze [d] [-a] Prints info for all servers up to <i>d</i> nodes away<br>" +
"scp [file] [server] Copies a file to a destination server<br>" +
"sudov Shows whether you have root access on this computer<br>" +
"tail [script] [args...] Displays dynamic logs for the specified script<br>" +
"theme [preset] | bg txt hlgt Change the color scheme of the UI<br>" +
"top Displays all running scripts and their RAM usage<br>" +
'unalias "[alias name]" Deletes the specified alias<br>' +
"wget [url] [target file] Retrieves code/text from a web server<br>";
exports.HelpTexts = {
alias: 'alias [-g] [name="value"] <br>' +
"Create or display aliases. An alias enables a replacement of a word with another string. " +
"It can be used to abbreviate a commonly used command, or commonly used parts of a command. The NAME " +
"of an alias defines the word that will be replaced, while the VALUE defines what it will be replaced by. For example, " +
"you could create the alias 'nuke' for the Terminal command 'run NUKE.exe' using the following: <br><br>" +
'alias nuke="run NUKE.exe"<br><br>' +
"Then, to run the NUKE.exe program you would just have to enter 'nuke' in Terminal rather than the full command. " +
"It is important to note that 'default' aliases will only be substituted for the first word of a Terminal command. For " +
"example, if the following alias was set: <br><br>" +
'alias worm="HTTPWorm.exe"<br><br>' +
"and then you tried to run the following terminal command: <br><br>" +
"run worm<br><br>" +
"This would fail because the worm alias is not the first word of a Terminal command. To allow an alias to be substituted " +
"anywhere in a Terminal command, rather than just the first word, you must set it to be a global alias using the -g flag: <br><br>" +
'alias -g worm="HTTPWorm.exe"<br><br>' +
"Now, the 'worm' alias will be substituted anytime it shows up as an individual word in a Terminal command. <br><br>" +
"Entering just the command 'alias' without any arguments prints the list of all defined aliases in the reusable form " +
"'alias NAME=VALUE' on the Terminal. <br><br>" +
"The 'unalias' command can be used to remove aliases.<br><br>",
analyze: "analze<br>" +
"Prints details and statistics about the current server. The information that is printed includes basic " +
"server details such as the hostname, whether the player has root access, what ports are opened/closed, and also " +
"hacking-related information such as an estimated chance to successfully hack, an estimate of how much money is " +
"available on the server, etc.",
buy: "buy [-l / program]<br>" +
"Purchase a program through the Dark Web. Requires a TOR router to use.<br><br>" +
"If this command is ran with the '-l' flag, it will display a list of all programs that can be bought through the " +
"dark web to the Terminal, as well as their costs.<br><br>" +
"Otherwise, the name of the program must be passed in as a parameter. This is name is NOT case-sensitive.",
cat: "cat [file]<br>" +
"Display message (.msg), literature (.lit), or text (.txt) files. Examples:<br><br>" +
"cat j1.msg<br>" +
"cat foo.lit<br>" +
"cat servers.txt",
check: "check [script name] [args...]<br>" +
"Print the logs of the script specified by the script name and arguments to the Terminal. Each argument must be separated by " +
"a space. Remember that a running script is uniquely " +
"identified both by its name and the arguments that are used to start it. So, if a script was ran with the following arguments: <br><br>" +
"run foo.script 1 2 foodnstuff<br><br>" +
"Then to run the 'check' command on this script you would have to pass the same arguments in: <br><br>" +
"check foo.script 1 2 foodnstuff",
clear: "clear<br>" +
"Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " +
"and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'cls' command",
cls: "cls<br>" +
"Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " +
"and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'clear' command",
connect: "connect [hostname/ip]<br>" +
"Connect to a remote server. The hostname or IP address of the remote server must be given as the argument " +
"to this command. Note that only servers that are immediately adjacent to the current server in the network can be connected to. To " +
"see which servers can be connected to, use the 'scan' command.",
download: "download [script/text file]<br>" +
"Downloads a script or text file to your computer (like your real life computer).<br>" +
"You can also download all of your scripts/text files as a zip file using the following Terminal commands:<br><br>" +
"Download all scripts and text files: download *<br>" +
"Download all scripts: download *.script<br>" +
"Download all text files: download *.txt<br>",
expr: "expr [mathematical expression]<br>" +
"Evaluate a simple mathematical expression. Supports native JavaScript operators:<br>" +
"+, -, /, *, **, %<br>" +
"Example:<br>" +
"expr 25 * 2 ** 10<br>" +
"Note that letters (non-digits) are not allowed and will be removed from the input.",
free: "free<br>" +
"Display's the memory usage on the current machine. Print the amount of RAM that is available on the current server as well as " +
"how much of it is being used.",
hack: "hack<br>" +
"Attempt to hack the current server. Requires root access in order to be run. See the wiki page for hacking mechanics<br>",
help: "help [command]<br>" +
"Display Terminal help information. Without arguments, 'help' prints a list of all valid Terminal commands and a brief " +
"description of their functionality. You can also pass the name of a Terminal command as an argument to 'help' to print " +
"more detailed information about the Terminal command. Examples: <br><br>" +
"help alias<br>" +
"help scan-analyze",
home: "home<br>" +
"Connect to your home computer. This will work no matter what server you are currently connected to.",
hostname: "hostname<br>" +
"Prints the hostname of the current server",
ifconfig: "ipconfig<br>" +
"Prints the IP address of the current server",
kill: "kill [script name] [args...]<br>" +
"Kill the script specified by the script name and arguments. Each argument must be separated by " +
"a space. Remember that a running script is uniquely identified by " +
"both its name and the arguments that are used to start it. So, if a script was ran with the following arguments:<br><br>" +
"run foo.script 1 sigma-cosmetics<br><br>" +
"Then to kill this script the same arguments would have to be used:<br><br>" +
"kill foo.script 1 sigma-cosmetics<br><br>" +
"Note that after issuing the 'kill' command for a script, it may take a while for the script to actually stop running. " +
"This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " +
"The script will not be stopped/killed until after that time has elapsed.",
killall: "killall<br>" +
"Kills all scripts on the current server. " +
"Note that after the 'kill' command is issued for a script, it may take a while for the script to actually stop running. " +
"This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " +
"The script will not be stopped/killed until after that time has elapsed.",
ls: "ls [| grep pattern]<br>" +
"The ls command, with no arguments, prints all files on the current server to the Terminal screen. " +
"This includes all scripts, programs, and message files. " +
"The files will be displayed in alphabetical order. <br><br>" +
"The '| grep pattern' optional parameter can be used to only display files whose filenames match the specified pattern. " +
"For example, if you wanted to only display files with the .script extension, you could use: <br><br>" +
"ls | grep .script<br><br>" +
"Alternatively, if you wanted to display all files with the word purchase in the filename, you could use: <br><br>" +
"ls | grep purchase",
lscpu: "lscpu<br>" +
"Prints the number of CPU Cores the current server has",
mem: "mem [script name] [-t] [num threads]<br>" +
"Displays the amount of RAM needed to run the specified script with a single thread. The command can also be used to print " +
"the amount of RAM needed to run a script with multiple threads using the '-t' flag. If the '-t' flag is specified, then " +
"an argument for the number of threads must be passed in afterwards. Examples:<br><br>" +
"mem foo.script<br>" +
"mem foo.script -t 50<br>" +
"The first example above will print the amount of RAM needed to run 'foo.script' with a single thread. The second example " +
"above will print the amount of RAM needed to run 'foo.script' with 50 threads.",
nano: "nano [file name]<br>" +
"Opens up the specified file in the Text Editor. Only scripts (.script) or text files (.txt) can be " +
"edited using the Text Editor. If the file does not already exist, then a new, empty one " +
"will be created",
ps: "ps<br>" +
"Prints all scripts that are running on the current server",
rm: "rm [file]<br>" +
"Removes the specified file from the current server. A file can be a script, a program, or a message file. <br><br>" +
"WARNING: This is permanent and cannot be undone",
run: "run [file name] [-t] [num threads] [args...]<br>" +
"Execute a program or a script.<br><br>" +
"The '[-t]', '[num threads]', and '[args...]' arguments are only valid when running a script. The '-t' flag is used " +
"to indicate that the script should be run with the specified number of threads. If the flag is omitted, " +
"then the script will be run with a single thread by default. " +
"If the '-t' flag is used, then it MUST come immediately " +
"after the script name, and the [num threads] argument MUST come immediately afterwards. <br><br>" +
"[args...] represents a variable number of arguments that will be passed into the script. See the documentation " +
"about script arguments. Each specified argument must be separated by a space. <br><br>",
scan: "scan<br>" +
"Prints all immediately-available network connection. This will print a list of all servers that you can currently connect " +
"to using the 'connect' Terminal command.",
"scan-analyze": "scan-analyze [depth] [-a]<br>" +
"Prints detailed information about all servers up to [depth] nodes away on the network. Calling " +
"'scan-analyze 1' will display information for the same servers that are shown by the 'scan' Terminal " +
"command. This command also shows the relative paths to reach each server.<br><br>" +
"By default, the maximum depth that can be specified for 'scan-analyze' is 3. However, once you have " +
"the DeepscanV1.exe and DeepscanV2.exe programs, you can execute 'scan-analyze' with a depth up to " +
"5 and 10, respectively.<br><br>" +
"The information 'scan-analyze' displays about each server includes whether or not you have root access to it, " +
"its required hacking level, the number of open ports required to run NUKE.exe on it, and how much RAM " +
"it has.<br><br>" +
"By default, this command will not display servers that you have purchased. However, you can pass in the " +
"-a flag at the end of the command if you would like to enable that.",
scp: "scp [filename] [target server]<br>" +
"Copies the specified file from the current server to the target server. " +
"This command only works for script files (.script extension), literature files (.lit extension), " +
"and text files (.txt extension). " +
"The second argument passed in must be the hostname or IP of the target server.",
sudov: "sudov<br>" +
"Prints whether or not you have root access to the current machine",
tail: "tail [script name] [args...]<br>" +
"Displays dynamic logs for the script specified by the script name and arguments. Each argument must be separated " +
"by a space. Remember that a running script is uniquely identified by both its name and the arguments that were used " +
"to run it. So, if a script was ran with the following arguments: <br><br>" +
"run foo.script 10 50000<br><br>" +
"Then in order to check its logs with 'tail' the same arguments must be used: <br><br>" +
"tail foo.script 10 50000",
theme: "theme [preset] | [#background #text #highlight]<br>" +
"Change the color of the game's user interface<br><br>" +
"This command can be called with a preset theme. Currently, the supported presets are 'default', 'muted', and 'solarized'. " +
"However, you can also specify your own color scheme using hex values. To do so, you must specify three hex color values " +
"for the background color, the text color, and the highlight color. These hex values must be preceded by a pound sign (#) and " +
"must be either 3 or 6 digits. Example:<br><br>" +
"theme #ffffff #385 #235012<br><br>" +
"A color picker such as " +
"<a href='https://www.google.com/search?q=color+picker&oq=color+picker&aqs=chrome.0.0l6.951j0j1&sourceid=chrome&ie=UTF-8' target='_blank'>Google's</a> " +
"can be used to get your desired hex color values<br><br>" +
"Themes are not saved, so when the game is closed and then re-opened or reloaded then it will revert back to the default theme.",
top: "top<br>" +
"Prints a list of all scripts running on the current server as well as their thread count and how much " +
"RAM they are using in total.",
unalias: 'unalias "[alias name]"<br>' +
"Deletes the specified alias. Note that the double quotation marks are required. <br><br>" +
"As an example, if an alias was declared using:<br><br>" +
'alias r="run"<br><br>' +
"Then it could be removed using:<br><br>" +
'unalias "r"<br><br>' +
"It is not necessary to differentiate between global and non-global aliases when using 'unalias'",
wget: "wget [url] [target file]<br>" +
"Retrieves data from a URL and downloads it to a file on the current server. The data can only " +
"be downloaded to a script (.script, .ns, .js) or a text file (.txt). If the file already exists, " +
"it will be overwritten by this command.<br><br>" +
"Note that it will not be possible to download data from many websites because they do not allow " +
"cross-origin resource sharing (CORS). Example:<br><br>" +
"wget https://raw.githubusercontent.com/danielyxie/bitburner/master/README.md game_readme.txt",
};
/***/ }),
/* 97 */,
/* 98 */,
/* 99 */,
/* 100 */,
/* 101 */,
/* 102 */,
/* 103 */,
/* 104 */
/*!************************************!*\
!*** ./src/Faction/FactionInfo.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Contains the "information" property for all the Factions, which is just a description of each faction
*/
class FactionInfo {
constructor(infoText, enemies, offerHackingMission, offerHackingWork, offerFieldWork, offerSecurityWork) {
this.infoText = infoText;
this.enemies = enemies;
this.offerHackingMission = offerHackingMission;
this.offerHackingWork = offerHackingWork;
this.offerFieldWork = offerFieldWork;
this.offerSecurityWork = offerSecurityWork;
// These are always all 1 for now.
this.augmentationPriceMult = 1;
this.augmentationRepRequirementMult = 1;
}
}
exports.FactionInfo = FactionInfo;
/**
* A map of all factions and associated info to them.
*/
// tslint:disable-next-line:variable-name
exports.FactionInfos = {
// Endgame
Illuminati: new FactionInfo("Humanity never changes. No matter how civilized society becomes, it will eventually fall back into chaos. " +
"And from this chaos, we are the Invisible hand that guides them to order. ", [], true, true, true, false),
Daedalus: new FactionInfo("Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", [], true, true, true, false),
"The Covenant": new FactionInfo("Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " +
"Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.<br>" +
"<br>" +
"Only then can you discover immortality.", [], true, true, true, false),
// Megacorporations, each forms its own faction
ECorp: new FactionInfo("ECorp's mission is simple: to connect the world of today with the technology of tomorrow. With our wide " +
"range of Internet-related software and commercial hardware, ECorp makes the world's information " +
"universally accessible.", [], true, true, true, true),
MegaCorp: new FactionInfo("MegaCorp does things that others don't. We imagine. We create. We invent. We build things that others have " +
"never even dreamed of. Our work fills the world's needs for food, water, power, and transporation on an " +
"unprecendented scale, in ways that no other company can.<br>" +
"<br>" +
"In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.", [], true, true, true, true),
"Bachman & Associates": new FactionInfo("Where Law and Business meet - thats where we are.<br>" +
"<br>" +
"Legal Insight - Business Instinct - Experience Innovation", [], true, true, true, true),
"Blade Industries": new FactionInfo("Augmentation is salvation", [], true, true, true, true),
NWO: new FactionInfo("The human being does not truly desire freedom. It wants to be observed, understood, and judged. It wants to " +
"be given purpose and direction in its life. That is why humans created God. And that is why humans created " +
"civilization - not because of willingness, but because of a need to be incorporated into higher orders of " +
"structure and meaning.", [], true, true, true, true),
"Clarke Incorporated": new FactionInfo("Unlocking the power of the genome", [], true, true, true, true),
"OmniTek Incorporated": new FactionInfo("Simply put, our mission is to design and build robots that make a difference", [], true, true, true, true),
"Four Sigma": new FactionInfo("The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven " +
"by deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", [], true, true, true, true),
"KuaiGong International": new FactionInfo("Dream big. Work hard. Make history.", [], true, true, true, true),
// Other Corporations
"Fulcrum Secret Technologies": new FactionInfo("The human organism has an innate desire to worship. That is why they created gods. If there were no gods, it " +
"would be necessary to create them. And now we can.", [], true, true, false, true),
// Hacker groups
BitRunners: new FactionInfo("Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. It's " +
"all transformed into bits, stored in bits, communicated through bits. Its impossible for any person to move, " +
"to live, to operate at any level without the use of bits. And when a person moves, lives, and operates, they " +
"leave behind their bits, mere traces of seemingly meaningless fragments of information. But these bits can be " +
"reconstructed. Transformed. Used.<br>" +
"<br>" +
"Those who run the bits, run the world", [], true, true, false, false),
"The Black Hand": new FactionInfo("The world, so afraid of strong government, now has no government. Only power - Digital power. Financial " +
"power. Technological power. And those at the top rule with an invisible hand. They built a society where the " +
"rich get richer, and everyone else suffers.<br>" +
"<br>" +
"So much pain. So many lives. Their darkness must end.", [], true, true, true, false),
NiteSec: new FactionInfo(" __..__ <br>" +
" _.nITESECNIt. <br>" +
" .-'NITESECNITESEc. <br>" +
" .' NITESECNITESECn <br>" +
" / NITESECNITESEC; <br>" +
" : :NITESECNITESEC; <br>" +
" ; $ NITESECNITESECN <br>" +
" : _, ,N'ITESECNITESEC <br>" +
" : .+^^`, : `NITESECNIT <br>" +
" ) /), `-,-=,NITESECNI <br>" +
" / ^ ,-;|NITESECN; <br>" +
" / _.' '-';NITESECN <br>" +
" ( , ,-''`^NITE' <br>" +
" )` :`. .' <br>" +
" )-- ; `- / <br>" +
" \' _.-' : <br>" +
" ( _.-' \. \ <br>" +
" \------. \ \ <br>" +
" \. \ \ <br>" +
" \ _.nIt <br>" +
" \ _.nITESECNi <br>" +
" nITESECNIT^' \ <br>" +
" NITE^' ___ \ <br>" +
" / .gP''''Tp. \ <br>" +
" : d' . `b \ <br>" +
" ; d' o `b ; <br>" +
" / d; `b| <br>" +
" /, $; @ `: <br>" +
" /' $$ ; <br>" +
" .' $$b o | <br>" +
" .' d$$$; : <br>" +
" / .d$$$$; , ; <br>" +
" d .dNITESEC $ | <br>" +
" :bp.__.gNITESEC$$ :$ ; <br>" +
" NITESECNITESECNIT $$b : <br>", [], true, true, false, false),
// City factions, essentially governments
Aevum: new FactionInfo("The Silicon City", [
"Chongqing",
"New Tokyo",
"Ishima",
"Volhaven",
], true, true, true, true),
Chongqing: new FactionInfo("Serve the people", [
"Sector-12",
"Aevum",
"Volhaven",
], true, true, true, true),
Ishima: new FactionInfo("The East Asian Order of the Future", [
"Sector-12",
"Aevum",
"Volhaven",
], true, true, true, true),
"New Tokyo": new FactionInfo("Asia's World City", [
"Sector-12",
"Aevum",
"Volhaven",
], true, true, true, true),
"Sector-12": new FactionInfo("The City of the Future", [
"Chongqing",
"New Tokyo",
"Ishima",
"Volhaven",
], true, true, true, true),
Volhaven: new FactionInfo("Benefit, Honour, and Glory", [
"Chongqing",
"Sector-12",
"New Tokyo",
"Aevum",
"Ishima",
], true, true, true, true),
// Criminal Organizations/Gangs
"Speakers for the Dead": new FactionInfo("It is better to reign in hell than to serve in heaven.", [], true, true, true, true),
"The Dark Army": new FactionInfo("The World doesn't care about right or wrong. It's all about power.", [], true, true, true, false),
"The Syndicate": new FactionInfo("Honor holds you back", [], true, true, true, true),
Silhouette: new FactionInfo("Corporations have filled the void of power left behind by the collapse of Western government. The issue is " +
"they've become so big that you don't know who they're working for. And if you're employed at one of these " +
"corporations, you don't even know who you're working for.<br>" +
"<br>" +
"That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.", [], true, true, true, false),
Tetrads: new FactionInfo("Following the Mandate of Heaven and Carrying out the Way", [], false, false, true, true),
"Slum Snakes": new FactionInfo("Slum Snakes rule!", [], false, false, true, true),
// Earlygame factions - factions the player will prestige with early on that don't belong in other categories.
Netburners: new FactionInfo("~~//*>H4CK|\|3T 8URN3R5**>?>\\~~", [], true, true, false, false),
"Tian Di Hui": new FactionInfo("Obey Heaven and Work Righteousness", [], true, true, false, true),
CyberSec: new FactionInfo("The Internet is the first thing that humanity has built that humanity doesnt understand, the largest " +
"experiment in anarchy that we have ever had. And as the world becomes increasingly dominated by the internet, " +
"society approaches the brink of total chaos. We serve only to protect society, to protect humanity, to " +
"protect the world from its imminent collapse.", [], true, true, false, false),
// Special Factions
Bladeburners: new FactionInfo("It's too bad they won't live. But then again, who does?<br><br>Note that for this faction, reputation can " +
"only be gained through Bladeburner actions. Completing Bladeburner contracts/operations will increase your " +
"reputation.", [], false, false, false, false),
};
/***/ }),
/* 105 */
/*!*************************************!*\
!*** ./src/NetscriptEnvironment.js ***!
\*************************************/
/*! exports provided: Environment */
/*! exports used: Environment */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Environment; });
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HacknetNode */ 63);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptFunctions */ 41);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptPort */ 68);
/* Environment
* NetScript program environment
*/
function Environment(workerScript,parent) {
if (parent){
//Create a copy of parent's variables
//this.vars = parent.vars;
this.vars = Object.assign({}, parent.vars);
} else {
this.vars = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_1__[/* NetscriptFunctions */ "a"])(workerScript);
}
this.parent = parent;
this.stopFlag = false;
}
Environment.prototype = {
//Create a "subscope", which is a new new "sub-environment"
//The subscope is linked to this through its parent variable
extend: function() {
return new Environment(null, this);
},
//Finds the scope where the variable with the given name is defined
lookup: function(name) {
var scope = this;
while (scope) {
if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
return scope;
}
scope = scope.parent;
}
return null;
},
//Get the current value of a variable
get: function(name) {
if (name in this.vars) {
return this.vars[name];
}
throw new Error("Undefined variable " + name);
},
//Sets the value of a variable in any scope
set: function(name, value) {
var scope = this.lookup(name);
//If scope has a value, then this variable is already set in a higher scope, so
//set is there. Otherwise, create a new variable in the local scope
if (scope !== null) {
return scope.vars[name] = value;
} else {
return this.vars[name] = value;
}
},
setArrayElement: function(name, idx, value) {
if (!(idx instanceof Array)) {
throw new Error("idx parameter is not an Array");
}
var scope = this.lookup(name);
if (!scope && this.parent) {
throw new Error("Undefined variable " + name);
}
var arr = (scope || this).vars[name];
if (!(arr.constructor === Array || arr instanceof Array)) {
throw new Error("Variable is not an array: " + name);
}
var res = arr;
for (var iterator = 0; iterator < idx.length-1; ++iterator) {
var i = idx[iterator];
if (!(res instanceof Array) || i >= res.length) {
throw new Error("Out-of-bounds array access");
}
res = res[i];
}
//Cant assign to ports or HacknetNodes
if (res[idx[idx.length-1]] instanceof _HacknetNode__WEBPACK_IMPORTED_MODULE_0__[/* HacknetNode */ "a"]) {
throw new Error("Cannot assign a Hacknet Node handle to a new value");
}
if (res[idx[idx.length-1]] instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_2__[/* NetscriptPort */ "a"]) {
throw new Error("Cannot assign a Netscript Port handle to a new value");
}
return res[idx[idx.length-1]] = value;
},
//Creates (or overwrites) a variable in the current scope
def: function(name, value) {
return this.vars[name] = value;
}
};
/***/ }),
/* 106 */
/*!*************************************!*\
!*** ./src/NetscriptJSEvaluator.js ***!
\*************************************/
/*! exports provided: makeScriptBlob, executeJSScript, _getScriptUrls */
/*! exports used: executeJSScript */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export makeScriptBlob */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return executeJSScript; });
/* unused harmony export _getScriptUrls */
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6);
// Makes a blob that contains the code of a given script.
function makeScriptBlob(code) {
return new Blob([code], {type: "text/javascript"});
}
// Begin executing a user JS script, and return a promise that resolves
// or rejects when the script finishes.
// - script is a script to execute (see Script.js). We depend only on .filename and .code.
// scripts is an array of other scripts on the server.
// env is the global environment that should be visible to all the scripts
// (i.e. hack, grow, etc.).
// When the promise returned by this resolves, we'll have finished
// running the main function of the script.
async function executeJSScript(scripts = [], workerScript) {
let loadedModule;
let urlStack = null;
let script = workerScript.getScript();
if (script.module === "") {
// The URL at the top is the one we want to import. It will
// recursively import all the other modules in the urlStack.
//
// Webpack likes to turn the import into a require, which sort of
// but not really behaves like import. Particularly, it cannot
// load fully dynamic content. So we hide the import from webpack
// by placing it inside an eval call.
urlStack = _getScriptUrls(script, scripts, []);
script.module = await eval('import(urlStack[urlStack.length - 1])');
}
loadedModule = script.module;
let ns = workerScript.env.vars;
try {
// TODO: putting await in a non-async function yields unhelpful
// "SyntaxError: unexpected reserved word" with no line number information.
if (!loadedModule.main) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_0__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `${script.filename} cannot be run because it does not have a main function.`);
}
return loadedModule.main(ns);
} finally {
// Revoke the generated URLs
if (urlStack != null) {
for (const url in urlStack) URL.revokeObjectURL(url);
}
};
}
// Gets a stack of blob urls, the top/right-most element being
// the blob url for the named script on the named server.
//
// - script -- the script for whom we are getting a URL.
// - scripts -- all the scripts available on this server
// - seen -- The modules above this one -- to prevent mutual dependency.
//
// TODO We don't make any effort to cache a given module when it is imported at
// different parts of the tree. That hasn't presented any problem with during
// testing, but it might be an idea for the future. Would require a topo-sort
// then url-izing from leaf-most to root-most.
function _getScriptUrls(script, scripts, seen) {
// Inspired by: https://stackoverflow.com/a/43834063/91401
const urlStack = [];
seen.push(script);
try {
// Replace every import statement with an import to a blob url containing
// the corresponding script. E.g.
//
// import {foo} from "bar.js";
//
// becomes
//
// import {foo} from "blob://<uuid>"
//
// Where the blob URL contains the script content.
let transformedCode = script.code.replace(/((?:from|import)\s+(?:'|"))(?:\.\/)?([^'"]+)('|";)/g,
(unmodified, prefix, filename, suffix) => {
const isAllowedImport = scripts.some(s => s.filename == filename);
if (!isAllowedImport) return unmodified;
// Find the corresponding script.
const [importedScript] = scripts.filter(s => s.filename == filename);
// Try to get a URL for the requested script and its dependencies.
const urls = _getScriptUrls(importedScript, scripts, seen);
// The top url in the stack is the replacement import file for this script.
urlStack.push(...urls);
return [prefix, urls[urls.length - 1], suffix].join('');
}
);
// We automatically define a print function() in the NetscriptJS module so that
// accidental calls to window.print() do not bring up the "print screen" dialog
transformedCode += `\n\nfunction print() {throw new Error("Invalid call to window.print(). Did you mean to use Netscript's print()?");}`
// If we successfully transformed the code, create a blob url for it and
// push that URL onto the top of the stack.
urlStack.push(URL.createObjectURL(makeScriptBlob(transformedCode)));
return urlStack;
} catch (err) {
// If there is an error, we need to clean up the URLs.
for (const url in urlStack) URL.revokeObjectURL(url);
throw err;
} finally {
seen.pop();
}
}
/***/ }),
/* 107 */
/*!************************!*\
!*** ./src/DevMenu.js ***!
\************************/
/*! exports provided: createDevMenu, closeDevMenu */
/*! exports used: closeDevMenu, createDevMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createDevMenu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return closeDevMenu; });
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 21);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CodingContractGenerator */ 92);
/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram */ 23);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction/Factions */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./RedPill */ 55);
/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./StockMarket */ 22);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Stock */ 25);
/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Terminal */ 49);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 42);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 20);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_14__);
const devMenuContainerId = "dev-menu-container";
function createDevMenu() {
if (false) {}
const devMenuText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h1", {
display: "block",
innerText: "Development Menu - Only meant to be used for testing/debugging",
});
// Generic
const genericHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {
display: "block",
innerText: "Generic"
});
const addMoney = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(1e15);
},
display: "block",
innerText: "Add $1000t",
});
const addRam = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].getHomeComputer().maxRam *= 2;
},
display: "block",
innerText: "Double Home Computer RAM",
});
const triggerBitflume = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_6__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN, true);
},
innerText: "Trigger BitFlume",
});
const destroyCurrentBitnode = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_6__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN);
},
innerText: "Destroy Current BitNode",
tooltip: "Will grant Source-File for the BitNode",
});
// Experience / stats
const statsHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {
display: "block",
innerText: "Experience/Stats"
});
const statsHackingExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- hacking exp",
type: "number",
});
const statsHackingExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsHackingExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainHackingExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Hacking Exp",
});
const statsStrengthExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- strength exp",
type: "number",
});
const statsStrengthExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsStrengthExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainStrengthExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Strength Exp",
});
const statsDefenseExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- defense exp",
type: "number",
});
const statsDefenseExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsDefenseExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainDefenseExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Defense Exp",
});
const statsDexterityExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- dexterity exp",
type: "number",
});
const statsDexterityExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsDexterityExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainDexterityExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Dexterity Exp",
});
const statsAgilityExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- agility exp",
type: "number",
});
const statsAgilityExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsAgilityExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainAgilityExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Agility Exp",
});
const statsCharismaExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- charisma exp",
type: "number",
});
const statsCharismaExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsCharismaExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainCharismaExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Charisma Exp",
});
const statsIntelligenceExpInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "+/- intelligence exp",
type: "number",
});
const statsIntelligenceExpButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const exp = parseInt(statsIntelligenceExpInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainIntelligenceExp(exp);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].updateSkillLevels();
},
innerText: "Add Intelligence Exp",
});
const statsEnableIntelligenceButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].intelligence = 1;
},
innerText: "Enable Intelligence"
});
const statsDisableIntelligenceButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].intelligence = 0;
},
innerText: "Disable Intelligence"
});
// Factions
const factionsHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Factions"});
const factionsDropdown = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("select", {
class: "dropdown",
margin: "5px",
});
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"]) {
factionsDropdown.options[factionsDropdown.options.length] = new Option(_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][i].name, _Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][i].name);
}
const factionsAddButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const facName = factionsDropdown.options[factionsDropdown.selectedIndex].value;
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].receiveInvite(facName);
},
innerText: "Receive Invite to Faction",
});
// Augmentations / Source Files
const augmentationsHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Augmentations"});
const augmentationsDropdown = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("select", {
class: "dropdown",
margin: "5px",
});
for (const i in _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"]) {
const augName = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"][i];
augmentationsDropdown.options[augmentationsDropdown.options.length] = new Option(augName, augName);
}
const augmentationsQueueButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].queueAugmentation(augmentationsDropdown.options[augmentationsDropdown.selectedIndex].value);
},
innerText: "Queue Augmentation",
})
// Programs
const programsHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Programs"});
const programsAddDropdown = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("select", {
class: "dropdown",
margin: "5px",
});
for (const i in _CreateProgram__WEBPACK_IMPORTED_MODULE_2__[/* Programs */ "a"]) {
const progName = _CreateProgram__WEBPACK_IMPORTED_MODULE_2__[/* Programs */ "a"][i].name;
programsAddDropdown.options[programsAddDropdown.options.length] = new Option(progName, progName);
}
const programsAddButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const program = programsAddDropdown.options[programsAddDropdown.selectedIndex].value;
if(!_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasProgram(program)) {
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].getHomeComputer().programs.push(program);
}
},
innerText: "Add Program",
})
// Servers
const serversHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Servers"});
const serversOpenAll = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
for (const i in _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"]) {
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].hasAdminRights = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].sshPortOpen = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].ftpPortOpen = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].smtpPortOpen = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].httpPortOpen = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].sqlPortOpen = true;
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].openPortCount = 5;
}
},
display: "block",
innerText: "Get Admin Rights to all servers",
});
const serversMinSecurityAll = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
for (const i in _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"]) {
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].hackDifficulty = _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].minDifficulty;
}
},
display: "block",
innerText: "Set all servers to min security",
});
const serversMaxMoneyAll = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
for (const i in _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"]) {
_Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].moneyAvailable = _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].moneyMax;
}
},
display: "block",
innerText: "Set all servers to max money",
});
const serversConnectToDropdown = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("select", {class: "dropdown"});
for (const i in _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"]) {
const hn = _Server__WEBPACK_IMPORTED_MODULE_5__[/* AllServers */ "b"][i].hostname;
serversConnectToDropdown.options[serversConnectToDropdown.options.length] = new Option(hn, hn);
}
const serversConnectToButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const host = serversConnectToDropdown.options[serversConnectToDropdown.selectedIndex].value;
_Terminal__WEBPACK_IMPORTED_MODULE_9__[/* Terminal */ "a"].connectToServer(host);
},
innerText: "Connect to server",
});
// Bladeburner
const bladeburnerHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Bladeburner"});
const bladeburnerGainRankInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "Rank to gain (or negative to lose rank)",
type: "number",
});
const bladeburnerGainRankButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
try {
const rank = parseInt(bladeburnerGainRankInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bladeburner.changeRank(rank);
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_12__[/* exceptionAlert */ "a"])(`Failed to change Bladeburner Rank in dev menu: ${e}`);
}
},
innerText: "Gain Bladeburner Rank",
});
const bladeburnerStoredCyclesInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "# Cycles to Add",
type: "number",
});
const bladeburnerStoredCyclesButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
try {
const cycles = parseInt(bladeburnerStoredCyclesInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bladeburner.storedCycles += cycles;
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_12__[/* exceptionAlert */ "a"])(`Failed to add cycles to Bladeburner in dev menu: ${e}`);
}
},
innerText: "Add Cycles to Bladeburner mechanic",
});
// Gang
const gangHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Gang"});
const gangStoredCyclesInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "# Cycles to add",
type: "number",
});
const gangAddStoredCycles = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
try {
const cycles = parseInt(gangStoredCyclesInput.value);
_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gang.storedCycles += cycles;
} catch(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_12__[/* exceptionAlert */ "a"])(`Failed to add stored cycles to gang mechanic: ${e}`);
}
},
innerText: "Add cycles to Gang mechanic",
});
// Coding Contracts
const contractsHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Coding Contracts"});
const generateRandomContractBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_1__[/* generateRandomContract */ "a"])();
},
innerText: "Generate Random Contract",
});
// Stock Market
const stockmarketHeader = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h2", {innerText: "Stock Market"});
const stockInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
display: "block",
placeholder: "Stock symbol(s), or 'all'",
});
function processStocks(cb) {
const input = stockInput.value.toString().replace(/\s/g, '');
// Empty input, or "all", will process all stocks
if (input === "" || input.toLowerCase() === "all") {
for (const name in _StockMarket__WEBPACK_IMPORTED_MODULE_7__[/* StockMarket */ "c"]) {
if (_StockMarket__WEBPACK_IMPORTED_MODULE_7__[/* StockMarket */ "c"].hasOwnProperty(name)) {
const stock = _StockMarket__WEBPACK_IMPORTED_MODULE_7__[/* StockMarket */ "c"][name];
if (stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_8__["Stock"]) {
cb(stock);
}
}
}
return;
}
const stockSymbols = input.split(",");
for (let i = 0; i < stockSymbols.length; ++i) {
const stock = _StockMarket__WEBPACK_IMPORTED_MODULE_7__[/* SymbolToStockMap */ "e"][stockSymbols];
if (stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_8__["Stock"]) {
cb(stock);
}
}
}
const stockPriceChangeInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("input", {
class: "text-input",
margin: "5px",
placeholder: "Price to change stock(s) to",
type: "number",
});
const stockPriceChangeBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
const price = parseInt(stockPriceChangeInput.value);
if (isNaN(price)) { return; }
processStocks((stock) => {
stock.price = price;
});
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])(`Stock Prices changed to ${price}`);
},
innerText: "Change Stock Price(s)",
});
const stockViewPriceCapBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("button", {
class: "std-button",
clickListener: () => {
let text = "";
processStocks((stock) => {
text += `${stock.symbol}: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.cap, '$0.000a')}<br>`;
});
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])(text);
},
innerText: "View Stock Price Caps",
});
// Add everything to container, then append to main menu
const devMenuContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("div", {
class: "generic-menupage-container",
id: devMenuContainerId,
});
devMenuContainer.appendChild(devMenuText);
devMenuContainer.appendChild(genericHeader);
devMenuContainer.appendChild(addMoney);
devMenuContainer.appendChild(addRam);
devMenuContainer.appendChild(triggerBitflume);
devMenuContainer.appendChild(destroyCurrentBitnode);
devMenuContainer.appendChild(statsHeader);
devMenuContainer.appendChild(statsHackingExpInput);
devMenuContainer.appendChild(statsHackingExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsStrengthExpInput);
devMenuContainer.appendChild(statsStrengthExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsDefenseExpInput);
devMenuContainer.appendChild(statsDefenseExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsDexterityExpInput);
devMenuContainer.appendChild(statsDexterityExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsAgilityExpInput);
devMenuContainer.appendChild(statsAgilityExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsCharismaExpInput);
devMenuContainer.appendChild(statsCharismaExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsIntelligenceExpInput);
devMenuContainer.appendChild(statsIntelligenceExpButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(statsEnableIntelligenceButton);
devMenuContainer.appendChild(statsDisableIntelligenceButton);
devMenuContainer.appendChild(factionsHeader);
devMenuContainer.appendChild(factionsDropdown);
devMenuContainer.appendChild(factionsAddButton);
devMenuContainer.appendChild(augmentationsHeader);
devMenuContainer.appendChild(augmentationsDropdown);
devMenuContainer.appendChild(augmentationsQueueButton);
devMenuContainer.appendChild(programsHeader);
devMenuContainer.appendChild(programsAddDropdown);
devMenuContainer.appendChild(programsAddButton);
devMenuContainer.appendChild(serversHeader);
devMenuContainer.appendChild(serversOpenAll);
devMenuContainer.appendChild(serversMinSecurityAll);
devMenuContainer.appendChild(serversMaxMoneyAll);
devMenuContainer.appendChild(serversConnectToDropdown);
devMenuContainer.appendChild(serversConnectToButton);
devMenuContainer.appendChild(bladeburnerHeader);
devMenuContainer.appendChild(bladeburnerGainRankInput);
devMenuContainer.appendChild(bladeburnerGainRankButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(bladeburnerStoredCyclesInput);
devMenuContainer.appendChild(bladeburnerStoredCyclesButton);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(gangHeader);
devMenuContainer.appendChild(gangStoredCyclesInput);
devMenuContainer.appendChild(gangAddStoredCycles);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(contractsHeader);
devMenuContainer.appendChild(generateRandomContractBtn);
devMenuContainer.appendChild(stockmarketHeader);
devMenuContainer.appendChild(stockInput);
devMenuContainer.appendChild(stockPriceChangeInput);
devMenuContainer.appendChild(stockPriceChangeBtn);
devMenuContainer.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_13__["createElement"])("br"));
devMenuContainer.appendChild(stockViewPriceCapBtn);
const entireGameContainer = document.getElementById("entire-game-container");
if (entireGameContainer == null) {
throw new Error("Could not find entire-game-container DOM element");
}
entireGameContainer.appendChild(devMenuContainer);
}
function closeDevMenu() {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_14__["removeElementById"])(devMenuContainerId);
}
/***/ }),
/* 108 */
/*!********************************!*\
!*** ./src/ServerPurchases.js ***!
\********************************/
/*! exports provided: purchaseServer, purchaseRamForHomeComputer */
/*! exports used: purchaseRamForHomeComputer, purchaseServer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return purchaseServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return purchaseRamForHomeComputer; });
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server */ 11);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress */ 57);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/YesNoBox */ 17);
/* Functions to handle any server-related purchasing:
* Purchasing new servers
* Purchasing more RAM for home computer
*/
function purchaseServer(ram, cost) {
//Check if player has enough money
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].money.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You don't have enough money to purchase this server!");
return;
}
//Maximum server limit
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].purchasedServers.length >= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].PurchasedServerLimit) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You have reached the maximum limit of " + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].PurchasedServerLimit + " servers. " +
"You cannot purchase any more. You can " +
"delete some of your purchased servers using the deleteServer() Netscript function in a script");
return;
}
var hostname = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_5__[/* yesNoTxtInpBoxGetInput */ "h"])();
if (hostname == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You must enter a hostname for your new server!");
return;
}
//Create server
var newServ = new _Server__WEBPACK_IMPORTED_MODULE_2__[/* Server */ "d"]({
ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_4__[/* createRandomIp */ "a"])(), hostname:hostname, organizationName:"",
isConnectedTo:false, adminRights:true, purchasedByPlayer:true, maxRam:ram
});
Object(_Server__WEBPACK_IMPORTED_MODULE_2__[/* AddToAllServers */ "a"])(newServ);
//Add to Player's purchasedServers array
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].purchasedServers.push(newServ.ip);
//Connect new server to home computer
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].loseMoney(cost);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("Server successfully purchased with hostname " + hostname);
}
function purchaseRamForHomeComputer(cost) {
if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].money.lt(cost)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You do not have enough money to purchase additional RAM for your home computer");
return;
}
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].getHomeComputer();
homeComputer.maxRam *= 2;
_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].loseMoney(cost);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
}
/***/ }),
/* 109 */
/*!************************************************!*\
!*** ./utils/uiHelpers/removeLoadingScreen.ts ***!
\************************************************/
/*! no static exports found */
/*! exports used: removeLoadingScreen */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 51);
const removeElementById_1 = __webpack_require__(/*! ./removeElementById */ 20);
/**
* Routes the player from the Loading screen to the main game content.
*/
function removeLoadingScreen() {
// TODO: Have this manipulate CSS classes instead of direct styles
removeElementById_1.removeElementById("loader");
getElementById_1.getElementById("entire-game-container").style.visibility = "visible";
}
exports.removeLoadingScreen = removeLoadingScreen;
/***/ }),
/* 110 */,
/* 111 */,
/* 112 */,
/* 113 */,
/* 114 */,
/* 115 */,
/* 116 */,
/* 117 */
/*!*************************************!*\
!*** ./src/ui/setSettingsLabels.js ***!
\*************************************/
/*! exports provided: setSettingsLabels */
/*! exports used: setSettingsLabels */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return setSettingsLabels; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../engine */ 8);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Settings */ 19);
/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _numeralFormat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./numeralFormat */ 4);
function setSettingsLabels() {
var nsExecTime = document.getElementById("settingsNSExecTimeRangeValLabel");
var nsLogLimit = document.getElementById("settingsNSLogRangeValLabel");
var nsPortLimit = document.getElementById("settingsNSPortRangeValLabel");
var suppressMsgs = document.getElementById("settingsSuppressMessages");
var suppressFactionInv = document.getElementById("settingsSuppressFactionInvites")
var suppressTravelConfirmation = document.getElementById("settingsSuppressTravelConfirmation");
var suppressBuyAugmentationConfirmation = document.getElementById("settingsSuppressBuyAugmentationConfirmation");
var suppressHospitalizationPopup = document.getElementById("settingsSuppressHospitalizationPopup");
var autosaveInterval = document.getElementById("settingsAutosaveIntervalValLabel");
var disableHotkeys = document.getElementById("settingsDisableHotkeys");
var locale = document.getElementById("settingsLocale");
//Initialize values on labels
nsExecTime.innerHTML = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].CodeInstructionRunTime + "ms";
nsLogLimit.innerHTML = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxLogCapacity;
nsPortLimit.innerHTML = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxPortCapacity;
suppressMsgs.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressMessages;
suppressFactionInv.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressFactionInvites;
suppressTravelConfirmation.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressTravelConfirmation;
suppressBuyAugmentationConfirmation.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressBuyAugmentationConfirmation;
suppressHospitalizationPopup.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressHospitalizationPopup;
autosaveInterval.innerHTML = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].AutosaveInterval;
disableHotkeys.checked = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].DisableHotkeys;
locale.value = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].Locale;
_numeralFormat__WEBPACK_IMPORTED_MODULE_2__[/* numeralWrapper */ "a"].updateLocale(_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].Locale); //Initialize locale
//Set handlers for when input changes for sliders
var nsExecTimeInput = document.getElementById("settingsNSExecTimeRangeVal");
var nsLogRangeInput = document.getElementById("settingsNSLogRangeVal");
var nsPortRangeInput = document.getElementById("settingsNSPortRangeVal");
var nsAutosaveIntervalInput = document.getElementById("settingsAutosaveIntervalVal");
nsExecTimeInput.value = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].CodeInstructionRunTime;
nsLogRangeInput.value = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxLogCapacity;
nsPortRangeInput.value = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxPortCapacity;
nsAutosaveIntervalInput.value = _Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].AutosaveInterval;
nsExecTimeInput.oninput = function() {
nsExecTime.innerHTML = this.value + 'ms';
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].CodeInstructionRunTime = this.value;
};
nsLogRangeInput.oninput = function() {
nsLogLimit.innerHTML = this.value;
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxLogCapacity = this.value;
};
nsPortRangeInput.oninput = function() {
nsPortLimit.innerHTML = this.value;
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].MaxPortCapacity = this.value;
};
nsAutosaveIntervalInput.oninput = function() {
autosaveInterval.innerHTML = this.value;
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].AutosaveInterval = Number(this.value);
if (Number(this.value) === 0) {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity;
} else {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Number(this.value) * 5;
}
};
//Set handlers for when settings change on checkboxes
suppressMsgs.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressMessages = this.checked;
};
suppressFactionInv.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressFactionInvites = this.checked;
};
suppressTravelConfirmation.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressTravelConfirmation = this.checked;
};
suppressBuyAugmentationConfirmation.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressBuyAugmentationConfirmation = this.checked;
};
suppressHospitalizationPopup.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].SuppressHospitalizationPopup = this.checked;
}
disableHotkeys.onclick = function() {
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].DisableHotkeys = this.checked;
}
//Locale selector
locale.onchange = function() {
if (!_numeralFormat__WEBPACK_IMPORTED_MODULE_2__[/* numeralWrapper */ "a"].updateLocale(locale.value)) {
console.warn(`Invalid locale for numeral: ${locale.value}`);
let defaultValue = 'en';
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].Locale = defaultValue;
locale.value = defaultValue;
return;
}
_Settings__WEBPACK_IMPORTED_MODULE_1__["Settings"].Locale = locale.value;
}
}
/***/ }),
/* 118 */
/*!**********************************!*\
!*** ./src/CharacterOverview.js ***!
\**********************************/
/*! exports provided: CharacterOverview */
/*! exports used: CharacterOverview */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CharacterOverview; });
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ui/numeralFormat */ 4);
function CharacterOverview() {
this.hp = document.getElementById("character-hp-text");
this.money = document.getElementById("character-money-text");
this.hack = document.getElementById("character-hack-text");
this.str = document.getElementById("character-str-text");
this.def = document.getElementById("character-def-text");
this.dex = document.getElementById("character-dex-text");
this.agi = document.getElementById("character-agi-text");
this.cha = document.getElementById("character-cha-text");
this.int = document.getElementById("character-int-text");
this.intWrapper = document.getElementById("character-int-wrapper");
this.repaintElem = document.getElementById("character-overview-text");
}
CharacterOverview.prototype.repaint = function() {
// this is an arbitrary function we can call to trigger a repaint.
this.repaintElem.getClientRects();
}
CharacterOverview.prototype.update = function() {
if (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hp == null) {_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hp = _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].max_hp;}
const replaceAndChanged = function(elem, text) {
if(elem.textContent === text) {
return false;
}
elem.textContent = text;
return true;
}
let changed = false;
changed = replaceAndChanged(this.hp, _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hp + " / " + _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].max_hp) || changed;
changed = replaceAndChanged(this.money, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_1__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].money.toNumber(), '$0.000a')) || changed;
changed = replaceAndChanged(this.hack, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].hacking_skill).toLocaleString()) || changed;
changed = replaceAndChanged(this.str, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].strength).toLocaleString()) || changed;
changed = replaceAndChanged(this.def, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].defense).toLocaleString()) || changed;
changed = replaceAndChanged(this.dex, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].dexterity).toLocaleString()) || changed;
changed = replaceAndChanged(this.agi, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].agility).toLocaleString()) || changed;
changed = replaceAndChanged(this.cha, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].charisma).toLocaleString()) || changed;
changed = replaceAndChanged(this.int, (_Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].intelligence).toLocaleString()) || changed;
// handle int appearing
const int = this.intWrapper;
const old = int.style.display;
const now = _Player__WEBPACK_IMPORTED_MODULE_0__[/* Player */ "a"].intelligence >= 1 ? "" : "none";
if(old !== now) {
int.style.display = now;
changed = true;
}
// recalculate box size if something changed
if(changed) this.repaint();
}
/***/ }),
/* 119 */
/*!******************************!*\
!*** ./src/JSInterpreter.js ***!
\******************************/
/*! exports provided: Interpreter */
/*! exports used: Interpreter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Interpreter; });
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn */ 46);
/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__);
/**
* @license
* JavaScript Interpreter
*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Interpreting JavaScript in JavaScript.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
/**
* Create a new interpreter.
* @param {string|!Object} code Raw JavaScript text or AST.
* @param {Function=} opt_initFunc Optional initialization function. Used to
* define APIs. When called it is passed the interpreter object and the
* global scope object.
* @param {Number} Bitburner-specific number used for determining exception line numbers
* @constructor
*/
var Interpreter = function(code, opt_initFunc, lineOffset=0) {
this.sourceCode = code;
this.sourceCodeLineOffset = lineOffset;
if (typeof code === 'string') {
code = _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"](code, Interpreter.PARSE_OPTIONS);
}
this.ast = code;
this.initFunc_ = opt_initFunc;
this.paused_ = false;
this.polyfills_ = [];
// Unique identifier for native functions. Used in serialization.
this.functionCounter_ = 0;
// Map node types to our step function names; a property lookup is faster
// than string concatenation with "step" prefix.
this.stepFunctions_ = Object.create(null);
var stepMatch = /^step([A-Z]\w*)$/;
var m;
for (var methodName in this) {
if ((typeof this[methodName] === 'function') &&
(m = methodName.match(stepMatch))) {
this.stepFunctions_[m[1]] = this[methodName].bind(this);
}
}
// Create and initialize the global scope.
this.global = this.createScope(this.ast, null);
// Run the polyfills.
this.ast = _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"](this.polyfills_.join('\n'), Interpreter.PARSE_OPTIONS);
this.polyfills_ = undefined; // Allow polyfill strings to garbage collect.
this.stripLocations_(this.ast, undefined, undefined);
var state = new Interpreter.State(this.ast, this.global);
state.done = false;
this.stateStack = [state];
this.run();
this.value = undefined;
// Point at the main program.
this.ast = code;
var state = new Interpreter.State(this.ast, this.global);
state.done = false;
this.stateStack.length = 0;
this.stateStack[0] = state;
// Get a handle on Acorn's node_t object. It's tricky to access.
this.nodeConstructor = state.node.constructor;
// Preserve publicly properties from being pruned/renamed by JS compilers.
// Add others as needed.
this['stateStack'] = this.stateStack;
};
/**
* @const {!Object} Configuration used for all Acorn parsing.
*/
Interpreter.PARSE_OPTIONS = {
ecmaVersion: 5,
locations: true
};
/**
* Property descriptor of readonly properties.
*/
Interpreter.READONLY_DESCRIPTOR = {
configurable: true,
enumerable: true,
writable: false
};
/**
* Property descriptor of non-enumerable properties.
*/
Interpreter.NONENUMERABLE_DESCRIPTOR = {
configurable: true,
enumerable: false,
writable: true
};
/**
* Property descriptor of readonly, non-enumerable properties.
*/
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR = {
configurable: true,
enumerable: false,
writable: false
};
/**
* Property descriptor of variables.
*/
Interpreter.VARIABLE_DESCRIPTOR = {
configurable: false,
enumerable: true,
writable: true
};
/**
* Unique symbol for indicating that a step has encountered an error, has
* added it to the stack, and will be thrown within the user's program.
* When STEP_ERROR is thrown in the JS-Interpreter, the error can be ignored.
*/
Interpreter.STEP_ERROR = {};
/**
* Unique symbol for indicating that a reference is a variable on the scope,
* not an object property.
*/
Interpreter.SCOPE_REFERENCE = {};
/**
* Unique symbol for indicating, when used as the value of the value
* parameter in calls to setProperty and friends, that the value
* should be taken from the property descriptor instead.
*/
Interpreter.VALUE_IN_DESCRIPTOR = {};
/**
* For cycle detection in array to string and error conversion;
* see spec bug github.com/tc39/ecma262/issues/289
* Since this is for atomic actions only, it can be a class property.
*/
Interpreter.toStringCycles_ = [];
/**
* Determine error/exception line number in Bitburner source code
* @param {Object} AST Node that causes Error/Exception
*/
Interpreter.prototype.getErrorLineNumber = function(node) {
var code = this.sourceCode;
if (node == null || node.start == null) {return NaN;}
try {
code = code.substring(0, node.start);
return (code.match(/\n/g) || []).length + 1 - this.sourceCodeLineOffset;
} catch(e) {
return NaN;
}
}
/**
* Generate the appropriate line number error message for Bitburner
* @param {Number} lineNumber
*/
Interpreter.prototype.getErrorLineNumberMessage = function(lineNumber) {
if (isNaN(lineNumber)) {
return " (Unknown line number)";
} else if (lineNumber <= 0) {
return " (Error occurred in an imported function)";
} else {
return " (Line Number " + lineNumber + ". This line number is probably incorrect " +
"if your script is importing any functions. This is being worked on)";
}
}
/**
* Add more code to the interpreter.
* @param {string|!Object} code Raw JavaScript text or AST.
*/
Interpreter.prototype.appendCode = function(code) {
var state = this.stateStack[0];
if (!state || state.node['type'] !== 'Program') {
throw Error('Expecting original AST to start with a Program node.');
}
if (typeof code === 'string') {
code = _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"](code, Interpreter.PARSE_OPTIONS);
}
if (!code || code['type'] !== 'Program') {
throw Error('Expecting new AST to start with a Program node.');
}
this.populateScope_(code, state.scope);
// Append the new program to the old one.
for (var i = 0, node; (node = code['body'][i]); i++) {
state.node['body'].push(node);
}
state.done = false;
};
/**
* Execute one step of the interpreter.
* @return {boolean} True if a step was executed, false if no more instructions.
*/
Interpreter.prototype.step = function() {
var stack = this.stateStack;
var state = stack[stack.length - 1];
if (!state) {
return false;
}
var node = state.node, type = node['type'];
if (type === 'Program' && state.done) {
return false;
} else if (this.paused_) {
return true;
}
try {
var nextState = this.stepFunctions_[type](stack, state, node);
} catch (e) {
// Eat any step errors. They have been thrown on the stack.
if (e !== Interpreter.STEP_ERROR) {
// Uh oh. This is a real error in the JS-Interpreter. Rethrow.
throw e;
}
}
if (nextState) {
stack.push(nextState);
}
if (!node['end']) {
// This is polyfill code. Keep executing until we arrive at user code.
return this.step();
}
return true;
};
/**
* Execute the interpreter to program completion. Vulnerable to infinite loops.
* @return {boolean} True if a execution is asynchronously blocked,
* false if no more instructions.
*/
Interpreter.prototype.run = function() {
while (!this.paused_ && this.step()) {}
return this.paused_;
};
/**
* Initialize the global scope with buitin properties and functions.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initGlobalScope = function(scope) {
// Initialize uneditable global properties.
this.setProperty(scope, 'NaN', NaN,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(scope, 'Infinity', Infinity,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(scope, 'undefined', undefined,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(scope, 'window', scope,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(scope, 'this', scope,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(scope, 'self', scope); // Editable.
// Create the objects which will become Object.prototype and
// Function.prototype, which are needed to bootstrap everything else.
this.OBJECT_PROTO = new Interpreter.Object(null);
this.FUNCTION_PROTO = new Interpreter.Object(this.OBJECT_PROTO);
// Initialize global objects.
this.initFunction(scope);
this.initObject(scope);
// Unable to set scope's parent prior (OBJECT did not exist).
// Note that in a browser this would be 'Window', whereas in Node.js it would
// be 'Object'. This interpreter is closer to Node in that it has no DOM.
scope.proto = this.OBJECT_PROTO;
this.setProperty(scope, 'constructor', this.OBJECT,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.initArray(scope);
this.initString(scope);
this.initBoolean(scope);
this.initNumber(scope);
this.initDate(scope);
this.initRegExp(scope);
this.initError(scope);
this.initMath(scope);
this.initJSON(scope);
// Initialize global functions.
var thisInterpreter = this;
var func = this.createNativeFunction(
function(x) {throw EvalError("Can't happen");}, false);
func.eval = true;
this.setProperty(scope, 'eval', func);
this.setProperty(scope, 'parseInt',
this.createNativeFunction(parseInt, false));
this.setProperty(scope, 'parseFloat',
this.createNativeFunction(parseFloat, false));
this.setProperty(scope, 'isNaN',
this.createNativeFunction(isNaN, false));
this.setProperty(scope, 'isFinite',
this.createNativeFunction(isFinite, false));
var strFunctions = [
[escape, 'escape'], [unescape, 'unescape'],
[decodeURI, 'decodeURI'], [decodeURIComponent, 'decodeURIComponent'],
[encodeURI, 'encodeURI'], [encodeURIComponent, 'encodeURIComponent']
];
for (var i = 0; i < strFunctions.length; i++) {
var wrapper = (function(nativeFunc) {
return function(str) {
try {
return nativeFunc(str);
} catch (e) {
// decodeURI('%xy') will throw an error. Catch and rethrow.
thisInterpreter.throwException(thisInterpreter.URI_ERROR, e.message);
}
};
})(strFunctions[i][0]);
this.setProperty(scope, strFunctions[i][1],
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
}
// Preserve publicly properties from being pruned/renamed by JS compilers.
// Add others as needed.
this['OBJECT'] = this.OBJECT; this['OBJECT_PROTO'] = this.OBJECT_PROTO;
this['FUNCTION'] = this.FUNCTION; this['FUNCTION_PROTO'] = this.FUNCTION_PROTO;
this['ARRAY'] = this.ARRAY; this['ARRAY_PROTO'] = this.ARRAY_PROTO;
this['REGEXP'] = this.REGEXP; this['REGEXP_PROTO'] = this.REGEXP_PROTO;
this['DATE'] = this.DATE; this['DATE_PROTO'] = this.DATE_PROTO;
// The following properties are obsolete. Do not use.
this['UNDEFINED'] = undefined; this['NULL'] = null; this['NAN'] = NaN;
this['TRUE'] = true; this['FALSE'] = false; this['STRING_EMPTY'] = '';
this['NUMBER_ZERO'] = 0; this['NUMBER_ONE'] = 1;
// Run any user-provided initialization.
if (this.initFunc_) {
this.initFunc_(this, scope);
}
};
/**
* Initialize the Function class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initFunction = function(scope) {
var thisInterpreter = this;
var wrapper;
var identifierRegexp = /^[A-Za-z_$][\w$]*$/;
// Function constructor.
wrapper = function(var_args) {
if (thisInterpreter.calledWithNew()) {
// Called as new Function().
var newFunc = this;
} else {
// Called as Function().
var newFunc =
thisInterpreter.createObjectProto(thisInterpreter.FUNCTION_PROTO);
}
if (arguments.length) {
var code = String(arguments[arguments.length - 1]);
} else {
var code = '';
}
var argsStr = Array.prototype.slice.call(arguments, 0, -1).join(',').trim();
if (argsStr) {
var args = argsStr.split(/\s*,\s*/);
for (var i = 0; i < args.length; i++) {
var name = args[i];
if (!identifierRegexp.test(name)) {
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid function argument: ' + name);
}
}
argsStr = args.join(', ');
}
// Interestingly, the scope for constructed functions is the global scope,
// even if they were constructed in some other scope.
newFunc.parentScope = thisInterpreter.global;
// Acorn needs to parse code in the context of a function or else 'return'
// statements will be syntax errors.
try {
var ast = _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"]('(function(' + argsStr + ') {' + code + '})',
Interpreter.PARSE_OPTIONS);
} catch (e) {
// Acorn threw a SyntaxError. Rethrow as a trappable error.
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid code: ' + e.message);
}
if (ast['body'].length !== 1) {
// Function('a', 'return a + 6;}; {alert(1);');
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid code in function body.');
}
newFunc.node = ast['body'][0]['expression'];
thisInterpreter.setProperty(newFunc, 'length', newFunc.node['length'],
Interpreter.READONLY_DESCRIPTOR);
return newFunc;
};
wrapper.id = this.functionCounter_++;
this.FUNCTION = this.createObjectProto(this.FUNCTION_PROTO);
this.setProperty(scope, 'Function', this.FUNCTION);
// Manually setup type and prototype because createObj doesn't recognize
// this object as a function (this.FUNCTION did not exist).
this.setProperty(this.FUNCTION, 'prototype', this.FUNCTION_PROTO);
this.FUNCTION.nativeFunc = wrapper;
// Configure Function.prototype.
this.setProperty(this.FUNCTION_PROTO, 'constructor', this.FUNCTION,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.FUNCTION_PROTO.nativeFunc = function() {};
this.FUNCTION_PROTO.nativeFunc.id = this.functionCounter_++;
this.setProperty(this.FUNCTION_PROTO, 'length', 0,
Interpreter.READONLY_DESCRIPTOR);
var boxThis = function(value) {
// In non-strict mode 'this' must be an object.
if ((!value || !value.isObject) && !thisInterpreter.getScope().strict) {
if (value === undefined || value === null) {
// 'Undefined' and 'null' are changed to global object.
value = thisInterpreter.global;
} else {
// Primitives must be boxed in non-strict mode.
var box = thisInterpreter.createObjectProto(
thisInterpreter.getPrototype(value));
box.data = value;
value = box;
}
}
return value;
};
wrapper = function(thisArg, args) {
var state =
thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1];
// Rewrite the current 'CallExpression' to apply a different function.
state.func_ = this;
// Assign the 'this' object.
state.funcThis_ = boxThis(thisArg);
// Bind any provided arguments.
state.arguments_ = [];
if (args !== null && args !== undefined) {
if (args.isObject) {
state.arguments_ = thisInterpreter.arrayPseudoToNative(args);
} else {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'CreateListFromArrayLike called on non-object');
}
}
state.doneExec_ = false;
};
this.setNativeFunctionPrototype(this.FUNCTION, 'apply', wrapper);
wrapper = function(thisArg /*, var_args */) {
var state =
thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1];
// Rewrite the current 'CallExpression' to call a different function.
state.func_ = this;
// Assign the 'this' object.
state.funcThis_ = boxThis(thisArg);
// Bind any provided arguments.
state.arguments_ = [];
for (var i = 1; i < arguments.length; i++) {
state.arguments_.push(arguments[i]);
}
state.doneExec_ = false;
};
this.setNativeFunctionPrototype(this.FUNCTION, 'call', wrapper);
this.polyfills_.push(
// Polyfill copied from:
// developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
"Object.defineProperty(Function.prototype, 'bind',",
"{configurable: true, writable: true, value:",
"function(oThis) {",
"if (typeof this !== 'function') {",
"throw TypeError('What is trying to be bound is not callable');",
"}",
"var aArgs = Array.prototype.slice.call(arguments, 1),",
"fToBind = this,",
"fNOP = function() {},",
"fBound = function() {",
"return fToBind.apply(this instanceof fNOP",
"? this",
": oThis,",
"aArgs.concat(Array.prototype.slice.call(arguments)));",
"};",
"if (this.prototype) {",
"fNOP.prototype = this.prototype;",
"}",
"fBound.prototype = new fNOP();",
"return fBound;",
"}",
"});",
"");
// Function has no parent to inherit from, so it needs its own mandatory
// toString and valueOf functions.
wrapper = function() {
return this.toString();
};
this.setNativeFunctionPrototype(this.FUNCTION, 'toString', wrapper);
this.setProperty(this.FUNCTION, 'toString',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function() {
return this.valueOf();
};
this.setNativeFunctionPrototype(this.FUNCTION, 'valueOf', wrapper);
this.setProperty(this.FUNCTION, 'valueOf',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
};
/**
* Initialize the Object class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initObject = function(scope) {
var thisInterpreter = this;
var wrapper;
// Object constructor.
wrapper = function(value) {
if (value === undefined || value === null) {
// Create a new object.
if (thisInterpreter.calledWithNew()) {
// Called as new Object().
return this;
} else {
// Called as Object().
return thisInterpreter.createObjectProto(thisInterpreter.OBJECT_PROTO);
}
}
if (!value.isObject) {
// Wrap the value as an object.
var box = thisInterpreter.createObjectProto(
thisInterpreter.getPrototype(value));
box.data = value;
return box;
}
// Return the provided object.
return value;
};
this.OBJECT = this.createNativeFunction(wrapper, true);
// Throw away the created prototype and use the root prototype.
this.setProperty(this.OBJECT, 'prototype', this.OBJECT_PROTO);
this.setProperty(this.OBJECT_PROTO, 'constructor', this.OBJECT,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(scope, 'Object', this.OBJECT);
/**
* Checks if the provided value is null or undefined.
* If so, then throw an error in the call stack.
* @param {Interpreter.Value} value Value to check.
*/
var throwIfNullUndefined = function(value) {
if (value === undefined || value === null) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
"Cannot convert '" + value + "' to object");
}
};
// Static methods on Object.
wrapper = function(obj) {
throwIfNullUndefined(obj);
var props = obj.isObject ? obj.properties : obj;
return thisInterpreter.arrayNativeToPseudo(
Object.getOwnPropertyNames(props));
};
this.setProperty(this.OBJECT, 'getOwnPropertyNames',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function(obj) {
throwIfNullUndefined(obj);
if (obj.isObject) {
obj = obj.properties;
}
return thisInterpreter.arrayNativeToPseudo(Object.keys(obj));
};
this.setProperty(this.OBJECT, 'keys',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function(proto) {
// Support for the second argument is the responsibility of a polyfill.
if (proto === null) {
return thisInterpreter.createObjectProto(null);
}
if (proto === undefined || !proto.isObject) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object prototype may only be an Object or null');
}
return thisInterpreter.createObjectProto(proto);
};
this.setProperty(this.OBJECT, 'create',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Add a polyfill to handle create's second argument.
this.polyfills_.push(
"(function() {",
"var create_ = Object.create;",
"Object.create = function(proto, props) {",
"var obj = create_(proto);",
"props && Object.defineProperties(obj, props);",
"return obj;",
"};",
"})();",
"");
wrapper = function(obj, prop, descriptor) {
prop = String(prop);
if (!obj || !obj.isObject) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object.defineProperty called on non-object');
}
if (!descriptor || !descriptor.isObject) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Property description must be an object');
}
if (!obj.properties[prop] && obj.preventExtensions) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
"Can't define property '" + prop + "', object is not extensible");
}
// The polyfill guarantees no inheritance and no getter functions.
// Therefore the descriptor properties map is the native object needed.
thisInterpreter.setProperty(obj, prop, Interpreter.VALUE_IN_DESCRIPTOR,
descriptor.properties);
return obj;
};
this.setProperty(this.OBJECT, 'defineProperty',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.polyfills_.push(
// Flatten the descriptor to remove any inheritance or getter functions.
"(function() {",
"var defineProperty_ = Object.defineProperty;",
"Object.defineProperty = function(obj, prop, d1) {",
"var d2 = {};",
"if ('configurable' in d1) d2.configurable = d1.configurable;",
"if ('enumerable' in d1) d2.enumerable = d1.enumerable;",
"if ('writable' in d1) d2.writable = d1.writable;",
"if ('value' in d1) d2.value = d1.value;",
"if ('get' in d1) d2.get = d1.get;",
"if ('set' in d1) d2.set = d1.set;",
"return defineProperty_(obj, prop, d2);",
"};",
"})();",
"Object.defineProperty(Object, 'defineProperties',",
"{configurable: true, writable: true, value:",
"function(obj, props) {",
"var keys = Object.keys(props);",
"for (var i = 0; i < keys.length; i++) {",
"Object.defineProperty(obj, keys[i], props[keys[i]]);",
"}",
"return obj;",
"}",
"});",
"");
wrapper = function(obj, prop) {
if (!obj || !obj.isObject) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object.getOwnPropertyDescriptor called on non-object');
}
prop = String(prop);
if (!(prop in obj.properties)) {
return undefined;
}
var descriptor = Object.getOwnPropertyDescriptor(obj.properties, prop);
var getter = obj.getter[prop];
var setter = obj.setter[prop];
if (getter || setter) {
descriptor.get = getter;
descriptor.set = setter;
delete descriptor.value;
delete descriptor.writable;
}
// Preserve value, but remove it for the nativeToPseudo call.
var value = descriptor.value;
var hasValue = 'value' in descriptor;
delete descriptor.value;
var pseudoDescriptor = thisInterpreter.nativeToPseudo(descriptor);
if (hasValue) {
thisInterpreter.setProperty(pseudoDescriptor, 'value', value);
}
return pseudoDescriptor;
};
this.setProperty(this.OBJECT, 'getOwnPropertyDescriptor',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function(obj) {
throwIfNullUndefined(obj);
return thisInterpreter.getPrototype(obj);
};
this.setProperty(this.OBJECT, 'getPrototypeOf',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function(obj) {
return Boolean(obj) && !obj.preventExtensions;
};
this.setProperty(this.OBJECT, 'isExtensible',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function(obj) {
if (obj && obj.isObject) {
obj.preventExtensions = true;
}
return obj;
};
this.setProperty(this.OBJECT, 'preventExtensions',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on Object.
this.setNativeFunctionPrototype(this.OBJECT, 'toString',
Interpreter.Object.prototype.toString);
this.setNativeFunctionPrototype(this.OBJECT, 'toLocaleString',
Interpreter.Object.prototype.toString);
this.setNativeFunctionPrototype(this.OBJECT, 'valueOf',
Interpreter.Object.prototype.valueOf);
wrapper = function(prop) {
throwIfNullUndefined(this);
if (!this.isObject) {
return this.hasOwnProperty(prop);
}
return String(prop) in this.properties;
};
this.setNativeFunctionPrototype(this.OBJECT, 'hasOwnProperty', wrapper);
wrapper = function(prop) {
throwIfNullUndefined(this);
if (!this.isObject) {
return this.propertyIsEnumerable(prop);
}
return Object.prototype.propertyIsEnumerable.call(this.properties, prop);
};
this.setNativeFunctionPrototype(this.OBJECT, 'propertyIsEnumerable', wrapper);
wrapper = function(obj) {
while (true) {
// Note, circular loops shouldn't be possible.
obj = thisInterpreter.getPrototype(obj);
if (!obj) {
// No parent; reached the top.
return false;
}
if (obj === this) {
return true;
}
}
};
this.setNativeFunctionPrototype(this.OBJECT, 'isPrototypeOf', wrapper);
};
/**
* Initialize the Array class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initArray = function(scope) {
var thisInterpreter = this;
var wrapper;
// Array constructor.
wrapper = function(var_args) {
if (thisInterpreter.calledWithNew()) {
// Called as new Array().
var newArray = this;
} else {
// Called as Array().
var newArray =
thisInterpreter.createObjectProto(thisInterpreter.ARRAY_PROTO);
}
var first = arguments[0];
if (arguments.length === 1 && typeof first === 'number') {
if (isNaN(Interpreter.legalArrayLength(first))) {
thisInterpreter.throwException(thisInterpreter.RANGE_ERROR,
'Invalid array length');
}
newArray.properties.length = first;
} else {
for (var i = 0; i < arguments.length; i++) {
newArray.properties[i] = arguments[i];
}
newArray.properties.length = i;
}
return newArray;
};
this.ARRAY = this.createNativeFunction(wrapper, true);
this.ARRAY_PROTO = this.ARRAY.properties['prototype'];
this.setProperty(scope, 'Array', this.ARRAY);
// Static methods on Array.
wrapper = function(obj) {
return obj && obj.class === 'Array';
};
this.setProperty(this.ARRAY, 'isArray',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on Array.
wrapper = function() {
return Array.prototype.pop.call(this.properties);
};
this.setNativeFunctionPrototype(this.ARRAY, 'pop', wrapper);
wrapper = function(var_args) {
return Array.prototype.push.apply(this.properties, arguments);
};
this.setNativeFunctionPrototype(this.ARRAY, 'push', wrapper);
wrapper = function() {
return Array.prototype.shift.call(this.properties);
};
this.setNativeFunctionPrototype(this.ARRAY, 'shift', wrapper);
wrapper = function(var_args) {
return Array.prototype.unshift.apply(this.properties, arguments);
};
this.setNativeFunctionPrototype(this.ARRAY, 'unshift', wrapper);
wrapper = function() {
Array.prototype.reverse.call(this.properties);
return this;
};
this.setNativeFunctionPrototype(this.ARRAY, 'reverse', wrapper);
wrapper = function(index, howmany /*, var_args*/) {
var list = Array.prototype.splice.apply(this.properties, arguments);
return thisInterpreter.arrayNativeToPseudo(list);
};
this.setNativeFunctionPrototype(this.ARRAY, 'splice', wrapper);
wrapper = function(opt_begin, opt_end) {
var list = Array.prototype.slice.call(this.properties, opt_begin, opt_end);
return thisInterpreter.arrayNativeToPseudo(list);
};
this.setNativeFunctionPrototype(this.ARRAY, 'slice', wrapper);
wrapper = function(opt_separator) {
return Array.prototype.join.call(this.properties, opt_separator);
};
this.setNativeFunctionPrototype(this.ARRAY, 'join', wrapper);
wrapper = function(var_args) {
var list = [];
var length = 0;
// Start by copying the current array.
var iLength = thisInterpreter.getProperty(this, 'length');
for (var i = 0; i < iLength; i++) {
if (thisInterpreter.hasProperty(this, i)) {
var element = thisInterpreter.getProperty(this, i);
list[length] = element;
}
length++;
}
// Loop through all arguments and copy them in.
for (var i = 0; i < arguments.length; i++) {
var value = arguments[i];
if (thisInterpreter.isa(value, thisInterpreter.ARRAY)) {
var jLength = thisInterpreter.getProperty(value, 'length');
for (var j = 0; j < jLength; j++) {
if (thisInterpreter.hasProperty(value, j)) {
list[length] = thisInterpreter.getProperty(value, j);
}
length++;
}
} else {
list[length] = value;
}
}
return thisInterpreter.arrayNativeToPseudo(list);
};
this.setNativeFunctionPrototype(this.ARRAY, 'concat', wrapper);
wrapper = function(searchElement, opt_fromIndex) {
return Array.prototype.indexOf.apply(this.properties, arguments);
};
this.setNativeFunctionPrototype(this.ARRAY, 'indexOf', wrapper);
wrapper = function(searchElement, opt_fromIndex) {
return Array.prototype.lastIndexOf.apply(this.properties, arguments);
};
this.setNativeFunctionPrototype(this.ARRAY, 'lastIndexOf', wrapper);
wrapper = function() {
Array.prototype.sort.call(this.properties);
return this;
};
this.setNativeFunctionPrototype(this.ARRAY, 'sort', wrapper);
this.polyfills_.push(
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/every
"Object.defineProperty(Array.prototype, 'every',",
"{configurable: true, writable: true, value:",
"function(callbackfn, thisArg) {",
"if (!this || typeof callbackfn !== 'function') throw TypeError();",
"var T, k;",
"var O = Object(this);",
"var len = O.length >>> 0;",
"if (arguments.length > 1) T = thisArg;",
"k = 0;",
"while (k < len) {",
"if (k in O && !callbackfn.call(T, O[k], k, O)) return false;",
"k++;",
"}",
"return true;",
"}",
"});",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
"Object.defineProperty(Array.prototype, 'filter',",
"{configurable: true, writable: true, value:",
"function(fun/*, thisArg*/) {",
"if (this === void 0 || this === null || typeof fun !== 'function') throw TypeError();",
"var t = Object(this);",
"var len = t.length >>> 0;",
"var res = [];",
"var thisArg = arguments.length >= 2 ? arguments[1] : void 0;",
"for (var i = 0; i < len; i++) {",
"if (i in t) {",
"var val = t[i];",
"if (fun.call(thisArg, val, i, t)) res.push(val);",
"}",
"}",
"return res;",
"}",
"});",
// Polyfill copied from:
// https://tc39.github.io/ecma262/#sec-array.prototype.find
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
"if (!Array.prototype.find) {",
"Object.defineProperty(Array.prototype, 'find', {",
"value: function(predicate) {",
"if (this == null) {",
"throw new TypeError('\"this\" is null or not defined');",
"}",
"var o = Object(this);",
"var len = o.length >>> 0;",
"if (typeof predicate !== 'function') {",
"throw new TypeError('predicate must be a function');",
"}",
"var thisArg = arguments[1];",
"var k = 0;",
"while (k < len) {",
"var kValue = o[k];",
"if (predicate.call(thisArg, kValue, k, o)) {",
"return kValue;",
"}",
"k++;",
"}",
"return undefined;",
"},",
"configurable: true,",
"writable: true",
"});",
"}",
// Poly fill copied from:
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
"if (!Array.prototype.findIndex) {",
"Object.defineProperty(Array.prototype, 'findIndex', {",
"value: function(predicate) {",
"if (this == null) {",
"throw new TypeError('\"this\" is null or not defined');",
"}",
"var o = Object(this);",
"var len = o.length >>> 0;",
"if (typeof predicate !== 'function') {",
"throw new TypeError('predicate must be a function');",
"}",
"var thisArg = arguments[1];",
"var k = 0;",
"while (k < len) {",
"var kValue = o[k];",
"if (predicate.call(thisArg, kValue, k, o)) {",
"return k;",
"}",
"k++;",
"}",
"return -1;",
"},",
"configurable: true,",
"writable: true",
"});",
"}",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
"Object.defineProperty(Array.prototype, 'forEach',",
"{configurable: true, writable: true, value:",
"function(callback, thisArg) {",
"if (!this || typeof callback !== 'function') throw TypeError();",
"var T, k;",
"var O = Object(this);",
"var len = O.length >>> 0;",
"if (arguments.length > 1) T = thisArg;",
"k = 0;",
"while (k < len) {",
"if (k in O) callback.call(T, O[k], k, O);",
"k++;",
"}",
"}",
"});",
// Polyfill copied from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill
"Object.defineProperty(Array.prototype, 'includes', {",
"value: function(searchElement, fromIndex) {",
"if (this == null) {",
"throw new TypeError('\"this\" is null or not defined');",
"}",
"// 1. Let O be ? ToObject(this value).",
"var o = Object(this);",
"// 2. Let len be ? ToLength(? Get(O, \"length\")).",
"var len = o.length >>> 0;",
"// 3. If len is 0, return false.",
"if (len === 0) {",
"return false;",
"}",
"// 4. Let n be ? ToInteger(fromIndex).",
"// (If fromIndex is undefined, this step produces the value 0.)",
"var n = fromIndex | 0;",
"// 5. If n ≥ 0, then",
"// a. Let k be n.",
"// 6. Else n < 0,",
"// a. Let k be len + n.",
"// b. If k < 0, let k be 0.",
"var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);",
"function sameValueZero(x, y) {",
"return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));",
"}",
"// 7. Repeat, while k < len",
"while (k < len) {",
"// a. Let elementK be the result of ? Get(O, ! ToString(k)).",
"// b. If SameValueZero(searchElement, elementK) is true, return true.",
"if (sameValueZero(o[k], searchElement)) {",
"return true;",
"}",
"// c. Increase k by 1. ",
"k++;",
"}",
"// 8. Return false",
"return false;",
"}",
"});",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
"Object.defineProperty(Array.prototype, 'map',",
"{configurable: true, writable: true, value:",
"function(callback, thisArg) {",
"if (!this || typeof callback !== 'function') new TypeError;",
"var T, A, k;",
"var O = Object(this);",
"var len = O.length >>> 0;",
"if (arguments.length > 1) T = thisArg;",
"A = new Array(len);",
"k = 0;",
"while (k < len) {",
"if (k in O) A[k] = callback.call(T, O[k], k, O);",
"k++;",
"}",
"return A;",
"}",
"});",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
"Object.defineProperty(Array.prototype, 'reduce',",
"{configurable: true, writable: true, value:",
"function(callback /*, initialValue*/) {",
"if (!this || typeof callback !== 'function') throw TypeError();",
"var t = Object(this), len = t.length >>> 0, k = 0, value;",
"if (arguments.length === 2) {",
"value = arguments[1];",
"} else {",
"while (k < len && !(k in t)) k++;",
"if (k >= len) {",
"throw TypeError('Reduce of empty array with no initial value');",
"}",
"value = t[k++];",
"}",
"for (; k < len; k++) {",
"if (k in t) value = callback(value, t[k], k, t);",
"}",
"return value;",
"}",
"});",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
"Object.defineProperty(Array.prototype, 'reduceRight',",
"{configurable: true, writable: true, value:",
"function(callback /*, initialValue*/) {",
"if (null === this || 'undefined' === typeof this || 'function' !== typeof callback) throw TypeError();",
"var t = Object(this), len = t.length >>> 0, k = len - 1, value;",
"if (arguments.length >= 2) {",
"value = arguments[1];",
"} else {",
"while (k >= 0 && !(k in t)) k--;",
"if (k < 0) {",
"throw TypeError('Reduce of empty array with no initial value');",
"}",
"value = t[k--];",
"}",
"for (; k >= 0; k--) {",
"if (k in t) value = callback(value, t[k], k, t);",
"}",
"return value;",
"}",
"});",
// Polyfill copied from:
// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/some
"Object.defineProperty(Array.prototype, 'some',",
"{configurable: true, writable: true, value:",
"function(fun/*, thisArg*/) {",
"if (!this || typeof fun !== 'function') throw TypeError();",
"var t = Object(this);",
"var len = t.length >>> 0;",
"var thisArg = arguments.length >= 2 ? arguments[1] : void 0;",
"for (var i = 0; i < len; i++) {",
"if (i in t && fun.call(thisArg, t[i], i, t)) {",
"return true;",
"}",
"}",
"return false;",
"}",
"});",
"(function() {",
"var sort_ = Array.prototype.sort;",
"Array.prototype.sort = function(opt_comp) {",
// Fast native sort.
"if (typeof opt_comp !== 'function') {",
"return sort_.call(this);",
"}",
// Slow bubble sort.
"for (var i = 0; i < this.length; i++) {",
"var changes = 0;",
"for (var j = 0; j < this.length - i - 1; j++) {",
"if (opt_comp(this[j], this[j + 1]) > 0) {",
"var swap = this[j];",
"this[j] = this[j + 1];",
"this[j + 1] = swap;",
"changes++;",
"}",
"}",
"if (!changes) break;",
"}",
"return this;",
"};",
"})();",
"Object.defineProperty(Array.prototype, 'toLocaleString',",
"{configurable: true, writable: true, value:",
"function() {",
"var out = [];",
"for (var i = 0; i < this.length; i++) {",
"out[i] = (this[i] === null || this[i] === undefined) ? '' : this[i].toLocaleString();",
"}",
"return out.join(',');",
"}",
"});",
"");
};
/**
* Initialize the String class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initString = function(scope) {
var thisInterpreter = this;
var wrapper;
// String constructor.
wrapper = function(value) {
value = String(value);
if (thisInterpreter.calledWithNew()) {
// Called as new String().
this.data = value;
return this;
} else {
// Called as String().
return value;
}
};
this.STRING = this.createNativeFunction(wrapper, true);
this.setProperty(scope, 'String', this.STRING);
// Static methods on String.
this.setProperty(this.STRING, 'fromCharCode',
this.createNativeFunction(String.fromCharCode, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on String.
// Methods with exclusively primitive arguments.
var functions = ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf',
'slice', 'substr', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase',
'toLowerCase', 'toUpperCase', 'trim'];
for (var i = 0; i < functions.length; i++) {
this.setNativeFunctionPrototype(this.STRING, functions[i],
String.prototype[functions[i]]);
}
wrapper = function(compareString, locales, options) {
locales = locales ? thisInterpreter.pseudoToNative(locales) : undefined;
options = options ? thisInterpreter.pseudoToNative(options) : undefined;
return String(this).localeCompare(compareString, locales, options);
};
this.setNativeFunctionPrototype(this.STRING, 'localeCompare', wrapper);
wrapper = function(separator, limit) {
if (thisInterpreter.isa(separator, thisInterpreter.REGEXP)) {
separator = separator.data;
}
var jsList = String(this).split(separator, limit);
return thisInterpreter.arrayNativeToPseudo(jsList);
};
this.setNativeFunctionPrototype(this.STRING, 'split', wrapper);
wrapper = function(regexp) {
if (thisInterpreter.isa(regexp, thisInterpreter.REGEXP)) {
regexp = regexp.data;
}
var m = String(this).match(regexp);
return m && thisInterpreter.arrayNativeToPseudo(m);
};
this.setNativeFunctionPrototype(this.STRING, 'match', wrapper);
wrapper = function(regexp) {
if (thisInterpreter.isa(regexp, thisInterpreter.REGEXP)) {
regexp = regexp.data;
}
return String(this).search(regexp);
};
this.setNativeFunctionPrototype(this.STRING, 'search', wrapper);
wrapper = function(substr, newSubstr) {
// Support for function replacements is the responsibility of a polyfill.
if (thisInterpreter.isa(substr, thisInterpreter.REGEXP)) {
substr = substr.data;
}
return String(this).replace(substr, newSubstr);
};
this.setNativeFunctionPrototype(this.STRING, 'replace', wrapper);
// Add a polyfill to handle replace's second argument being a function.
this.polyfills_.push(
"(function() {",
"var replace_ = String.prototype.replace;",
"String.prototype.replace = function(substr, newSubstr) {",
"if (typeof newSubstr !== 'function') {",
// string.replace(string|regexp, string)
"return replace_.call(this, substr, newSubstr);",
"}",
"var str = this;",
"if (substr instanceof RegExp) {", // string.replace(regexp, function)
"var subs = [];",
"var m = substr.exec(str);",
"while (m) {",
"m.push(m.index, str);",
"var inject = newSubstr.apply(null, m);",
"subs.push([m.index, m[0].length, inject]);",
"m = substr.global ? substr.exec(str) : null;",
"}",
"for (var i = subs.length - 1; i >= 0; i--) {",
"str = str.substring(0, subs[i][0]) + subs[i][2] + " +
"str.substring(subs[i][0] + subs[i][1]);",
"}",
"} else {", // string.replace(string, function)
"var i = str.indexOf(substr);",
"if (i !== -1) {",
"var inject = newSubstr(str.substr(i, substr.length), i, str);",
"str = str.substring(0, i) + inject + " +
"str.substring(i + substr.length);",
"}",
"}",
"return str;",
"};",
"})();",
// Polyfill copied from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
"if (!String.prototype.endsWith) {",
"String.prototype.endsWith = function(search, this_len) {",
"if (this_len === undefined || this_len > this.length) {",
"this_len = this.length;",
"}",
"return this.substring(this_len - search.length, this_len) === search;",
"};",
"}",
//Polyfill copied from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
"if (!String.prototype.includes) {",
"String.prototype.includes = function(search, start) {",
"'use strict';",
"if (typeof start !== 'number') {",
"start = 0;",
"}",
" ",
"if (start + search.length > this.length) {",
"return false;",
"} else {",
"return this.indexOf(search, start) !== -1;",
"}",
"};",
"}",
// Polyfill copied from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
"if (!String.prototype.startsWith) {",
"String.prototype.startsWith = function(search, pos) {",
"return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;",
"};",
"}",
"");
};
/**
* Initialize the Boolean class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initBoolean = function(scope) {
var thisInterpreter = this;
var wrapper;
// Boolean constructor.
wrapper = function(value) {
value = Boolean(value);
if (thisInterpreter.calledWithNew()) {
// Called as new Boolean().
this.data = value;
return this;
} else {
// Called as Boolean().
return value;
}
};
this.BOOLEAN = this.createNativeFunction(wrapper, true);
this.setProperty(scope, 'Boolean', this.BOOLEAN);
};
/**
* Initialize the Number class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initNumber = function(scope) {
var thisInterpreter = this;
var wrapper;
// Number constructor.
wrapper = function(value) {
value = Number(value);
if (thisInterpreter.calledWithNew()) {
// Called as new Number().
this.data = value;
return this;
} else {
// Called as Number().
return value;
}
};
this.NUMBER = this.createNativeFunction(wrapper, true);
this.setProperty(scope, 'Number', this.NUMBER);
var numConsts = ['MAX_VALUE', 'MIN_VALUE', 'NaN', 'NEGATIVE_INFINITY',
'POSITIVE_INFINITY'];
for (var i = 0; i < numConsts.length; i++) {
this.setProperty(this.NUMBER, numConsts[i], Number[numConsts[i]],
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
}
// Instance methods on Number.
wrapper = function(fractionDigits) {
try {
return Number(this).toExponential(fractionDigits);
} catch (e) {
// Throws if fractionDigits isn't within 0-20.
thisInterpreter.throwException(thisInterpreter.ERROR, e.message);
}
};
this.setNativeFunctionPrototype(this.NUMBER, 'toExponential', wrapper);
wrapper = function(digits) {
try {
return Number(this).toFixed(digits);
} catch (e) {
// Throws if digits isn't within 0-20.
thisInterpreter.throwException(thisInterpreter.ERROR, e.message);
}
};
this.setNativeFunctionPrototype(this.NUMBER, 'toFixed', wrapper);
wrapper = function(precision) {
try {
return Number(this).toPrecision(precision);
} catch (e) {
// Throws if precision isn't within range (depends on implementation).
thisInterpreter.throwException(thisInterpreter.ERROR, e.message);
}
};
this.setNativeFunctionPrototype(this.NUMBER, 'toPrecision', wrapper);
wrapper = function(radix) {
try {
return Number(this).toString(radix);
} catch (e) {
// Throws if radix isn't within 2-36.
thisInterpreter.throwException(thisInterpreter.ERROR, e.message);
}
};
this.setNativeFunctionPrototype(this.NUMBER, 'toString', wrapper);
wrapper = function(locales, options) {
locales = locales ? thisInterpreter.pseudoToNative(locales) : undefined;
options = options ? thisInterpreter.pseudoToNative(options) : undefined;
return Number(this).toLocaleString(locales, options);
};
this.setNativeFunctionPrototype(this.NUMBER, 'toLocaleString', wrapper);
};
/**
* Initialize the Date class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initDate = function(scope) {
var thisInterpreter = this;
var wrapper;
// Date constructor.
wrapper = function(value, var_args) {
if (!thisInterpreter.calledWithNew()) {
// Called as Date().
// Calling Date() as a function returns a string, no arguments are heeded.
return Date();
}
// Called as new Date().
var args = [null].concat(Array.from(arguments));
this.data = new (Function.prototype.bind.apply(Date, args));
return this;
};
this.DATE = this.createNativeFunction(wrapper, true);
this.DATE_PROTO = this.DATE.properties['prototype'];
this.setProperty(scope, 'Date', this.DATE);
// Static methods on Date.
this.setProperty(this.DATE, 'now', this.createNativeFunction(Date.now, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.DATE, 'parse',
this.createNativeFunction(Date.parse, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.DATE, 'UTC', this.createNativeFunction(Date.UTC, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on Date.
var functions = ['getDate', 'getDay', 'getFullYear', 'getHours',
'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',
'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',
'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',
'getUTCSeconds', 'getYear',
'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate',
'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes',
'setUTCMonth', 'setUTCSeconds', 'setYear',
'toDateString', 'toISOString', 'toJSON', 'toGMTString',
'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString',
'toTimeString', 'toUTCString'];
for (var i = 0; i < functions.length; i++) {
wrapper = (function(nativeFunc) {
return function(var_args) {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = thisInterpreter.pseudoToNative(arguments[i]);
}
return this.data[nativeFunc].apply(this.data, args);
};
})(functions[i]);
this.setNativeFunctionPrototype(this.DATE, functions[i], wrapper);
}
};
/**
* Initialize Regular Expression object.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initRegExp = function(scope) {
var thisInterpreter = this;
var wrapper;
// RegExp constructor.
wrapper = function(pattern, flags) {
if (thisInterpreter.calledWithNew()) {
// Called as new RegExp().
var rgx = this;
} else {
// Called as RegExp().
var rgx = thisInterpreter.createObjectProto(thisInterpreter.REGEXP_PROTO);
}
pattern = pattern ? pattern.toString() : '';
flags = flags ? flags.toString() : '';
thisInterpreter.populateRegExp(rgx, new RegExp(pattern, flags));
return rgx;
};
this.REGEXP = this.createNativeFunction(wrapper, true);
this.REGEXP_PROTO = this.REGEXP.properties['prototype'];
this.setProperty(scope, 'RegExp', this.REGEXP);
this.setProperty(this.REGEXP.properties['prototype'], 'global', undefined,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.REGEXP.properties['prototype'], 'ignoreCase', undefined,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.REGEXP.properties['prototype'], 'multiline', undefined,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.REGEXP.properties['prototype'], 'source', '(?:)',
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
wrapper = function(str) {
return this.data.test(str);
};
this.setNativeFunctionPrototype(this.REGEXP, 'test', wrapper);
wrapper = function(str) {
str = str.toString();
// Get lastIndex from wrapped regex, since this is settable.
this.data.lastIndex =
Number(thisInterpreter.getProperty(this, 'lastIndex'));
var match = this.data.exec(str);
thisInterpreter.setProperty(this, 'lastIndex', this.data.lastIndex);
if (match) {
var result =
thisInterpreter.createObjectProto(thisInterpreter.ARRAY_PROTO);
for (var i = 0; i < match.length; i++) {
thisInterpreter.setProperty(result, i, match[i]);
}
// match has additional properties.
thisInterpreter.setProperty(result, 'index', match.index);
thisInterpreter.setProperty(result, 'input', match.input);
return result;
}
return null;
};
this.setNativeFunctionPrototype(this.REGEXP, 'exec', wrapper);
};
/**
* Initialize the Error class.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initError = function(scope) {
var thisInterpreter = this;
// Error constructor.
this.ERROR = this.createNativeFunction(function(opt_message) {
if (thisInterpreter.calledWithNew()) {
// Called as new Error().
var newError = this;
} else {
// Called as Error().
var newError = thisInterpreter.createObject(thisInterpreter.ERROR);
}
if (opt_message) {
thisInterpreter.setProperty(newError, 'message', String(opt_message),
Interpreter.NONENUMERABLE_DESCRIPTOR);
}
return newError;
}, true);
this.setProperty(scope, 'Error', this.ERROR);
this.setProperty(this.ERROR.properties['prototype'], 'message', '',
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.ERROR.properties['prototype'], 'name', 'Error',
Interpreter.NONENUMERABLE_DESCRIPTOR);
var createErrorSubclass = function(name) {
var constructor = thisInterpreter.createNativeFunction(
function(opt_message) {
if (thisInterpreter.calledWithNew()) {
// Called as new XyzError().
var newError = this;
} else {
// Called as XyzError().
var newError = thisInterpreter.createObject(constructor);
}
if (opt_message) {
thisInterpreter.setProperty(newError, 'message',
String(opt_message), Interpreter.NONENUMERABLE_DESCRIPTOR);
}
return newError;
}, true);
thisInterpreter.setProperty(constructor, 'prototype',
thisInterpreter.createObject(thisInterpreter.ERROR));
thisInterpreter.setProperty(constructor.properties['prototype'], 'name',
name, Interpreter.NONENUMERABLE_DESCRIPTOR);
thisInterpreter.setProperty(scope, name, constructor);
return constructor;
};
this.EVAL_ERROR = createErrorSubclass('EvalError');
this.RANGE_ERROR = createErrorSubclass('RangeError');
this.REFERENCE_ERROR = createErrorSubclass('ReferenceError');
this.SYNTAX_ERROR = createErrorSubclass('SyntaxError');
this.TYPE_ERROR = createErrorSubclass('TypeError');
this.URI_ERROR = createErrorSubclass('URIError');
};
/**
* Initialize Math object.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initMath = function(scope) {
var thisInterpreter = this;
var myMath = this.createObjectProto(this.OBJECT_PROTO);
this.setProperty(scope, 'Math', myMath);
var mathConsts = ['E', 'LN2', 'LN10', 'LOG2E', 'LOG10E', 'PI',
'SQRT1_2', 'SQRT2'];
for (var i = 0; i < mathConsts.length; i++) {
this.setProperty(myMath, mathConsts[i], Math[mathConsts[i]],
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
}
var numFunctions = ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
'exp', 'floor', 'log', 'max', 'min', 'pow', 'random',
'round', 'sin', 'sqrt', 'tan'];
for (var i = 0; i < numFunctions.length; i++) {
this.setProperty(myMath, numFunctions[i],
this.createNativeFunction(Math[numFunctions[i]], false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
}
};
/**
* Initialize JSON object.
* @param {!Interpreter.Object} scope Global scope.
*/
Interpreter.prototype.initJSON = function(scope) {
var thisInterpreter = this;
var myJSON = thisInterpreter.createObjectProto(this.OBJECT_PROTO);
this.setProperty(scope, 'JSON', myJSON);
var wrapper = function(text) {
try {
var nativeObj = JSON.parse(text.toString());
} catch (e) {
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR, e.message);
}
return thisInterpreter.nativeToPseudo(nativeObj);
};
this.setProperty(myJSON, 'parse', this.createNativeFunction(wrapper, false));
wrapper = function(value) {
var nativeObj = thisInterpreter.pseudoToNative(value);
try {
var str = JSON.stringify(nativeObj);
} catch (e) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, e.message);
}
return str;
};
this.setProperty(myJSON, 'stringify',
this.createNativeFunction(wrapper, false));
};
/**
* Is an object of a certain class?
* @param {Interpreter.Value} child Object to check.
* @param {Interpreter.Object} constructor Constructor of object.
* @return {boolean} True if object is the class or inherits from it.
* False otherwise.
*/
Interpreter.prototype.isa = function(child, constructor) {
if (child === null || child === undefined || !constructor) {
return false;
}
var proto = constructor.properties['prototype'];
if (child === proto) {
return true;
}
// The first step up the prototype chain is harder since the child might be
// a primitive value. Subsequent steps can just follow the .proto property.
child = this.getPrototype(child);
while (child) {
if (child === proto) {
return true;
}
child = child.proto;
}
return false;
};
/**
* Is a value a legal integer for an array length?
* @param {Interpreter.Value} x Value to check.
* @return {number} Zero, or a positive integer if the value can be
* converted to such. NaN otherwise.
*/
Interpreter.legalArrayLength = function(x) {
var n = x >>> 0;
// Array length must be between 0 and 2^32-1 (inclusive).
return (n === Number(x)) ? n : NaN;
};
/**
* Is a value a legal integer for an array index?
* @param {Interpreter.Value} x Value to check.
* @return {number} Zero, or a positive integer if the value can be
* converted to such. NaN otherwise.
*/
Interpreter.legalArrayIndex = function(x) {
var n = x >>> 0;
// Array index cannot be 2^32-1, otherwise length would be 2^32.
// 0xffffffff is 2^32-1.
return (String(n) === String(x) && n !== 0xffffffff) ? n : NaN;
};
/**
* Typedef for JS values.
* @typedef {!Interpreter.Object|boolean|number|string|undefined|null}
*/
Interpreter.Value;
/**
* Class for an object.
* @param {Interpreter.Object} proto Prototype object or null.
* @constructor
*/
Interpreter.Object = function(proto) {
this.getter = Object.create(null);
this.setter = Object.create(null);
this.properties = Object.create(null);
this.proto = proto;
};
/** @type {Interpreter.Object} */
Interpreter.Object.prototype.proto = null;
/** @type {boolean} */
Interpreter.Object.prototype.isObject = true;
/** @type {string} */
Interpreter.Object.prototype.class = 'Object';
/** @type {Date|RegExp|boolean|number|string|undefined|null} */
Interpreter.Object.prototype.data = null;
/**
* Convert this object into a string.
* @return {string} String value.
* @override
*/
Interpreter.Object.prototype.toString = function() {
if (this.class === 'Array') {
// Array
var cycles = Interpreter.toStringCycles_;
cycles.push(this);
try {
var strs = [];
for (var i = 0; i < this.properties.length; i++) {
var value = this.properties[i];
strs[i] = (value && value.isObject && cycles.indexOf(value) !== -1) ?
'...' : value;
}
} finally {
cycles.pop();
}
return strs.join(',');
}
if (this.class === 'Error') {
var cycles = Interpreter.toStringCycles_;
if (cycles.indexOf(this) !== -1) {
return '[object Error]';
}
var name, message;
// Bug: Does not support getters and setters for name or message.
var obj = this;
do {
if ('name' in obj.properties) {
name = obj.properties['name'];
break;
}
} while ((obj = obj.proto));
var obj = this;
do {
if ('message' in obj.properties) {
message = obj.properties['message'];
break;
}
} while ((obj = obj.proto));
cycles.push(this);
try {
name = name && name.toString();
message = message && message.toString();
} finally {
cycles.pop();
}
return message ? name + ': ' + message : String(name);
}
// RegExp, Date, and boxed primitives.
if (this.data !== null) {
return String(this.data);
}
return '[object ' + this.class + ']';
};
/**
* Return the object's value.
* @return {Interpreter.Value} Value.
* @override
*/
Interpreter.Object.prototype.valueOf = function() {
if (this.data === undefined || this.data === null ||
this.data instanceof RegExp) {
return this; // An Object.
}
if (this.data instanceof Date) {
return this.data.valueOf(); // Milliseconds.
}
return /** @type {(boolean|number|string)} */ (this.data); // Boxed primitive.
};
/**
* Create a new data object based on a constructor's prototype.
* @param {Interpreter.Object} constructor Parent constructor function,
* or null if scope object.
* @return {!Interpreter.Object} New data object.
*/
Interpreter.prototype.createObject = function(constructor) {
return this.createObjectProto(constructor &&
constructor.properties['prototype']);
};
/**
* Create a new data object based on a prototype.
* @param {Interpreter.Object} proto Prototype object.
* @return {!Interpreter.Object} New data object.
*/
Interpreter.prototype.createObjectProto = function(proto) {
if (typeof proto !== 'object') {
throw Error('Non object prototype');
}
var obj = new Interpreter.Object(proto);
// Functions have prototype objects.
if (this.isa(obj, this.FUNCTION)) {
this.setProperty(obj, 'prototype',
this.createObjectProto(this.OBJECT_PROTO || null));
obj.class = 'Function';
}
// Arrays have length.
if (this.isa(obj, this.ARRAY)) {
this.setProperty(obj, 'length', 0,
{configurable: false, enumerable: false, writable: true});
obj.class = 'Array';
}
if (this.isa(obj, this.ERROR)) {
obj.class = 'Error';
}
return obj;
};
/**
* Initialize a pseudo regular expression object based on a native regular
* expression object.
* @param {!Interpreter.Object} pseudoRegexp The existing object to set.
* @param {!RegExp} nativeRegexp The native regular expression.
*/
Interpreter.prototype.populateRegExp = function(pseudoRegexp, nativeRegexp) {
pseudoRegexp.data = nativeRegexp;
// lastIndex is settable, all others are read-only attributes
this.setProperty(pseudoRegexp, 'lastIndex', nativeRegexp.lastIndex,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(pseudoRegexp, 'source', nativeRegexp.source,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(pseudoRegexp, 'global', nativeRegexp.global,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(pseudoRegexp, 'ignoreCase', nativeRegexp.ignoreCase,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(pseudoRegexp, 'multiline', nativeRegexp.multiline,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
};
/**
* Create a new function.
* @param {!Object} node AST node defining the function.
* @param {!Object} scope Parent scope.
* @return {!Interpreter.Object} New function.
*/
Interpreter.prototype.createFunction = function(node, scope) {
var func = this.createObjectProto(this.FUNCTION_PROTO);
func.parentScope = scope;
func.node = node;
this.setProperty(func, 'length', func.node['params'].length,
Interpreter.READONLY_DESCRIPTOR);
return func;
};
/**
* Create a new native function.
* @param {!Function} nativeFunc JavaScript function.
* @param {boolean=} opt_constructor If true, the function's
* prototype will have its constructor property set to the function.
* If false, the function cannot be called as a constructor (e.g. escape).
* Defaults to undefined.
* @return {!Interpreter.Object} New function.
*/
Interpreter.prototype.createNativeFunction =
function(nativeFunc, opt_constructor) {
var func = this.createObjectProto(this.FUNCTION_PROTO);
func.nativeFunc = nativeFunc;
nativeFunc.id = this.functionCounter_++;
this.setProperty(func, 'length', nativeFunc.length,
Interpreter.READONLY_DESCRIPTOR);
if (opt_constructor) {
this.setProperty(func.properties['prototype'], 'constructor', func,
Interpreter.NONENUMERABLE_DESCRIPTOR);
} else if (opt_constructor === false) {
func.illegalConstructor = true;
this.setProperty(func, 'prototype', undefined);
}
return func;
};
/**
* Create a new native asynchronous function.
* @param {!Function} asyncFunc JavaScript function.
* @return {!Interpreter.Object} New function.
*/
Interpreter.prototype.createAsyncFunction = function(asyncFunc) {
var func = this.createObjectProto(this.FUNCTION_PROTO);
func.asyncFunc = asyncFunc;
asyncFunc.id = this.functionCounter_++;
this.setProperty(func, 'length', asyncFunc.length,
Interpreter.READONLY_DESCRIPTOR);
return func;
};
/**
* Converts from a native JS object or value to a JS interpreter object.
* Can handle JSON-style values, does NOT handle cycles.
* @param {*} nativeObj The native JS object to be converted.
* @return {Interpreter.Value} The equivalent JS interpreter object.
*/
Interpreter.prototype.nativeToPseudo = function(nativeObj) {
if ((typeof nativeObj !== 'object' && typeof nativeObj !== 'function') ||
nativeObj === null) {
return nativeObj;
}
if (nativeObj instanceof RegExp) {
var pseudoRegexp = this.createObjectProto(this.REGEXP_PROTO);
this.populateRegExp(pseudoRegexp, nativeObj);
return pseudoRegexp;
}
if (nativeObj instanceof Date) {
var pseudoDate = this.createObjectProto(this.DATE_PROTO);
pseudoDate.data = nativeObj;
return pseudoDate;
}
if (nativeObj instanceof Function) {
var interpreter = this;
var wrapper = function() {
return interpreter.nativeToPseudo(
nativeObj.apply(interpreter,
Array.prototype.slice.call(arguments)
.map(function(i) {
return interpreter.pseudoToNative(i);
})
)
);
};
return this.createNativeFunction(wrapper, undefined);
}
var pseudoObj;
if (Array.isArray(nativeObj)) { // Array.
pseudoObj = this.createObjectProto(this.ARRAY_PROTO);
for (var i = 0; i < nativeObj.length; i++) {
if (i in nativeObj) {
this.setProperty(pseudoObj, i, this.nativeToPseudo(nativeObj[i]));
}
}
} else { // Object.
pseudoObj = this.createObjectProto(this.OBJECT_PROTO);
for (var key in nativeObj) {
this.setProperty(pseudoObj, key, this.nativeToPseudo(nativeObj[key]));
}
}
return pseudoObj;
};
/**
* Converts from a JS interpreter object to native JS object.
* Can handle JSON-style values, plus cycles.
* @param {Interpreter.Value} pseudoObj The JS interpreter object to be
* converted.
* @param {Object=} opt_cycles Cycle detection (used in recursive calls).
* @return {*} The equivalent native JS object or value.
*/
Interpreter.prototype.pseudoToNative = function(pseudoObj, opt_cycles) {
if ((typeof pseudoObj !== 'object' && typeof pseudoObj !== 'function') ||
pseudoObj === null) {
return pseudoObj;
}
if (this.isa(pseudoObj, this.REGEXP)) { // Regular expression.
return pseudoObj.data;
}
if (this.isa(pseudoObj, this.DATE)) { // Date.
return pseudoObj.data;
}
var cycles = opt_cycles || {
pseudo: [],
native: []
};
var i = cycles.pseudo.indexOf(pseudoObj);
if (i !== -1) {
return cycles.native[i];
}
cycles.pseudo.push(pseudoObj);
var nativeObj;
if (this.isa(pseudoObj, this.ARRAY)) { // Array.
nativeObj = [];
cycles.native.push(nativeObj);
var length = this.getProperty(pseudoObj, 'length');
for (var i = 0; i < length; i++) {
if (this.hasProperty(pseudoObj, i)) {
nativeObj[i] =
this.pseudoToNative(this.getProperty(pseudoObj, i), cycles);
}
}
} else { // Object.
nativeObj = {};
cycles.native.push(nativeObj);
var val;
for (var key in pseudoObj.properties) {
val = pseudoObj.properties[key];
nativeObj[key] = this.pseudoToNative(val, cycles);
}
}
cycles.pseudo.pop();
cycles.native.pop();
return nativeObj;
};
/**
* Converts from a native JS array to a JS interpreter array.
* Does handle non-numeric properties (like str.match's index prop).
* Does NOT recurse into the array's contents.
* @param {!Array} nativeArray The JS array to be converted.
* @return {!Interpreter.Object} The equivalent JS interpreter array.
*/
Interpreter.prototype.arrayNativeToPseudo = function(nativeArray) {
var pseudoArray = this.createObjectProto(this.ARRAY_PROTO);
var props = Object.getOwnPropertyNames(nativeArray);
for (var i = 0; i < props.length; i++) {
this.setProperty(pseudoArray, props[i], nativeArray[props[i]]);
}
return pseudoArray;
};
/**
* Converts from a JS interpreter array to native JS array.
* Does handle non-numeric properties (like str.match's index prop).
* Does NOT recurse into the array's contents.
* @param {!Interpreter.Object} pseudoArray The JS interpreter array,
* or JS interpreter object pretending to be an array.
* @return {!Array} The equivalent native JS array.
*/
Interpreter.prototype.arrayPseudoToNative = function(pseudoArray) {
var nativeArray = [];
for (var key in pseudoArray.properties) {
nativeArray[key] = this.getProperty(pseudoArray, key);
}
// pseudoArray might be an object pretending to be an array. In this case
// it's possible that length is non-existent, invalid, or smaller than the
// largest defined numeric property. Set length explicitly here.
nativeArray.length = Interpreter.legalArrayLength(
this.getProperty(pseudoArray, 'length')) || 0;
return nativeArray;
};
/**
* Look up the prototype for this value.
* @param {Interpreter.Value} value Data object.
* @return {Interpreter.Object} Prototype object, null if none.
*/
Interpreter.prototype.getPrototype = function(value) {
switch (typeof value) {
case 'number':
return this.NUMBER.properties['prototype'];
case 'boolean':
return this.BOOLEAN.properties['prototype'];
case 'string':
return this.STRING.properties['prototype'];
}
if (value) {
return value.proto;
}
return null;
};
/**
* Fetch a property value from a data object.
* @param {Interpreter.Value} obj Data object.
* @param {Interpreter.Value} name Name of property.
* @param {Acorn AST Node} node Node that triggered this function. Used by Bitburner for getting error line numbers
* @return {Interpreter.Value} Property value (may be undefined).
*/
Interpreter.prototype.getProperty = function(obj, name, node) {
name = String(name);
if (obj === undefined || obj === null) {
let lineNum;
if (node != null && node.loc != null && node.loc.start != null) {
lineNum = node.loc.start.line;
}
this.throwException(this.TYPE_ERROR,
"Cannot read property '" + name + "' of " + obj, lineNum);
}
if (name === 'length') {
// Special cases for magic length property.
if (this.isa(obj, this.STRING)) {
return String(obj).length;
}
} else if (name.charCodeAt(0) < 0x40) {
// Might have numbers in there?
// Special cases for string array indexing
if (this.isa(obj, this.STRING)) {
var n = Interpreter.legalArrayIndex(name);
if (!isNaN(n) && n < String(obj).length) {
return String(obj)[n];
}
}
}
do {
if (obj.properties && name in obj.properties) {
var getter = obj.getter[name];
if (getter) {
// Flag this function as being a getter and thus needing immediate
// execution (rather than being the value of the property).
getter.isGetter = true;
return getter;
}
return obj.properties[name];
}
} while ((obj = this.getPrototype(obj)));
return undefined;
};
/**
* Does the named property exist on a data object.
* @param {Interpreter.Value} obj Data object.
* @param {Interpreter.Value} name Name of property.
* @return {boolean} True if property exists.
*/
Interpreter.prototype.hasProperty = function(obj, name) {
if (!obj.isObject) {
throw TypeError('Primitive data type has no properties');
}
name = String(name);
if (name === 'length' && this.isa(obj, this.STRING)) {
return true;
}
if (this.isa(obj, this.STRING)) {
var n = Interpreter.legalArrayIndex(name);
if (!isNaN(n) && n < String(obj).length) {
return true;
}
}
do {
if (obj.properties && name in obj.properties) {
return true;
}
} while ((obj = this.getPrototype(obj)));
return false;
};
/**
* Set a property value on a data object.
* @param {!Interpreter.Object} obj Data object.
* @param {Interpreter.Value} name Name of property.
* @param {Interpreter.Value} value New property value.
* Use Interpreter.VALUE_IN_DESCRIPTOR if value is handled by
* descriptor instead.
* @param {Object=} opt_descriptor Optional descriptor object.
* @return {!Interpreter.Object|undefined} Returns a setter function if one
* needs to be called, otherwise undefined.
*/
Interpreter.prototype.setProperty = function(obj, name, value, opt_descriptor) {
name = String(name);
if (obj === undefined || obj === null) {
this.throwException(this.TYPE_ERROR,
"Cannot set property '" + name + "' of " + obj);
}
if (opt_descriptor && ('get' in opt_descriptor || 'set' in opt_descriptor) &&
('value' in opt_descriptor || 'writable' in opt_descriptor)) {
this.throwException(this.TYPE_ERROR, 'Invalid property descriptor. ' +
'Cannot both specify accessors and a value or writable attribute');
}
var strict = !this.stateStack || this.getScope().strict;
if (!obj.isObject) {
if (strict) {
this.throwException(this.TYPE_ERROR, "Can't create property '" + name +
"' on '" + obj + "'");
}
return;
}
if (this.isa(obj, this.STRING)) {
var n = Interpreter.legalArrayIndex(name);
if (name === 'length' || (!isNaN(n) && n < String(obj).length)) {
// Can't set length or letters on String objects.
if (strict) {
this.throwException(this.TYPE_ERROR, "Cannot assign to read only " +
"property '" + name + "' of String '" + obj.data + "'");
}
return;
}
}
if (obj.class === 'Array') {
// Arrays have a magic length variable that is bound to the elements.
var length = obj.properties.length;
var i;
if (name === 'length') {
// Delete elements if length is smaller.
if (opt_descriptor) {
if (!('value' in opt_descriptor)) {
return;
}
value = opt_descriptor.value;
}
value = Interpreter.legalArrayLength(value);
if (isNaN(value)) {
this.throwException(this.RANGE_ERROR, 'Invalid array length');
}
if (value < length) {
for (i in obj.properties) {
i = Interpreter.legalArrayIndex(i);
if (!isNaN(i) && value <= i) {
delete obj.properties[i];
}
}
}
} else if (!isNaN(i = Interpreter.legalArrayIndex(name))) {
// Increase length if this index is larger.
obj.properties.length = Math.max(length, i + 1);
}
}
if (obj.preventExtensions && !(name in obj.properties)) {
if (strict) {
this.throwException(this.TYPE_ERROR, "Can't add property '" + name +
"', object is not extensible");
}
return;
}
if (opt_descriptor) {
// Define the property.
if ('get' in opt_descriptor) {
if (opt_descriptor.get) {
obj.getter[name] = opt_descriptor.get;
} else {
delete obj.getter[name];
}
}
if ('set' in opt_descriptor) {
if (opt_descriptor.set) {
obj.setter[name] = opt_descriptor.set;
} else {
delete obj.setter[name];
}
}
var descriptor = {};
if ('configurable' in opt_descriptor) {
descriptor.configurable = opt_descriptor.configurable;
}
if ('enumerable' in opt_descriptor) {
descriptor.enumerable = opt_descriptor.enumerable;
}
if ('writable' in opt_descriptor) {
descriptor.writable = opt_descriptor.writable;
delete obj.getter[name];
delete obj.setter[name];
}
if ('value' in opt_descriptor) {
descriptor.value = opt_descriptor.value;
delete obj.getter[name];
delete obj.setter[name];
} else if (value !== Interpreter.VALUE_IN_DESCRIPTOR) {
descriptor.value = value;
delete obj.getter[name];
delete obj.setter[name];
}
try {
Object.defineProperty(obj.properties, name, descriptor);
} catch (e) {
this.throwException(this.TYPE_ERROR, 'Cannot redefine property: ' + name);
}
} else {
// Set the property.
if (value === Interpreter.VALUE_IN_DESCRIPTOR) {
throw ReferenceError('Value not specified.');
}
// Determine the parent (possibly self) where the property is defined.
var defObj = obj;
while (!(name in defObj.properties)) {
defObj = this.getPrototype(defObj);
if (!defObj) {
// This is a new property.
defObj = obj;
break;
}
}
if (defObj.setter && defObj.setter[name]) {
return defObj.setter[name];
}
if (defObj.getter && defObj.getter[name]) {
if (strict) {
this.throwException(this.TYPE_ERROR, "Cannot set property '" + name +
"' of object '" + obj + "' which only has a getter");
}
} else {
// No setter, simple assignment.
try {
obj.properties[name] = value;
} catch (e) {
if (strict) {
this.throwException(this.TYPE_ERROR, "Cannot assign to read only " +
"property '" + name + "' of object '" + obj + "'");
}
}
}
}
};
/**
* Convenience method for adding a native function as a non-enumerable property
* onto an object's prototype.
* @param {!Interpreter.Object} obj Data object.
* @param {Interpreter.Value} name Name of property.
* @param {!Function} wrapper Function object.
*/
Interpreter.prototype.setNativeFunctionPrototype =
function(obj, name, wrapper) {
this.setProperty(obj.properties['prototype'], name,
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
};
/**
* Returns the current scope from the stateStack.
* @return {!Interpreter.Object} Current scope dictionary.
*/
Interpreter.prototype.getScope = function() {
var scope = this.stateStack[this.stateStack.length - 1].scope;
if (!scope) {
throw Error('No scope found.');
}
return scope;
};
/**
* Create a new scope dictionary.
* @param {!Object} node AST node defining the scope container
* (e.g. a function).
* @param {Interpreter.Object} parentScope Scope to link to.
* @return {!Interpreter.Object} New scope.
*/
Interpreter.prototype.createScope = function(node, parentScope) {
var scope = this.createObjectProto(null);
scope.parentScope = parentScope;
if (!parentScope) {
this.initGlobalScope(scope);
}
this.populateScope_(node, scope);
// Determine if this scope starts with 'use strict'.
scope.strict = false;
if (parentScope && parentScope.strict) {
scope.strict = true;
} else {
var firstNode = node['body'] && node['body'][0];
if (firstNode && firstNode.expression &&
firstNode.expression['type'] === 'Literal' &&
firstNode.expression.value === 'use strict') {
scope.strict = true;
}
}
return scope;
};
/**
* Create a new special scope dictionary. Similar to createScope(), but
* doesn't assume that the scope is for a function body.
* This is used for 'catch' clauses and 'with' statements.
* @param {!Interpreter.Object} parentScope Scope to link to.
* @param {Interpreter.Object=} opt_scope Optional object to transform into
* scope.
* @return {!Interpreter.Object} New scope.
*/
Interpreter.prototype.createSpecialScope = function(parentScope, opt_scope) {
if (!parentScope) {
throw Error('parentScope required');
}
var scope = opt_scope || this.createObjectProto(null);
scope.parentScope = parentScope;
scope.strict = parentScope.strict;
return scope;
};
/**
* Retrieves a value from the scope chain.
* @param {string} name Name of variable.
* @param {Acorn AST Node} node Node that triggered this function. Used by Bitburner for getting error line number
* @return {Interpreter.Value} Any value.
* May be flagged as being a getter and thus needing immediate execution
* (rather than being the value of the property).
*/
Interpreter.prototype.getValueFromScope = function(name, node) {
var scope = this.getScope();
while (scope && scope !== this.global) {
if (name in scope.properties) {
return scope.properties[name];
}
scope = scope.parentScope;
}
// The root scope is also an object which has inherited properties and
// could also have getters.
if (scope === this.global && this.hasProperty(scope, name)) {
return this.getProperty(scope, name);
}
// Typeof operator is unique: it can safely look at non-defined variables.
var prevNode = this.stateStack[this.stateStack.length - 1].node;
if (prevNode['type'] === 'UnaryExpression' &&
prevNode['operator'] === 'typeof') {
return undefined;
}
var lineNum;
if (node != null && node.loc != null && node.loc.start != null) {
lineNum = node.loc.start.line;
}
this.throwException(this.REFERENCE_ERROR, name + ' is not defined', lineNum);
};
/**
* Sets a value to the current scope.
* @param {string} name Name of variable.
* @param {Interpreter.Value} value Value.
* @return {!Interpreter.Object|undefined} Returns a setter function if one
* needs to be called, otherwise undefined.
*/
Interpreter.prototype.setValueToScope = function(name, value) {
var scope = this.getScope();
var strict = scope.strict;
while (scope && scope !== this.global) {
if (name in scope.properties) {
scope.properties[name] = value;
return undefined;
}
scope = scope.parentScope;
}
// The root scope is also an object which has readonly properties and
// could also have setters.
if (scope === this.global && (!strict || this.hasProperty(scope, name))) {
return this.setProperty(scope, name, value);
}
this.throwException(this.REFERENCE_ERROR, name + ' is not defined');
};
/**
* Create a new scope for the given node.
* @param {!Object} node AST node (program or function).
* @param {!Interpreter.Object} scope Scope dictionary to populate.
* @private
*/
Interpreter.prototype.populateScope_ = function(node, scope) {
if (node['type'] === 'VariableDeclaration') {
for (var i = 0; i < node['declarations'].length; i++) {
this.setProperty(scope, node['declarations'][i]['id']['name'],
undefined, Interpreter.VARIABLE_DESCRIPTOR);
}
} else if (node['type'] === 'FunctionDeclaration') {
this.setProperty(scope, node['id']['name'],
this.createFunction(node, scope), Interpreter.VARIABLE_DESCRIPTOR);
return; // Do not recurse into function.
} else if (node['type'] === 'FunctionExpression') {
return; // Do not recurse into function.
} else if (node['type'] === 'ExpressionStatement') {
return; // Expressions can't contain variable/function declarations.
}
var nodeClass = node['constructor'];
for (var name in node) {
var prop = node[name];
if (prop && typeof prop === 'object') {
if (Array.isArray(prop)) {
for (var i = 0; i < prop.length; i++) {
if (prop[i] && prop[i].constructor === nodeClass) {
this.populateScope_(prop[i], scope);
}
}
} else {
if (prop.constructor === nodeClass) {
this.populateScope_(prop, scope);
}
}
}
}
};
/**
* Remove start and end values from AST, or set start and end values to a
* constant value. Used to remove highlighting from polyfills and to set
* highlighting in an eval to cover the entire eval expression.
* @param {!Object} node AST node.
* @param {number=} start Starting character of all nodes, or undefined.
* @param {number=} end Ending character of all nodes, or undefined.
* @private
*/
Interpreter.prototype.stripLocations_ = function(node, start, end) {
if (start) {
node['start'] = start;
} else {
delete node['start'];
}
if (end) {
node['end'] = end;
} else {
delete node['end'];
}
for (var name in node) {
if (node.hasOwnProperty(name)) {
var prop = node[name];
if (prop && typeof prop === 'object') {
this.stripLocations_(prop, start, end);
}
}
}
};
/**
* Is the current state directly being called with as a construction with 'new'.
* @return {boolean} True if 'new foo()', false if 'foo()'.
*/
Interpreter.prototype.calledWithNew = function() {
return this.stateStack[this.stateStack.length - 1].isConstructor;
};
/**
* Gets a value from the scope chain or from an object property.
* @param {!Array} ref Name of variable or object/propname tuple.
* @param {Acorn AST Node} node Node that triggered this function. Used by Bitburner for getting error line number
* @return {Interpreter.Value} Any value.
* May be flagged as being a getter and thus needing immediate execution
* (rather than being the value of the property).
*/
Interpreter.prototype.getValue = function(ref, node) {
if (ref[0] === Interpreter.SCOPE_REFERENCE) {
// A null/varname variable lookup.
return this.getValueFromScope(ref[1], node);
} else {
// An obj/prop components tuple (foo.bar).
return this.getProperty(ref[0], ref[1], node);
}
};
/**
* Sets a value to the scope chain or to an object property.
* @param {!Array} ref Name of variable or object/propname tuple.
* @param {Interpreter.Value} value Value.
* @return {!Interpreter.Object|undefined} Returns a setter function if one
* needs to be called, otherwise undefined.
*/
Interpreter.prototype.setValue = function(ref, value) {
if (ref[0] === Interpreter.SCOPE_REFERENCE) {
// A null/varname variable lookup.
return this.setValueToScope(ref[1], value);
} else {
// An obj/prop components tuple (foo.bar).
return this.setProperty(ref[0], ref[1], value);
}
};
/**
* Completion Value Types.
* @enum {number}
*/
Interpreter.Completion = {
NORMAL: 0,
BREAK: 1,
CONTINUE: 2,
RETURN: 3,
THROW: 4
};
/**
* Throw an exception in the interpreter that can be handled by an
* interpreter try/catch statement. If unhandled, a real exception will
* be thrown. Can be called with either an error class and a message, or
* with an actual object to be thrown.
* @param {!Interpreter.Object} errorClass Type of error (if message is
* provided) or the value to throw (if no message).
* @param {string=} opt_message Message being thrown.
*/
Interpreter.prototype.throwException = function(errorClass, opt_message, lineNumber) {
if (opt_message === undefined) {
var error = errorClass; // This is a value to throw, not an error class.
} else {
var error = this.createObject(errorClass);
this.setProperty(error, 'message', opt_message,
Interpreter.NONENUMERABLE_DESCRIPTOR);
}
var lineNumErrorMsg;
if (lineNumber != null) {
lineNumErrorMsg = this.getErrorLineNumberMessage(lineNumber);
}
this.unwind(Interpreter.Completion.THROW, error, undefined, lineNumErrorMsg);
// Abort anything related to the current step.
throw Interpreter.STEP_ERROR;
};
/**
* Unwind the stack to the innermost relevant enclosing TryStatement,
* For/ForIn/WhileStatement or Call/NewExpression. If this results in
* the stack being completely unwound the thread will be terminated
* and the appropriate error being thrown.
* @param {Interpreter.Completion} type Completion type.
* @param {Interpreter.Value=} value Value computed, returned or thrown.
* @param {string=} label Target label for break or return.
*/
Interpreter.prototype.unwind = function(type, value, label, lineNumberMsg="") {
if (type === Interpreter.Completion.NORMAL) {
throw TypeError('Should not unwind for NORMAL completions');
}
for (var stack = this.stateStack; stack.length > 0; stack.pop()) {
var state = stack[stack.length - 1];
switch (state.node['type']) {
case 'TryStatement':
state.cv = {type: type, value: value, label: label};
return;
case 'CallExpression':
case 'NewExpression':
if (type === Interpreter.Completion.RETURN) {
state.value = value;
return;
} else if (type !== Interpreter.Completion.THROW) {
throw Error('Unsynatctic break/continue not rejected by Acorn');
}
}
if (type === Interpreter.Completion.BREAK) {
if (label ? (state.labels && state.labels.indexOf(label) !== -1) :
(state.isLoop || state.isSwitch)) {
stack.pop();
return;
}
} else if (type === Interpreter.Completion.CONTINUE) {
if (label ? (state.labels && state.labels.indexOf(label) !== -1) :
state.isLoop) {
return;
}
}
}
// Unhandled completion. Throw a real error.
var realError;
if (this.isa(value, this.ERROR)) {
var errorTable = {
'EvalError': EvalError,
'RangeError': RangeError,
'ReferenceError': ReferenceError,
'SyntaxError': SyntaxError,
'TypeError': TypeError,
'URIError': URIError
};
var name = this.getProperty(value, 'name').toString();
var message = this.getProperty(value, 'message').valueOf();
var type = errorTable[name] || Error;
realError = type(message + lineNumberMsg);
} else {
realError = String(value) + lineNumberMsg;
}
throw realError;
};
/**
* Create a call to a getter function.
* @param {!Interpreter.Object} func Function to execute.
* @param {!Interpreter.Object|!Array} left
* Name of variable or object/propname tuple.
* @private
*/
Interpreter.prototype.createGetter_ = function(func, left) {
// Normally 'this' will be specified as the object component (o.x).
// Sometimes 'this' is explicitly provided (o).
var funcThis = Array.isArray(left) ? left[0] : left;
var node = new this.nodeConstructor();
node['type'] = 'CallExpression';
var state = new Interpreter.State(node,
this.stateStack[this.stateStack.length - 1].scope);
state.doneCallee_ = true;
state.funcThis_ = funcThis;
state.func_ = func;
state.doneArgs_ = true;
state.arguments_ = [];
return state;
};
/**
* Create a call to a setter function.
* @param {!Interpreter.Object} func Function to execute.
* @param {!Interpreter.Object|!Array} left
* Name of variable or object/propname tuple.
* @param {Interpreter.Value} value Value to set.
* @private
*/
Interpreter.prototype.createSetter_ = function(func, left, value) {
// Normally 'this' will be specified as the object component (o.x).
// Sometimes 'this' is implicitly the global object (x).
var funcThis = Array.isArray(left) ? left[0] : this.global;
var node = new this.nodeConstructor();
node['type'] = 'CallExpression';
var state = new Interpreter.State(node,
this.stateStack[this.stateStack.length - 1].scope);
state.doneCallee_ = true;
state.funcThis_ = funcThis;
state.func_ = func;
state.doneArgs_ = true;
state.arguments_ = [value];
return state;
};
/**
* Class for a state.
* @param {!Object} node AST node for the state.
* @param {!Interpreter.Object} scope Scope object for the state.
* @constructor
*/
Interpreter.State = function(node, scope) {
this.node = node;
this.scope = scope;
};
///////////////////////////////////////////////////////////////////////////////
// Functions to handle each node type.
///////////////////////////////////////////////////////////////////////////////
Interpreter.prototype['stepArrayExpression'] = function(stack, state, node) {
var elements = node['elements'];
var n = state.n_ || 0;
if (!state.array_) {
state.array_ = this.createObjectProto(this.ARRAY_PROTO);
state.array_.properties.length = elements.length;
} else {
this.setProperty(state.array_, n, state.value);
n++;
}
while (n < elements.length) {
// Skip missing elements - they're not defined, not undefined.
if (elements[n]) {
state.n_ = n;
return new Interpreter.State(elements[n], state.scope);
}
n++;
}
stack.pop();
stack[stack.length - 1].value = state.array_;
};
Interpreter.prototype['stepAssignmentExpression'] =
function(stack, state, node) {
if (!state.doneLeft_) {
state.doneLeft_ = true;
var nextState = new Interpreter.State(node['left'], state.scope);
nextState.components = true;
return nextState;
}
if (!state.doneRight_) {
if (!state.leftReference_) {
state.leftReference_ = state.value;
}
if (state.doneGetter_) {
state.leftValue_ = state.value;
}
if (!state.doneGetter_ && node['operator'] !== '=') {
var leftValue = this.getValue(state.leftReference_, node);
state.leftValue_ = leftValue;
if (leftValue && typeof leftValue === 'object' && leftValue.isGetter) {
// Clear the getter flag and call the getter function.
leftValue.isGetter = false;
state.doneGetter_ = true;
var func = /** @type {!Interpreter.Object} */ (leftValue);
return this.createGetter_(func, state.leftReference_);
}
}
state.doneRight_ = true;
return new Interpreter.State(node['right'], state.scope);
}
if (state.doneSetter_) {
// Return if setter function.
// Setter method on property has completed.
// Ignore its return value, and use the original set value instead.
stack.pop();
stack[stack.length - 1].value = state.setterValue_;
return;
}
var value = state.leftValue_;
var rightValue = state.value;
switch (node['operator']) {
case '=': value = rightValue; break;
case '+=': value += rightValue; break;
case '-=': value -= rightValue; break;
case '*=': value *= rightValue; break;
case '/=': value /= rightValue; break;
case '%=': value %= rightValue; break;
case '<<=': value <<= rightValue; break;
case '>>=': value >>= rightValue; break;
case '>>>=': value >>>= rightValue; break;
case '&=': value &= rightValue; break;
case '^=': value ^= rightValue; break;
case '|=': value |= rightValue; break;
default:
throw SyntaxError('Unknown assignment expression: ' + node['operator']);
}
var setter = this.setValue(state.leftReference_, value);
if (setter) {
state.doneSetter_ = true;
state.setterValue_ = value;
return this.createSetter_(setter, state.leftReference_, value);
}
// Return if no setter function.
stack.pop();
stack[stack.length - 1].value = value;
};
Interpreter.prototype['stepBinaryExpression'] = function(stack, state, node) {
if (!state.doneLeft_) {
state.doneLeft_ = true;
return new Interpreter.State(node['left'], state.scope);
}
if (!state.doneRight_) {
state.doneRight_ = true;
state.leftValue_ = state.value;
return new Interpreter.State(node['right'], state.scope);
}
stack.pop();
var leftValue = state.leftValue_;
var rightValue = state.value;
var value;
switch (node['operator']) {
case '==': value = leftValue == rightValue; break;
case '!=': value = leftValue != rightValue; break;
case '===': value = leftValue === rightValue; break;
case '!==': value = leftValue !== rightValue; break;
case '>': value = leftValue > rightValue; break;
case '>=': value = leftValue >= rightValue; break;
case '<': value = leftValue < rightValue; break;
case '<=': value = leftValue <= rightValue; break;
case '+': value = leftValue + rightValue; break;
case '-': value = leftValue - rightValue; break;
case '*': value = leftValue * rightValue; break;
case '/': value = leftValue / rightValue; break;
case '%': value = leftValue % rightValue; break;
case '&': value = leftValue & rightValue; break;
case '|': value = leftValue | rightValue; break;
case '^': value = leftValue ^ rightValue; break;
case '<<': value = leftValue << rightValue; break;
case '>>': value = leftValue >> rightValue; break;
case '>>>': value = leftValue >>> rightValue; break;
case 'in':
if (!rightValue || !rightValue.isObject) {
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.TYPE_ERROR,
"'in' expects an object, not '" + rightValue + "'", lineNum);
}
value = this.hasProperty(rightValue, leftValue);
break;
case 'instanceof':
if (!this.isa(rightValue, this.FUNCTION)) {
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.TYPE_ERROR,
'Right-hand side of instanceof is not an object', lineNum);
}
value = leftValue.isObject ? this.isa(leftValue, rightValue) : false;
break;
default:
throw SyntaxError('Unknown binary operator: ' + node['operator']);
}
stack[stack.length - 1].value = value;
};
Interpreter.prototype['stepBlockStatement'] = function(stack, state, node) {
var n = state.n_ || 0;
var expression = node['body'][n];
if (expression) {
state.n_ = n + 1;
return new Interpreter.State(expression, state.scope);
}
stack.pop();
};
Interpreter.prototype['stepBreakStatement'] = function(stack, state, node) {
var label = node['label'] && node['label']['name'];
this.unwind(Interpreter.Completion.BREAK, undefined, label);
};
Interpreter.prototype['stepCallExpression'] = function(stack, state, node) {
if (!state.doneCallee_) {
state.doneCallee_ = 1;
// Components needed to determine value of 'this'.
var nextState = new Interpreter.State(node['callee'], state.scope);
nextState.components = true;
return nextState;
}
if (state.doneCallee_ === 1) {
// Determine value of the function.
state.doneCallee_ = 2;
var func = state.value;
if (Array.isArray(func)) {
state.func_ = this.getValue(func, node);
if (func[0] === Interpreter.SCOPE_REFERENCE) {
// (Globally or locally) named function. Is it named 'eval'?
state.directEval_ = (func[1] === 'eval');
} else {
// Method function, 'this' is object (ignored if invoked as 'new').
state.funcThis_ = func[0];
}
func = state.func_;
if (func && typeof func === 'object' && func.isGetter) {
// Clear the getter flag and call the getter function.
func.isGetter = false;
state.doneCallee_ = 1;
return this.createGetter_(/** @type {!Interpreter.Object} */ (func),
state.value);
}
} else {
// Already evaluated function: (function(){...})();
state.func_ = func;
}
state.arguments_ = [];
state.n_ = 0;
}
var func = state.func_;
if (!state.doneArgs_) {
if (state.n_ !== 0) {
state.arguments_.push(state.value);
}
if (node['arguments'][state.n_]) {
return new Interpreter.State(node['arguments'][state.n_++], state.scope);
}
// Determine value of 'this' in function.
if (node['type'] === 'NewExpression') {
if (func.illegalConstructor) {
// Illegal: new escape();
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.TYPE_ERROR, func + ' is not a constructor', lineNum);
}
// Constructor, 'this' is new object.
var proto = func.properties['prototype'];
if (typeof proto !== 'object' || proto === null) {
// Non-object prototypes default to Object.prototype.
proto = this.OBJECT_PROTO;
}
state.funcThis_ = this.createObjectProto(proto);
state.isConstructor = true;
} else if (state.funcThis_ === undefined) {
// Global function, 'this' is global object (or 'undefined' if strict).
state.funcThis_ = state.scope.strict ? undefined : this.global;
}
state.doneArgs_ = true;
}
if (!state.doneExec_) {
state.doneExec_ = true;
if (!func || !func.isObject) {
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.TYPE_ERROR, func + ' is not a function', lineNum);
}
var funcNode = func.node;
if (funcNode) {
var scope = this.createScope(funcNode['body'], func.parentScope);
// Add all arguments.
for (var i = 0; i < funcNode['params'].length; i++) {
var paramName = funcNode['params'][i]['name'];
var paramValue = state.arguments_.length > i ? state.arguments_[i] :
undefined;
this.setProperty(scope, paramName, paramValue);
}
// Build arguments variable.
var argsList = this.createObjectProto(this.ARRAY_PROTO);
for (var i = 0; i < state.arguments_.length; i++) {
this.setProperty(argsList, i, state.arguments_[i]);
}
this.setProperty(scope, 'arguments', argsList);
// Add the function's name (var x = function foo(){};)
var name = funcNode['id'] && funcNode['id']['name'];
if (name) {
this.setProperty(scope, name, func);
}
this.setProperty(scope, 'this', state.funcThis_,
Interpreter.READONLY_DESCRIPTOR);
state.value = undefined; // Default value if no explicit return.
return new Interpreter.State(funcNode['body'], scope);
} else if (func.eval) {
var code = state.arguments_[0];
if (typeof code !== 'string') {
// JS does not parse String objects:
// eval(new String('1 + 1')) -> '1 + 1'
state.value = code;
} else {
try {
var ast = _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"](code.toString(), Interpreter.PARSE_OPTIONS);
} catch (e) {
// Acorn threw a SyntaxError. Rethrow as a trappable error.
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.SYNTAX_ERROR, 'Invalid code: ' + e.message, lineNum);
}
var evalNode = new this.nodeConstructor();
evalNode['type'] = 'EvalProgram_';
evalNode['body'] = ast['body'];
this.stripLocations_(evalNode, node['start'], node['end']);
// Create new scope and update it with definitions in eval().
var scope = state.directEval_ ? state.scope : this.global;
if (scope.strict) {
// Strict mode get its own scope in eval.
scope = this.createScope(ast, scope);
} else {
// Non-strict mode pollutes the current scope.
this.populateScope_(ast, scope);
}
this.value = undefined; // Default value if no code.
return new Interpreter.State(evalNode, scope);
}
} else if (func.nativeFunc) {
state.value = func.nativeFunc.apply(state.funcThis_, state.arguments_);
} else if (func.asyncFunc) {
var thisInterpreter = this;
var callback = function(value) {
state.value = value;
thisInterpreter.paused_ = false;
};
var argsWithCallback = state.arguments_.concat(callback);
this.paused_ = true;
func.asyncFunc.apply(state.funcThis_, argsWithCallback);
return;
} else {
/* A child of a function is a function but is not callable. For example:
var F = function() {};
F.prototype = escape;
var f = new F();
f();
*/
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.TYPE_ERROR, func.class + ' is not a function', lineNum);
}
} else {
// Execution complete. Put the return value on the stack.
stack.pop();
if (state.isConstructor && typeof state.value !== 'object') {
stack[stack.length - 1].value = state.funcThis_;
} else {
stack[stack.length - 1].value = state.value;
}
}
};
Interpreter.prototype['stepCatchClause'] = function(stack, state, node) {
if (!state.done_) {
state.done_ = true;
// Create an empty scope.
var scope = this.createSpecialScope(state.scope);
// Add the argument.
this.setProperty(scope, node['param']['name'], state.throwValue);
// Execute catch clause.
return new Interpreter.State(node['body'], scope);
} else {
stack.pop();
}
};
Interpreter.prototype['stepConditionalExpression'] =
function(stack, state, node) {
var mode = state.mode_ || 0;
if (mode === 0) {
state.mode_ = 1;
return new Interpreter.State(node['test'], state.scope);
}
if (mode === 1) {
state.mode_ = 2;
var value = Boolean(state.value);
if (value && node['consequent']) {
// Execute 'if' block.
return new Interpreter.State(node['consequent'], state.scope);
} else if (!value && node['alternate']) {
// Execute 'else' block.
return new Interpreter.State(node['alternate'], state.scope);
}
// eval('1;if(false){2}') -> undefined
this.value = undefined;
}
stack.pop();
if (node['type'] === 'ConditionalExpression') {
stack[stack.length - 1].value = state.value;
}
};
Interpreter.prototype['stepContinueStatement'] = function(stack, state, node) {
var label = node['label'] && node['label']['name'];
this.unwind(Interpreter.Completion.CONTINUE, undefined, label);
};
Interpreter.prototype['stepDebuggerStatement'] = function(stack, state, node) {
// Do nothing. May be overridden by developers.
stack.pop();
};
Interpreter.prototype['stepDoWhileStatement'] = function(stack, state, node) {
if (node['type'] === 'DoWhileStatement' && state.test_ === undefined) {
// First iteration of do/while executes without checking test.
state.value = true;
state.test_ = true;
}
if (!state.test_) {
state.test_ = true;
return new Interpreter.State(node['test'], state.scope);
}
if (!state.value) { // Done, exit loop.
stack.pop();
} else if (node['body']) { // Execute the body.
state.test_ = false;
state.isLoop = true;
return new Interpreter.State(node['body'], state.scope);
}
};
Interpreter.prototype['stepEmptyStatement'] = function(stack, state, node) {
stack.pop();
};
Interpreter.prototype['stepEvalProgram_'] = function(stack, state, node) {
var n = state.n_ || 0;
var expression = node['body'][n];
if (expression) {
state.n_ = n + 1;
return new Interpreter.State(expression, state.scope);
}
stack.pop();
stack[stack.length - 1].value = this.value;
};
Interpreter.prototype['stepExpressionStatement'] = function(stack, state, node) {
if (!state.done_) {
state.done_ = true;
return new Interpreter.State(node['expression'], state.scope);
}
stack.pop();
// Save this value to interpreter.value for use as a return value if
// this code is inside an eval function.
this.value = state.value;
};
Interpreter.prototype['stepForInStatement'] = function(stack, state, node) {
// First, initialize a variable if exists. Only do so once, ever.
if (!state.doneInit_) {
state.doneInit_ = true;
if (node['left']['declarations'] &&
node['left']['declarations'][0]['init']) {
if (state.scope.strict) {
let lineNum = this.getErrorLineNumber(node);
this.throwException(this.SYNTAX_ERROR,
'for-in loop variable declaration may not have an initializer.', lineNum);
}
// Variable initialization: for (var x = 4 in y)
return new Interpreter.State(node['left'], state.scope);
}
}
// Second, look up the object. Only do so once, ever.
if (!state.doneObject_) {
state.doneObject_ = true;
if (!state.variable_) {
state.variable_ = state.value;
}
return new Interpreter.State(node['right'], state.scope);
}
if (!state.isLoop) {
// First iteration.
state.isLoop = true;
state.object_ = state.value;
state.visited_ = Object.create(null);
}
// Third, find the property name for this iteration.
if (state.name_ === undefined) {
gotPropName: while (true) {
if (state.object_ && state.object_.isObject) {
if (!state.props_) {
state.props_ = Object.getOwnPropertyNames(state.object_.properties);
}
while (true) {
var prop = state.props_.shift();
if (prop === undefined) {
break; // Reached end of this object's properties.
}
if (!Object.prototype.hasOwnProperty.call(state.object_.properties,
prop)) {
continue; // Property has been deleted in the loop.
}
if (state.visited_[prop]) {
continue; // Already seen this property on a child.
}
state.visited_[prop] = true;
if (!Object.prototype.propertyIsEnumerable.call(
state.object_.properties, prop)) {
continue; // Skip non-enumerable property.
}
state.name_ = prop;
break gotPropName;
}
} else if (state.object_ !== null && state.object_ !== undefined) {
// Primitive value (other than null or undefined).
if (!state.props_) {
state.props_ = Object.getOwnPropertyNames(state.object_);
}
while (true) {
var prop = state.props_.shift();
if (prop === undefined) {
break; // Reached end of this value's properties.
}
state.visited_[prop] = true;
if (!Object.prototype.propertyIsEnumerable.call(
state.object_, prop)) {
continue; // Skip non-enumerable property.
}
state.name_ = prop;
break gotPropName;
}
}
state.object_ = this.getPrototype(state.object_);
state.props_ = null;
if (state.object_ === null) {
// Done, exit loop.
stack.pop();
return;
}
}
}
// Fourth, find the variable
if (!state.doneVariable_) {
state.doneVariable_ = true;
var left = node['left'];
if (left['type'] === 'VariableDeclaration') {
// Inline variable declaration: for (var x in y)
state.variable_ =
[Interpreter.SCOPE_REFERENCE, left['declarations'][0]['id']['name']];
} else {
// Arbitrary left side: for (foo().bar in y)
state.variable_ = null;
var nextState = new Interpreter.State(left, state.scope);
nextState.components = true;
return nextState;
}
}
if (!state.variable_) {
state.variable_ = state.value;
}
// Fifth, set the variable.
if (!state.doneSetter_) {
state.doneSetter_ = true;
var value = state.name_;
var setter = this.setValue(state.variable_, value);
if (setter) {
return this.createSetter_(setter, state.variable_, value);
}
}
// Next step will be step three.
state.name_ = undefined;
// Reevaluate the variable since it could be a setter on the global object.
state.doneVariable_ = false;
state.doneSetter_ = false;
// Sixth and finally, execute the body if there was one. this.
if (node['body']) {
return new Interpreter.State(node['body'], state.scope);
}
};
Interpreter.prototype['stepForStatement'] = function(stack, state, node) {
var mode = state.mode_ || 0;
if (mode === 0) {
state.mode_ = 1;
if (node['init']) {
return new Interpreter.State(node['init'], state.scope);
}
} else if (mode === 1) {
state.mode_ = 2;
if (node['test']) {
return new Interpreter.State(node['test'], state.scope);
}
} else if (mode === 2) {
state.mode_ = 3;
if (node['test'] && !state.value) {
// Done, exit loop.
stack.pop();
} else { // Execute the body.
state.isLoop = true;
return new Interpreter.State(node['body'], state.scope);
}
} else if (mode === 3) {
state.mode_ = 1;
if (node['update']) {
return new Interpreter.State(node['update'], state.scope);
}
}
};
Interpreter.prototype['stepFunctionDeclaration'] =
function(stack, state, node) {
// This was found and handled when the scope was populated.
stack.pop();
};
Interpreter.prototype['stepFunctionExpression'] = function(stack, state, node) {
stack.pop();
stack[stack.length - 1].value = this.createFunction(node, state.scope);
};
Interpreter.prototype['stepIdentifier'] = function(stack, state, node) {
stack.pop();
if (state.components) {
stack[stack.length - 1].value = [Interpreter.SCOPE_REFERENCE, node['name']];
return;
}
var value = this.getValueFromScope(node['name'], node);
// An identifier could be a getter if it's a property on the global object.
if (value && typeof value === 'object' && value.isGetter) {
// Clear the getter flag and call the getter function.
value.isGetter = false;
var scope = state.scope;
while (!this.hasProperty(scope, node['name'])) {
scope = scope.parentScope;
}
var func = /** @type {!Interpreter.Object} */ (value);
return this.createGetter_(func, this.global);
}
stack[stack.length - 1].value = value;
};
Interpreter.prototype['stepIfStatement'] =
Interpreter.prototype['stepConditionalExpression'];
Interpreter.prototype['stepLabeledStatement'] = function(stack, state, node) {
// No need to hit this node again on the way back up the stack.
stack.pop();
// Note that a statement might have multiple labels.
var labels = state.labels || [];
labels.push(node['label']['name']);
var nextState = new Interpreter.State(node['body'], state.scope);
nextState.labels = labels;
return nextState;
};
Interpreter.prototype['stepLiteral'] = function(stack, state, node) {
stack.pop();
var value = node['value'];
if (value instanceof RegExp) {
var pseudoRegexp = this.createObjectProto(this.REGEXP_PROTO);
this.populateRegExp(pseudoRegexp, value);
value = pseudoRegexp;
}
stack[stack.length - 1].value = value;
};
Interpreter.prototype['stepLogicalExpression'] = function(stack, state, node) {
if (node['operator'] !== '&&' && node['operator'] !== '||') {
throw SyntaxError('Unknown logical operator: ' + node['operator']);
}
if (!state.doneLeft_) {
state.doneLeft_ = true;
return new Interpreter.State(node['left'], state.scope);
}
if (!state.doneRight_) {
if ((node['operator'] === '&&' && !state.value) ||
(node['operator'] === '||' && state.value)) {
// Shortcut evaluation.
stack.pop();
stack[stack.length - 1].value = state.value;
} else {
state.doneRight_ = true;
return new Interpreter.State(node['right'], state.scope);
}
} else {
stack.pop();
stack[stack.length - 1].value = state.value;
}
};
Interpreter.prototype['stepMemberExpression'] = function(stack, state, node) {
if (!state.doneObject_) {
state.doneObject_ = true;
return new Interpreter.State(node['object'], state.scope);
}
var propName;
if (!node['computed']) {
state.object_ = state.value;
// obj.foo -- Just access 'foo' directly.
propName = node['property']['name'];
} else if (!state.doneProperty_) {
state.object_ = state.value;
// obj[foo] -- Compute value of 'foo'.
state.doneProperty_ = true;
return new Interpreter.State(node['property'], state.scope);
} else {
propName = state.value;
}
stack.pop();
if (state.components) {
stack[stack.length - 1].value = [state.object_, propName];
} else {
var value = this.getProperty(state.object_, propName);
if (value && typeof value === 'object' && value.isGetter) {
// Clear the getter flag and call the getter function.
value.isGetter = false;
var func = /** @type {!Interpreter.Object} */ (value);
return this.createGetter_(func, state.object_);
}
stack[stack.length - 1].value = value;
}
};
Interpreter.prototype['stepNewExpression'] =
Interpreter.prototype['stepCallExpression'];
Interpreter.prototype['stepObjectExpression'] = function(stack, state, node) {
var n = state.n_ || 0;
var property = node['properties'][n];
if (!state.object_) {
// First execution.
state.object_ = this.createObjectProto(this.OBJECT_PROTO);
state.properties_ = Object.create(null);
} else {
// Determine property name.
var key = property['key'];
if (key['type'] === 'Identifier') {
var propName = key['name'];
} else if (key['type'] === 'Literal') {
var propName = key['value'];
} else {
throw SyntaxError('Unknown object structure: ' + key['type']);
}
// Set the property computed in the previous execution.
if (!state.properties_[propName]) {
// Create temp object to collect value, getter, and/or setter.
state.properties_[propName] = {};
}
state.properties_[propName][property['kind']] = state.value;
state.n_ = ++n;
property = node['properties'][n];
}
if (property) {
return new Interpreter.State(property['value'], state.scope);
}
for (var key in state.properties_) {
var kinds = state.properties_[key];
if ('get' in kinds || 'set' in kinds) {
// Set a property with a getter or setter.
var descriptor = {
configurable: true,
enumerable: true,
get: kinds['get'],
set: kinds['set']
};
this.setProperty(state.object_, key, null, descriptor);
} else {
// Set a normal property with a value.
this.setProperty(state.object_, key, kinds['init']);
}
}
stack.pop();
stack[stack.length - 1].value = state.object_;
};
Interpreter.prototype['stepProgram'] = function(stack, state, node) {
var expression = node['body'].shift();
if (expression) {
state.done = false;
return new Interpreter.State(expression, state.scope);
}
state.done = true;
// Don't pop the stateStack.
// Leave the root scope on the tree in case the program is appended to.
};
Interpreter.prototype['stepReturnStatement'] = function(stack, state, node) {
if (node['argument'] && !state.done_) {
state.done_ = true;
return new Interpreter.State(node['argument'], state.scope);
}
this.unwind(Interpreter.Completion.RETURN, state.value, undefined);
};
Interpreter.prototype['stepSequenceExpression'] = function(stack, state, node) {
var n = state.n_ || 0;
var expression = node['expressions'][n];
if (expression) {
state.n_ = n + 1;
return new Interpreter.State(expression, state.scope);
}
stack.pop();
stack[stack.length - 1].value = state.value;
};
Interpreter.prototype['stepSwitchStatement'] = function(stack, state, node) {
if (!state.test_) {
state.test_ = 1;
return new Interpreter.State(node['discriminant'], state.scope);
}
if (state.test_ === 1) {
state.test_ = 2;
// Preserve switch value between case tests.
state.switchValue_ = state.value;
state.defaultCase_ = -1;
}
while (true) {
var index = state.index_ || 0;
var switchCase = node['cases'][index];
if (!state.matched_ && switchCase && !switchCase['test']) {
// Test on the default case is null.
// Bypass (but store) the default case, and get back to it later.
state.defaultCase_ = index;
state.index_ = index + 1;
continue;
}
if (!switchCase && !state.matched_ && state.defaultCase_ !== -1) {
// Ran through all cases, no match. Jump to the default.
state.matched_ = true;
state.index_ = state.defaultCase_;
continue;
}
if (switchCase) {
if (!state.matched_ && !state.tested_ && switchCase['test']) {
state.tested_ = true;
return new Interpreter.State(switchCase['test'], state.scope);
}
if (state.matched_ || state.value === state.switchValue_) {
state.matched_ = true;
var n = state.n_ || 0;
if (switchCase['consequent'][n]) {
state.isSwitch = true;
state.n_ = n + 1;
return new Interpreter.State(switchCase['consequent'][n],
state.scope);
}
}
// Move on to next case.
state.tested_ = false;
state.n_ = 0;
state.index_ = index + 1;
} else {
stack.pop();
return;
}
}
};
Interpreter.prototype['stepThisExpression'] = function(stack, state, node) {
stack.pop();
stack[stack.length - 1].value = this.getValueFromScope('this', node);
};
Interpreter.prototype['stepThrowStatement'] = function(stack, state, node) {
if (!state.done_) {
state.done_ = true;
return new Interpreter.State(node['argument'], state.scope);
} else {
this.throwException(state.value);
}
};
Interpreter.prototype['stepTryStatement'] = function(stack, state, node) {
if (!state.doneBlock_) {
state.doneBlock_ = true;
return new Interpreter.State(node['block'], state.scope);
}
if (state.cv && state.cv.type === Interpreter.Completion.THROW &&
!state.doneHandler_ && node['handler']) {
state.doneHandler_ = true;
var nextState = new Interpreter.State(node['handler'], state.scope);
nextState.throwValue = state.cv.value;
state.cv = undefined; // This error has been handled, don't rethrow.
return nextState;
}
if (!state.doneFinalizer_ && node['finalizer']) {
state.doneFinalizer_ = true;
return new Interpreter.State(node['finalizer'], state.scope);
}
stack.pop();
if (state.cv) {
// There was no catch handler, or the catch/finally threw an error.
// Throw the error up to a higher try.
this.unwind(state.cv.type, state.cv.value, state.cv.label);
}
};
Interpreter.prototype['stepUnaryExpression'] = function(stack, state, node) {
if (!state.done_) {
state.done_ = true;
var nextState = new Interpreter.State(node['argument'], state.scope);
nextState.components = node['operator'] === 'delete';
return nextState;
}
stack.pop();
var value = state.value;
if (node['operator'] === '-') {
value = -value;
} else if (node['operator'] === '+') {
value = +value;
} else if (node['operator'] === '!') {
value = !value;
} else if (node['operator'] === '~') {
value = ~value;
} else if (node['operator'] === 'delete') {
var result = true;
// If value is not an array, then it is a primitive, or some other value.
// If so, skip the delete and return true.
if (Array.isArray(value)) {
var obj = value[0];
if (obj === Interpreter.SCOPE_REFERENCE) {
// 'delete foo;' is the same as 'delete window.foo'.
obj = state.scope;
}
var name = String(value[1]);
try {
delete obj.properties[name];
} catch (e) {
if (state.scope.strict) {
this.throwException(this.TYPE_ERROR, "Cannot delete property '" +
name + "' of '" + obj + "'");
} else {
result = false;
}
}
}
value = result;
} else if (node['operator'] === 'typeof') {
value = (value && value.class === 'Function') ? 'function' : typeof value;
} else if (node['operator'] === 'void') {
value = undefined;
} else {
throw SyntaxError('Unknown unary operator: ' + node['operator']);
}
stack[stack.length - 1].value = value;
};
Interpreter.prototype['stepUpdateExpression'] = function(stack, state, node) {
if (!state.doneLeft_) {
state.doneLeft_ = true;
var nextState = new Interpreter.State(node['argument'], state.scope);
nextState.components = true;
return nextState;
}
if (!state.leftSide_) {
state.leftSide_ = state.value;
}
if (state.doneGetter_) {
state.leftValue_ = state.value;
}
if (!state.doneGetter_) {
var leftValue = this.getValue(state.leftSide_, node);
state.leftValue_ = leftValue;
if (leftValue && typeof leftValue === 'object' && leftValue.isGetter) {
// Clear the getter flag and call the getter function.
leftValue.isGetter = false;
state.doneGetter_ = true;
var func = /** @type {!Interpreter.Object} */ (leftValue);
return this.createGetter_(func, state.leftSide_);
}
}
if (state.doneSetter_) {
// Return if setter function.
// Setter method on property has completed.
// Ignore its return value, and use the original set value instead.
stack.pop();
stack[stack.length - 1].value = state.setterValue_;
return;
}
var leftValue = Number(state.leftValue_);
var changeValue;
if (node['operator'] === '++') {
changeValue = leftValue + 1;
} else if (node['operator'] === '--') {
changeValue = leftValue - 1;
} else {
throw SyntaxError('Unknown update expression: ' + node['operator']);
}
var returnValue = node['prefix'] ? changeValue : leftValue;
var setter = this.setValue(state.leftSide_, changeValue);
if (setter) {
state.doneSetter_ = true;
state.setterValue_ = returnValue;
return this.createSetter_(setter, state.leftSide_, changeValue);
}
// Return if no setter function.
stack.pop();
stack[stack.length - 1].value = returnValue;
};
Interpreter.prototype['stepVariableDeclaration'] = function(stack, state, node) {
var declarations = node['declarations'];
var n = state.n_ || 0;
var declarationNode = declarations[n];
if (state.init_ && declarationNode) {
// This setValue call never needs to deal with calling a setter function.
// Note that this is setting the init value, not defining the variable.
// Variable definition is done when scope is populated.
this.setValueToScope(declarationNode['id']['name'], state.value);
state.init_ = false;
declarationNode = declarations[++n];
}
while (declarationNode) {
// Skip any declarations that are not initialized. They have already
// been defined as undefined in populateScope_.
if (declarationNode['init']) {
state.n_ = n;
state.init_ = true;
return new Interpreter.State(declarationNode['init'], state.scope);
}
declarationNode = declarations[++n];
}
stack.pop();
};
Interpreter.prototype['stepWithStatement'] = function(stack, state, node) {
if (!state.doneObject_) {
state.doneObject_ = true;
return new Interpreter.State(node['object'], state.scope);
} else if (!state.doneBody_) {
state.doneBody_ = true;
var scope = this.createSpecialScope(state.scope, state.value);
return new Interpreter.State(node['body'], scope);
} else {
stack.pop();
}
};
Interpreter.prototype['stepWhileStatement'] =
Interpreter.prototype['stepDoWhileStatement'];
// Preserve top-level API functions from being pruned/renamed by JS compilers.
// Add others as needed.
// The global object ('window' in a browser, 'global' in node.js) is 'this'.
//this['Interpreter'] = Interpreter;
Interpreter.prototype['step'] = Interpreter.prototype.step;
Interpreter.prototype['run'] = Interpreter.prototype.run;
Interpreter.prototype['appendCode'] = Interpreter.prototype.appendCode;
Interpreter.prototype['createObject'] = Interpreter.prototype.createObject;
Interpreter.prototype['createObjectProto'] =
Interpreter.prototype.createObjectProto;
Interpreter.prototype['createAsyncFunction'] =
Interpreter.prototype.createAsyncFunction;
Interpreter.prototype['createNativeFunction'] =
Interpreter.prototype.createNativeFunction;
Interpreter.prototype['getProperty'] = Interpreter.prototype.getProperty;
Interpreter.prototype['setProperty'] = Interpreter.prototype.setProperty;
Interpreter.prototype['nativeToPseudo'] = Interpreter.prototype.nativeToPseudo;
Interpreter.prototype['pseudoToNative'] = Interpreter.prototype.pseudoToNative;
// Obsolete. Do not use.
Interpreter.prototype['createPrimitive'] = function(x) {return x;};
/***/ }),
/* 120 */
/*!***************************************!*\
!*** ./utils/helpers/isPowerOfTwo.ts ***!
\***************************************/
/*! no static exports found */
/*! exports used: isPowerOfTwo */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Determines if the number is a power of 2
* @param n The number to check.
*/
function isPowerOfTwo(n) {
if (isNaN(n)) {
return false;
}
if (n === 0) {
return false;
}
// Disabiling the bitwise rule because it's honestly the most effecient way to check for this.
// tslint:disable-next-line:no-bitwise
return (n & (n - 1)) === 0;
}
exports.isPowerOfTwo = isPowerOfTwo;
/***/ }),
/* 121 */
/*!****************************************!*\
!*** ./src/data/gangmemberupgrades.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: gangMemberUpgradesMetadata */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Array of metadata for all Gang Member upgrades. Used to construct the global GangMemberUpgrade
* objects in Gang.js
*/
exports.gangMemberUpgradesMetadata = [
{
cost: 1e6,
mults: { str: 1.04, def: 1.04 },
name: "Baseball Bat",
upgType: "w",
},
{
cost: 12e6,
mults: { str: 1.08, def: 1.08, dex: 1.08 },
name: "Katana",
upgType: "w",
},
{
cost: 25e6,
mults: { str: 1.1, def: 1.1, dex: 1.1, agi: 1.1 },
name: "Glock 18C",
upgType: "w",
},
{
cost: 50e6,
mults: { str: 1.12, def: 1.1, agi: 1.1 },
name: "P90C",
upgType: "w",
},
{
cost: 60e6,
mults: { str: 1.2, def: 1.15 },
name: "Steyr AUG",
upgType: "w",
},
{
cost: 100e6,
mults: { str: 1.25, def: 1.2 },
name: "AK-47",
upgType: "w",
},
{
cost: 150e6,
mults: { str: 1.3, def: 1.25 },
name: "M15A10 Assault Rifle",
upgType: "w",
},
{
cost: 225e6,
mults: { str: 1.3, dex: 1.25, agi: 1.3 },
name: "AWM Sniper Rifle",
upgType: "w",
},
{
cost: 2e6,
mults: { def: 1.04 },
name: "Bulletproof Vest",
upgType: "a",
},
{
cost: 5e6,
mults: { def: 1.08 },
name: "Full Body Armor",
upgType: "a",
},
{
cost: 25e6,
mults: { def: 1.15, agi: 1.15 },
name: "Liquid Body Armor",
upgType: "a",
},
{
cost: 40e6,
mults: { def: 1.2 },
name: "Graphene Plating Armor",
upgType: "a",
},
{
cost: 3e6,
mults: { agi: 1.04, cha: 1.04 },
name: "Ford Flex V20",
upgType: "v",
},
{
cost: 9e6,
mults: { agi: 1.08, cha: 1.08 },
name: "ATX1070 Superbike",
upgType: "v",
},
{
cost: 18e6,
mults: { agi: 1.12, cha: 1.12 },
name: "Mercedes-Benz S9001",
upgType: "v",
},
{
cost: 30e6,
mults: { agi: 1.16, cha: 1.16 },
name: "White Ferrari",
upgType: "v",
},
{
cost: 5e6,
mults: { hack: 1.05 },
name: "NUKE Rootkit",
upgType: "r",
},
{
cost: 25e6,
mults: { hack: 1.1 },
name: "Soulstealer Rootkit",
upgType: "r",
},
{
cost: 75e6,
mults: { hack: 1.15 },
name: "Demon Rootkit",
upgType: "r",
},
{
cost: 40e6,
mults: { hack: 1.12 },
name: "Hmap Node",
upgType: "r",
},
{
cost: 75e6,
mults: { hack: 1.15 },
name: "Jack the Ripper",
upgType: "r",
},
{
cost: 10e9,
mults: { str: 1.3, dex: 1.3 },
name: "Bionic Arms",
upgType: "g",
},
{
cost: 10e9,
mults: { agi: 1.6 },
name: "Bionic Legs",
upgType: "g",
},
{
cost: 15e9,
mults: { str: 1.15, def: 1.15, dex: 1.15, agi: 1.15 },
name: "Bionic Spine",
upgType: "g",
},
{
cost: 20e9,
mults: { str: 1.4, def: 1.4 },
name: "BrachiBlades",
upgType: "g",
},
{
cost: 12e9,
mults: { str: 1.2, def: 1.2 },
name: "Nanofiber Weave",
upgType: "g",
},
{
cost: 25e9,
mults: { str: 1.5, agi: 1.5 },
name: "Synthetic Heart",
upgType: "g",
},
{
cost: 15e9,
mults: { str: 1.3, def: 1.3 },
name: "Synfibril Muscle",
upgType: "g",
},
{
cost: 5e9,
mults: { hack: 1.05 },
name: "BitWire",
upgType: "g",
},
{
cost: 10e9,
mults: { hack: 1.15 },
name: "Neuralstimulator",
upgType: "g",
},
{
cost: 7.5e9,
mults: { hack: 1.1 },
name: "DataJack",
upgType: "g",
},
{
cost: 50e9,
mults: { str: 1.7, def: 1.7 },
name: "Graphene Bone Lacings",
upgType: "g",
},
];
/***/ }),
/* 122 */
/*!*************************************!*\
!*** ./src/data/gangmembertasks.ts ***!
\*************************************/
/*! no static exports found */
/*! exports used: gangMemberTasksMetadata */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* tslint:disable:max-line-length */
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Array of metadata for all Gang Member tasks. Used to construct the global GangMemberTask
* objects in Gang.js
*/
exports.gangMemberTasksMetadata = [
{
desc: "This gang member is currently idle",
isCombat: true,
isHacking: true,
name: "Unassigned",
params: { hackWeight: 100 },
},
{
desc: "Assign this gang member to create and distribute ransomware<br><br>Earns money - Slightly increases respect - Slightly increases wanted level",
isCombat: false,
isHacking: true,
name: "Ransomware",
params: { baseRespect: 0.00005, baseWanted: 0.0001, baseMoney: 1, hackWeight: 100, difficulty: 1 },
},
{
desc: "Assign this gang member to attempt phishing scams and attacks<br><br>Earns money - Slightly increases respect - Slightly increases wanted level",
isCombat: false,
isHacking: true,
name: "Phishing",
params: { baseRespect: 0.00008, baseWanted: 0.003, baseMoney: 2.5, hackWeight: 85, chaWeight: 15, difficulty: 3.5 },
},
{
desc: "Assign this gang member to attempt identity theft<br><br>Earns money - Increases respect - Increases wanted level",
isCombat: false,
isHacking: true,
name: "Identity Theft",
params: { baseRespect: 0.0001, baseWanted: 0.075, baseMoney: 6, hackWeight: 80, chaWeight: 20, difficulty: 5 },
},
{
desc: "Assign this gang member to carry out DDoS attacks<br><br>Increases respect - Increases wanted level",
isCombat: false,
isHacking: true,
name: "DDoS Attacks",
params: { baseRespect: 0.0004, baseWanted: 0.2, hackWeight: 100, difficulty: 8 },
},
{
desc: "Assign this gang member to create and distribute malicious viruses<br><br>Increases respect - Increases wanted level",
isCombat: false,
isHacking: true,
name: "Plant Virus",
params: { baseRespect: 0.0006, baseWanted: 0.4, hackWeight: 100, difficulty: 12 },
},
{
desc: "Assign this gang member to commit financial fraud and digital counterfeiting<br><br>Earns money - Slightly increases respect - Slightly increases wanted level",
isCombat: false,
isHacking: true,
name: "Fraud & Counterfeiting",
params: { baseRespect: 0.0004, baseWanted: 0.3, baseMoney: 15, hackWeight: 80, chaWeight: 20, difficulty: 20 },
},
{
desc: "Assign this gang member to launder money<br><br>Earns money - Increases respect - Increases wanted level",
isCombat: false,
isHacking: true,
name: "Money Laundering",
params: { baseRespect: 0.001, baseWanted: 1.25, baseMoney: 120, hackWeight: 75, chaWeight: 25, difficulty: 25 },
},
{
desc: "Assign this gang member to commit acts of cyberterrorism<br><br>Greatly increases respect - Greatly increases wanted level",
isCombat: false,
isHacking: true,
name: "Cyberterrorism",
params: { baseRespect: 0.01, baseWanted: 6, hackWeight: 80, chaWeight: 20, difficulty: 36 },
},
{
desc: "Assign this gang member to be an ethical hacker for corporations<br><br>Earns money - Lowers wanted level",
isCombat: false,
isHacking: true,
name: "Ethical Hacking",
params: { baseWanted: -0.001, baseMoney: 1, hackWeight: 90, chaWeight: 10, difficulty: 1 },
},
{
desc: "Assign this gang member to mug random people on the streets<br><br>Earns money - Slightly increases respect - Very slightly increases wanted level",
isCombat: true,
isHacking: false,
name: "Mug People",
params: {
baseRespect: 0.00005, baseWanted: 0.00005, baseMoney: 1.2,
strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 10, chaWeight: 15,
difficulty: 1,
},
},
{
desc: "Assign this gang member to sell drugs<br><br>Earns money - Slightly increases respect - Slightly increases wanted level - Scales slightly with territory",
isCombat: true,
isHacking: false,
name: "Deal Drugs",
params: {
baseRespect: 0.00006, baseWanted: 0.002, baseMoney: 5,
agiWeight: 20, dexWeight: 20, chaWeight: 60,
difficulty: 3.5,
territory: {
money: 1.2,
respect: 1,
wanted: 1.15,
},
},
},
{
desc: "Assign this gang member to extort civilians in your territory<br><br>Earns money - Slightly increases respect - Increases wanted - Scales heavily with territory",
isCombat: true,
isHacking: false,
name: "Strongarm Civilians",
params: {
baseRespect: 0.00004, baseWanted: 0.02, baseMoney: 2.5,
hackWeight: 10, strWeight: 25, defWeight: 25, dexWeight: 20, agiWeight: 10, chaWeight: 10,
difficulty: 5,
territory: {
money: 1.6,
respect: 1.1,
wanted: 1.5
}
}
},
{
desc: "Assign this gang member to run cons<br><br>Earns money - Increases respect - Increases wanted level",
isCombat: true,
isHacking: false,
name: "Run a Con",
params: {
baseRespect: 0.00012, baseWanted: 0.05, baseMoney: 15,
strWeight: 5, defWeight: 5, agiWeight: 25, dexWeight: 25, chaWeight: 40,
difficulty: 14,
},
},
{
desc: "Assign this gang member to commit armed robbery on stores, banks and armored cars<br><br>Earns money - Increases respect - Increases wanted level",
isCombat: true,
isHacking: false,
name: "Armed Robbery",
params: {
baseRespect: 0.00014, baseWanted: 0.1, baseMoney: 38,
hackWeight: 20, strWeight: 15, defWeight: 15, agiWeight: 10, dexWeight: 20, chaWeight: 20,
difficulty: 20,
},
},
{
desc: "Assign this gang member to traffick illegal arms<br><br>Earns money - Increases respect - Increases wanted level - Scales heavily with territory",
isCombat: true,
isHacking: false,
name: "Traffick Illegal Arms",
params: {
baseRespect: 0.0002, baseWanted: 0.24, baseMoney: 58,
hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, chaWeight: 25,
difficulty: 32,
territory: {
money: 1.4,
respect: 1.3,
wanted: 1.25,
},
},
},
{
desc: "Assign this gang member to threaten and black mail high-profile targets<br><br>Earns money - Slightly increases respect - Slightly increases wanted level",
isCombat: true,
isHacking: false,
name: "Threaten & Blackmail",
params: {
baseRespect: 0.0002, baseWanted: 0.125, baseMoney: 24,
hackWeight: 25, strWeight: 25, dexWeight: 25, chaWeight: 25,
difficulty: 28,
},
},
{
desc: "Assign this gang member to engage in human trafficking operations<br><br>Earns money - Increases respect - Increases wanted level - Scales heavily with territory",
isCombat: true,
isHacking: false,
name: "Human Trafficking",
params: {
baseRespect: 0.004, baseWanted: 1.25, baseMoney: 120,
hackWeight: 30, strWeight: 5, defWeight: 5, dexWeight: 30, chaWeight: 30,
difficulty: 36,
territory: {
money: 1.5,
respect: 1.5,
wanted: 1.6,
}
}
},
{
desc: "Assign this gang member to commit acts of terrorism<br><br>Greatly increases respect - Greatly increases wanted level - Scales heavily with territory",
isCombat: true,
isHacking: false,
name: "Terrorism",
params: {
baseRespect: 0.01, baseWanted: 6,
hackWeight: 20, strWeight: 20, defWeight: 20, dexWeight: 20, chaWeight: 20,
difficulty: 36,
territory: {
money: 1,
respect: 2,
wanted: 2,
},
},
},
{
desc: "Assign this gang member to be a vigilante and protect the city from criminals<br><br>Decreases wanted level",
isCombat: true,
isHacking: true,
name: "Vigilante Justice",
params: {
baseWanted: -0.001,
hackWeight: 20, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight: 20,
difficulty: 1,
territory: {
money: 1,
respect: 1,
wanted: 0.9,
},
},
},
{
desc: "Assign this gang member to increase their combat stats (str, def, dex, agi)",
isCombat: true,
isHacking: true,
name: "Train Combat",
params: {
strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 25,
difficulty: 5
},
},
{
desc: "Assign this gang member to train their hacking skills",
isCombat: true,
isHacking: true,
name: "Train Hacking",
params: { hackWeight: 100, difficulty: 8 },
},
{
desc: "Assign this gang member to train their charisma",
isCombat: true,
isHacking: true,
name: "Train Charisma",
params: { chaWeight: 100, difficulty: 8 },
},
{
desc: "Assign this gang member to engage in territorial warfare with other gangs. Members assigned to this task will help increase your gang's territory and will defend your territory from being taken.",
isCombat: true,
isHacking: true,
name: "Territory Warfare",
params: {
hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight: 20, chaWeight: 5,
difficulty: 5
},
},
];
/***/ }),
/* 123 */
/*!***************************************!*\
!*** ./utils/FactionInvitationBox.js ***!
\***************************************/
/*! exports provided: factionInvitationBoxCreate */
/*! exports used: factionInvitationBoxCreate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factionInvitationBoxCreate; });
/* harmony import */ var _src_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Faction/FactionHelpers */ 44);
/* harmony import */ var _src_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../src/engine */ 8);
/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Player */ 0);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../src/ui/navigationTracking */ 12);
/* harmony import */ var _src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__);
/* Faction Invitation Pop-up box */
function factionInvitationBoxClose() {
var factionInvitationBox = document.getElementById("faction-invitation-box-container");
factionInvitationBox.style.display = "none";
}
function factionInvitationBoxOpen() {
var factionInvitationBox = document.getElementById("faction-invitation-box-container");
factionInvitationBox.style.display = "flex";
}
function factionInvitationSetText(txt) {
var textBox = document.getElementById("faction-invitation-box-text");
textBox.innerHTML = txt;
}
function factionInvitationSetMessage(msg) {
var msgBox = document.getElementById("faction-invitation-box-message");
msgBox.innerHTML = msg;
}
//ram argument is in GB
function factionInvitationBoxCreate(faction) {
factionInvitationSetText("You have received a faction invitation from " + faction.name);
faction.alreadyInvited = true;
_src_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].factionInvitations.push(faction.name);
if (_src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__["routing"].isOn(_src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__["Page"].Factions)) {
_src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionsContent();
}
var newYesButton = Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("faction-invitation-box-yes");
newYesButton.addEventListener("click", function() {
//Remove from invited factions
var i = _src_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].factionInvitations.findIndex((facName)=>{return facName === faction.name});
if (i === -1) {
console.error("Could not find faction in Player.factionInvitations");
} else {
_src_Player__WEBPACK_IMPORTED_MODULE_2__[/* Player */ "a"].factionInvitations.splice(i, 1);
}
Object(_src_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_0__[/* joinFaction */ "c"])(faction);
factionInvitationBoxClose();
if (_src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__["routing"].isOn(_src_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_4__["Page"].Factions)) {
_src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionsContent();
}
return false;
});
var noButton = Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("faction-invitation-box-no");
noButton.addEventListener("click", function() {
factionInvitationBoxClose();
return false;
});
factionInvitationBoxOpen();
}
/***/ }),
/* 124 */
/*!*****************************!*\
!*** ./src/data/servers.ts ***!
\*****************************/
/*! no static exports found */
/*! exports used: serverMetadata */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// tslint:disable:max-file-line-count
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The metadata for building up the servers on the network.
*/
exports.serverMetadata = [
{
hackDifficulty: 99,
hostname: "ecorp",
moneyAvailable: {
max: 70e9,
min: 30e9,
},
networkLayer: 15,
numOpenPortsRequired: 5,
organizationName: "ECorp",
requiredHackingSkill: {
max: 1400,
min: 1050,
},
serverGrowth: 99,
},
{
hackDifficulty: 99,
hostname: "megacorp",
moneyAvailable: {
max: 60e9,
min: 40e9,
},
networkLayer: 15,
numOpenPortsRequired: 5,
organizationName: "MegaCorp",
requiredHackingSkill: {
max: 1350,
min: 1100,
},
serverGrowth: 99,
},
{
hackDifficulty: {
max: 88,
min: 72,
},
hostname: "b-and-a",
moneyAvailable: {
max: 30e9,
min: 15e9,
},
networkLayer: 14,
numOpenPortsRequired: 5,
organizationName: "Bachman & Associates",
requiredHackingSkill: {
max: 1150,
min: 900,
},
serverGrowth: {
max: 80,
min: 60,
},
},
{
hackDifficulty: {
max: 97,
min: 88,
},
hostname: "blade",
literature: ["beyond-man.lit"],
maxRamExponent: {
max: 9,
min: 5,
},
moneyAvailable: {
max: 40e9,
min: 10e9,
},
networkLayer: 14,
numOpenPortsRequired: 5,
organizationName: "Blade Industries",
requiredHackingSkill: {
max: 1200,
min: 900,
},
serverGrowth: {
max: 85,
min: 55,
},
},
{
hackDifficulty: 99,
hostname: "nwo",
literature: ["the-hidden-world.lit"],
moneyAvailable: {
max: 40e9,
min: 20e9,
},
networkLayer: 14,
numOpenPortsRequired: 5,
organizationName: "New World Order",
requiredHackingSkill: {
max: 1300,
min: 950,
},
serverGrowth: {
max: 95,
min: 65,
},
},
{
hackDifficulty: {
max: 65,
min: 45,
},
hostname: "clarkinc",
literature: [
"beyond-man.lit",
"cost-of-immortality.lit",
],
moneyAvailable: {
max: 25e9,
min: 15e9,
},
networkLayer: 14,
numOpenPortsRequired: 5,
organizationName: "Clarke Incorporated",
requiredHackingSkill: {
max: 1250,
min: 950,
},
serverGrowth: {
max: 75,
min: 45,
},
},
{
hackDifficulty: {
max: 99,
min: 90,
},
hostname: "omnitek",
literature: [
"coded-intelligence.lit",
"history-of-synthoids.lit",
],
maxRamExponent: {
max: 9,
min: 7,
},
moneyAvailable: {
max: 22e9,
min: 13e9,
},
networkLayer: 13,
numOpenPortsRequired: 5,
organizationName: "OmniTek Incorporated",
requiredHackingSkill: {
max: 1100,
min: 900,
},
serverGrowth: {
max: 99,
min: 95,
},
},
{
hackDifficulty: {
max: 75,
min: 55,
},
hostname: "4sigma",
moneyAvailable: {
max: 25e9,
min: 15e9,
},
networkLayer: 13,
numOpenPortsRequired: 5,
organizationName: "FourSigma",
requiredHackingSkill: {
max: 1250,
min: 900,
},
serverGrowth: {
max: 99,
min: 75,
},
},
{
hackDifficulty: {
max: 99,
min: 95,
},
hostname: "kuai-gong",
moneyAvailable: {
max: 30e9,
min: 20e9,
},
networkLayer: 13,
numOpenPortsRequired: 5,
organizationName: "KuaiGong International",
requiredHackingSkill: {
max: 1300,
min: 950,
},
serverGrowth: {
max: 99,
min: 90,
},
},
{
hackDifficulty: {
max: 97,
min: 83,
},
hostname: "fulcrumtech",
literature: ["simulated-reality.lit"],
maxRamExponent: {
max: 11,
min: 7,
},
moneyAvailable: {
max: 1800e6,
min: 1400e6,
},
networkLayer: 12,
numOpenPortsRequired: 5,
organizationName: "Fulcrum Technologies",
requiredHackingSkill: {
max: 1250,
min: 950,
},
serverGrowth: {
max: 99,
min: 80,
},
},
{
hackDifficulty: 99,
hostname: "fulcrumassets",
moneyAvailable: 1e6,
networkLayer: 15,
numOpenPortsRequired: 5,
organizationName: "Fulcrum Technologies Assets",
requiredHackingSkill: {
max: 1600,
min: 1100,
},
serverGrowth: 1,
specialName: "Fulcrum Secret Technologies Server",
},
{
hackDifficulty: {
max: 92,
min: 78,
},
hostname: "stormtech",
moneyAvailable: {
max: 1200e6,
min: 1000e6,
},
networkLayer: 12,
numOpenPortsRequired: 5,
organizationName: "Storm Technologies",
requiredHackingSkill: {
max: 1075,
min: 875,
},
serverGrowth: {
max: 92,
min: 68,
},
},
{
hackDifficulty: {
max: 96,
min: 84,
},
hostname: "defcomm",
moneyAvailable: {
max: 950e6,
min: 800e6,
},
networkLayer: 9,
numOpenPortsRequired: 5,
organizationName: "DefComm",
requiredHackingSkill: {
max: 1050,
min: 850,
},
serverGrowth: {
max: 73,
min: 47,
},
},
{
hackDifficulty: {
max: 90,
min: 70,
},
hostname: "infocomm",
moneyAvailable: {
max: 900e6,
min: 600e6,
},
networkLayer: 10,
numOpenPortsRequired: 5,
organizationName: "InfoComm",
requiredHackingSkill: {
max: 950,
min: 875,
},
serverGrowth: {
max: 75,
min: 35,
},
},
{
hackDifficulty: {
max: 95,
min: 85,
},
hostname: "helios",
literature: ["beyond-man.lit"],
maxRamExponent: {
max: 8,
min: 5,
},
moneyAvailable: {
max: 750e6,
min: 550e6,
},
networkLayer: 12,
numOpenPortsRequired: 5,
organizationName: "Helios Labs",
requiredHackingSkill: {
max: 900,
min: 800,
},
serverGrowth: {
max: 80,
min: 70,
},
},
{
hackDifficulty: {
max: 90,
min: 80,
},
hostname: "vitalife",
literature: ["A-Green-Tomorrow.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 800e6,
min: 700e6,
},
networkLayer: 12,
numOpenPortsRequired: 5,
organizationName: "VitaLife",
requiredHackingSkill: {
max: 900,
min: 775,
},
serverGrowth: {
max: 80,
min: 60,
},
},
{
hackDifficulty: {
max: 95,
min: 85,
},
hostname: "icarus",
moneyAvailable: {
max: 1000e6,
min: 900e6,
},
networkLayer: 9,
numOpenPortsRequired: 5,
organizationName: "Icarus Microsystems",
requiredHackingSkill: {
max: 925,
min: 850,
},
serverGrowth: {
max: 95,
min: 85,
},
},
{
hackDifficulty: {
max: 90,
min: 80,
},
hostname: "univ-energy",
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 1200e6,
min: 1100e6,
},
networkLayer: 9,
numOpenPortsRequired: 4,
organizationName: "Universal Energy",
requiredHackingSkill: {
max: 900,
min: 800,
},
serverGrowth: {
max: 90,
min: 80,
},
},
{
hackDifficulty: {
max: 80,
min: 70,
},
hostname: "titan-labs",
literature: ["coded-intelligence.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 900000000,
min: 750000000,
},
networkLayer: 11,
numOpenPortsRequired: 5,
organizationName: "Titan Laboratories",
requiredHackingSkill: {
max: 875,
min: 800,
},
serverGrowth: {
max: 80,
min: 60,
},
},
{
hackDifficulty: {
max: 75,
min: 65,
},
hostname: "microdyne",
literature: ["synthetic-muscles.lit"],
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 700000000,
min: 500000000,
},
networkLayer: 11,
numOpenPortsRequired: 5,
organizationName: "Microdyne Technologies",
requiredHackingSkill: {
max: 875,
min: 800,
},
serverGrowth: {
max: 90,
min: 70,
},
},
{
hackDifficulty: {
max: 80,
min: 70,
},
hostname: "taiyang-digital",
literature: [
"A-Green-Tomorrow.lit",
"brighter-than-the-sun.lit",
],
moneyAvailable: {
max: 900000000,
min: 800000000,
},
networkLayer: 10,
numOpenPortsRequired: 5,
organizationName: "Taiyang Digital",
requiredHackingSkill: {
max: 950,
min: 850,
},
serverGrowth: {
max: 80,
min: 70,
},
},
{
hackDifficulty: {
max: 65,
min: 55,
},
hostname: "galactic-cyber",
moneyAvailable: {
max: 850000000,
min: 750000000,
},
networkLayer: 7,
numOpenPortsRequired: 5,
organizationName: "Galactic Cybersystems",
requiredHackingSkill: {
max: 875,
min: 825,
},
serverGrowth: {
max: 90,
min: 70,
},
},
{
hackDifficulty: {
max: 90,
min: 80,
},
hostname: "aerocorp",
literature: ["man-and-machine.lit"],
moneyAvailable: {
max: 1200000000,
min: 1000000000,
},
networkLayer: 7,
numOpenPortsRequired: 5,
organizationName: "AeroCorp",
requiredHackingSkill: {
max: 925,
min: 850,
},
serverGrowth: {
max: 65,
min: 55,
},
},
{
hackDifficulty: {
max: 95,
min: 85,
},
hostname: "omnia",
literature: ["history-of-synthoids.lit"],
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 1000000000,
min: 900000000,
},
networkLayer: 8,
numOpenPortsRequired: 5,
organizationName: "Omnia Cybersystems",
requiredHackingSkill: {
max: 950,
min: 850,
},
serverGrowth: {
max: 70,
min: 60,
},
},
{
hackDifficulty: {
max: 65,
min: 55,
},
hostname: "zb-def",
literature: ["synthetic-muscles.lit"],
moneyAvailable: {
max: 1100000000,
min: 900000000,
},
networkLayer: 10,
numOpenPortsRequired: 4,
organizationName: "ZB Defense Industries",
requiredHackingSkill: {
max: 825,
min: 775,
},
serverGrowth: {
max: 75,
min: 65,
},
},
{
hackDifficulty: {
max: 80,
min: 60,
},
hostname: "applied-energetics",
moneyAvailable: {
max: 1000000000,
min: 700000000,
},
networkLayer: 11,
numOpenPortsRequired: 4,
organizationName: "Applied Energetics",
requiredHackingSkill: {
max: 850,
min: 775,
},
serverGrowth: {
max: 75,
min: 70,
},
},
{
hackDifficulty: {
max: 80,
min: 70,
},
hostname: "solaris",
literature: [
"A-Green-Tomorrow.lit",
"the-failed-frontier.lit",
],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 900000000,
min: 700000000,
},
networkLayer: 9,
numOpenPortsRequired: 5,
organizationName: "Solaris Space Systems",
requiredHackingSkill: {
max: 850,
min: 750,
},
serverGrowth: {
max: 80,
min: 70,
},
},
{
hackDifficulty: {
max: 85,
min: 75,
},
hostname: "deltaone",
moneyAvailable: {
max: 1700000000,
min: 1300000000,
},
networkLayer: 8,
numOpenPortsRequired: 5,
organizationName: "Delta One",
requiredHackingSkill: {
max: 900,
min: 800,
},
serverGrowth: {
max: 70,
min: 50,
},
},
{
hackDifficulty: {
max: 85,
min: 75,
},
hostname: "global-pharm",
literature: ["A-Green-Tomorrow.lit"],
maxRamExponent: {
max: 6,
min: 3,
},
moneyAvailable: {
max: 1750000000,
min: 1500000000,
},
networkLayer: 7,
numOpenPortsRequired: 4,
organizationName: "Global Pharmaceuticals",
requiredHackingSkill: {
max: 850,
min: 750,
},
serverGrowth: {
max: 90,
min: 80,
},
},
{
hackDifficulty: {
max: 80,
min: 60,
},
hostname: "nova-med",
moneyAvailable: {
max: 1250000000,
min: 1100000000,
},
networkLayer: 10,
numOpenPortsRequired: 4,
organizationName: "Nova Medical",
requiredHackingSkill: {
max: 850,
min: 775,
},
serverGrowth: {
max: 85,
min: 65,
},
},
{
hackDifficulty: {
max: 90,
min: 70,
},
hostname: "zeus-med",
moneyAvailable: {
max: 1500000000,
min: 1300000000,
},
networkLayer: 9,
numOpenPortsRequired: 5,
organizationName: "Zeus Medical",
requiredHackingSkill: {
max: 850,
min: 800,
},
serverGrowth: {
max: 80,
min: 70,
},
},
{
hackDifficulty: {
max: 80,
min: 70,
},
hostname: "unitalife",
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 1100000000,
min: 1000000000,
},
networkLayer: 8,
numOpenPortsRequired: 4,
organizationName: "UnitaLife Group",
requiredHackingSkill: {
max: 825,
min: 775,
},
serverGrowth: {
max: 80,
min: 70,
},
},
{
hackDifficulty: {
max: 80,
min: 60,
},
hostname: "lexo-corp",
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 800000000,
min: 700000000,
},
networkLayer: 6,
numOpenPortsRequired: 4,
organizationName: "Lexo Corporation",
requiredHackingSkill: {
max: 750,
min: 650,
},
serverGrowth: {
max: 65,
min: 55,
},
},
{
hackDifficulty: {
max: 60,
min: 40,
},
hostname: "rho-construction",
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 700000000,
min: 500000000,
},
networkLayer: 6,
numOpenPortsRequired: 3,
organizationName: "Rho Construction",
requiredHackingSkill: {
max: 525,
min: 475,
},
serverGrowth: {
max: 60,
min: 40,
},
},
{
hackDifficulty: {
max: 70,
min: 50,
},
hostname: "alpha-ent",
literature: ["sector-12-crime.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 750000000,
min: 600000000,
},
networkLayer: 6,
numOpenPortsRequired: 4,
organizationName: "Alpha Enterprises",
requiredHackingSkill: {
max: 600,
min: 500,
},
serverGrowth: {
max: 60,
min: 50,
},
},
{
hackDifficulty: {
max: 80,
min: 70,
},
hostname: "aevum-police",
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 400000000,
min: 200000000,
},
networkLayer: 6,
numOpenPortsRequired: 4,
organizationName: "Aevum Police Network",
requiredHackingSkill: {
max: 450,
min: 400,
},
serverGrowth: {
max: 50,
min: 30,
},
},
{
hackDifficulty: {
max: 55,
min: 45,
},
hostname: "rothman-uni",
literature: [
"secret-societies.lit",
"the-failed-frontier.lit",
"tensions-in-tech-race.lit",
],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 250000000,
min: 175000000,
},
networkLayer: 5,
numOpenPortsRequired: 3,
organizationName: "Rothman University Network",
requiredHackingSkill: {
max: 430,
min: 370,
},
serverGrowth: {
max: 45,
min: 35,
},
},
{
hackDifficulty: {
max: 85,
min: 65,
},
hostname: "zb-institute",
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 1100000000,
min: 800000000,
},
networkLayer: 5,
numOpenPortsRequired: 5,
organizationName: "ZB Institute of Technology Network",
requiredHackingSkill: {
max: 775,
min: 725,
},
serverGrowth: {
max: 85,
min: 75,
},
},
{
hackDifficulty: {
max: 65,
min: 45,
},
hostname: "summit-uni",
literature: [
"secret-societies.lit",
"the-failed-frontier.lit",
"synthetic-muscles.lit",
],
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: {
max: 350000000,
min: 200000000,
},
networkLayer: 5,
numOpenPortsRequired: 3,
organizationName: "Summit University Network",
requiredHackingSkill: {
max: 475,
min: 425,
},
serverGrowth: {
max: 60,
min: 40,
},
},
{
hackDifficulty: {
max: 80,
min: 60,
},
hostname: "syscore",
moneyAvailable: {
max: 600000000,
min: 400000000,
},
networkLayer: 5,
numOpenPortsRequired: 4,
organizationName: "SysCore Securities",
requiredHackingSkill: {
max: 650,
min: 550,
},
serverGrowth: {
max: 70,
min: 60,
},
},
{
hackDifficulty: {
max: 70,
min: 60,
},
hostname: "catalyst",
literature: ["tensions-in-tech-race.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: {
max: 550000000,
min: 300000000,
},
networkLayer: 5,
numOpenPortsRequired: 3,
organizationName: "Catalyst Ventures",
requiredHackingSkill: {
max: 450,
min: 400,
},
serverGrowth: {
max: 55,
min: 25,
},
},
{
hackDifficulty: {
max: 45,
min: 35,
},
hostname: "the-hub",
maxRamExponent: {
max: 6,
min: 3,
},
moneyAvailable: {
max: 200000000,
min: 150000000,
},
networkLayer: 4,
numOpenPortsRequired: 2,
organizationName: "The Hub",
requiredHackingSkill: {
max: 325,
min: 275,
},
serverGrowth: {
max: 55,
min: 45,
},
},
{
hackDifficulty: {
max: 65,
min: 55,
},
hostname: "comptek",
literature: ["man-and-machine.lit"],
moneyAvailable: {
max: 250000000,
min: 220000000,
},
networkLayer: 4,
numOpenPortsRequired: 3,
organizationName: "CompuTek",
requiredHackingSkill: {
max: 400,
min: 300,
},
serverGrowth: {
max: 65,
min: 45,
},
},
{
hackDifficulty: {
max: 80,
min: 60,
},
hostname: "netlink",
literature: ["simulated-reality.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: 275000000,
networkLayer: 4,
numOpenPortsRequired: 3,
organizationName: "Netlink Technologies",
requiredHackingSkill: {
max: 425,
min: 375,
},
serverGrowth: {
max: 75,
min: 45,
},
},
{
hackDifficulty: {
max: 65,
min: 35,
},
hostname: "johnson-ortho",
moneyAvailable: {
max: 85000000,
min: 70000000,
},
networkLayer: 4,
numOpenPortsRequired: 2,
organizationName: "Johnson Orthopedics",
requiredHackingSkill: {
max: 300,
min: 250,
},
serverGrowth: {
max: 65,
min: 35,
},
},
{
hackDifficulty: 10,
hostname: "foodnstuff",
literature: ["sector-12-crime.lit"],
maxRamExponent: 4,
moneyAvailable: 2000000,
networkLayer: 1,
numOpenPortsRequired: 0,
organizationName: "Food N Stuff Supermarket",
requiredHackingSkill: 1,
serverGrowth: 5,
},
{
hackDifficulty: 10,
hostname: "sigma-cosmetics",
maxRamExponent: 4,
moneyAvailable: 2300000,
networkLayer: 1,
numOpenPortsRequired: 0,
organizationName: "Sigma Cosmetics",
requiredHackingSkill: 5,
serverGrowth: 10,
},
{
hackDifficulty: 15,
hostname: "joesguns",
maxRamExponent: 4,
moneyAvailable: 2500000,
networkLayer: 1,
numOpenPortsRequired: 0,
organizationName: "Joe's Guns",
requiredHackingSkill: 10,
serverGrowth: 20,
},
{
hackDifficulty: 25,
hostname: "zer0",
maxRamExponent: 5,
moneyAvailable: 7500000,
networkLayer: 2,
numOpenPortsRequired: 1,
organizationName: "ZER0 Nightclub",
requiredHackingSkill: 75,
serverGrowth: 40,
},
{
hackDifficulty: 20,
hostname: "nectar-net",
maxRamExponent: 4,
moneyAvailable: 2750000,
networkLayer: 2,
numOpenPortsRequired: 0,
organizationName: "Nectar Nightclub Network",
requiredHackingSkill: 20,
serverGrowth: 25,
},
{
hackDifficulty: 25,
hostname: "neo-net",
literature: ["the-hidden-world.lit"],
maxRamExponent: 5,
moneyAvailable: 5000000,
networkLayer: 3,
numOpenPortsRequired: 1,
organizationName: "Neo Nightclub Network",
requiredHackingSkill: 50,
serverGrowth: 25,
},
{
hackDifficulty: 30,
hostname: "silver-helix",
literature: ["new-triads.lit"],
maxRamExponent: 6,
moneyAvailable: 45000000,
networkLayer: 3,
numOpenPortsRequired: 2,
organizationName: "Silver Helix",
requiredHackingSkill: 150,
serverGrowth: 30,
},
{
hackDifficulty: 15,
hostname: "hong-fang-tea",
literature: ["brighter-than-the-sun.lit"],
maxRamExponent: 4,
moneyAvailable: 3000000,
networkLayer: 1,
numOpenPortsRequired: 0,
organizationName: "HongFang Teahouse",
requiredHackingSkill: 30,
serverGrowth: 20,
},
{
hackDifficulty: 15,
hostname: "harakiri-sushi",
maxRamExponent: 4,
moneyAvailable: 4000000,
networkLayer: 1,
numOpenPortsRequired: 0,
organizationName: "HaraKiri Sushi Bar Network",
requiredHackingSkill: 40,
serverGrowth: 40,
},
{
hackDifficulty: 20,
hostname: "phantasy",
maxRamExponent: 5,
moneyAvailable: 24000000,
networkLayer: 3,
numOpenPortsRequired: 2,
organizationName: "Phantasy Club",
requiredHackingSkill: 100,
serverGrowth: 35,
},
{
hackDifficulty: 15,
hostname: "max-hardware",
maxRamExponent: 5,
moneyAvailable: 10000000,
networkLayer: 2,
numOpenPortsRequired: 1,
organizationName: "Max Hardware Store",
requiredHackingSkill: 80,
serverGrowth: 30,
},
{
hackDifficulty: {
max: 35,
min: 25,
},
hostname: "omega-net",
literature: ["the-new-god.lit"],
maxRamExponent: 5,
moneyAvailable: {
max: 70000000,
min: 60000000,
},
networkLayer: 3,
numOpenPortsRequired: 2,
organizationName: "Omega Software",
requiredHackingSkill: {
max: 220,
min: 180,
},
serverGrowth: {
max: 40,
min: 30,
},
},
{
hackDifficulty: {
max: 45,
min: 35,
},
hostname: "crush-fitness",
moneyAvailable: {
max: 60000000,
min: 40000000,
},
networkLayer: 4,
numOpenPortsRequired: 2,
organizationName: "Crush Fitness",
requiredHackingSkill: {
max: 275,
min: 225,
},
serverGrowth: {
max: 33,
min: 27,
},
},
{
hackDifficulty: 30,
hostname: "iron-gym",
maxRamExponent: 5,
moneyAvailable: 20000000,
networkLayer: 1,
numOpenPortsRequired: 1,
organizationName: "Iron Gym Network",
requiredHackingSkill: 100,
serverGrowth: 20,
},
{
hackDifficulty: {
max: 55,
min: 45,
},
hostname: "millenium-fitness",
maxRamExponent: {
max: 8,
min: 4,
},
moneyAvailable: 250000000,
networkLayer: 6,
numOpenPortsRequired: 3,
organizationName: "Millenium Fitness Network",
requiredHackingSkill: {
max: 525,
min: 475,
},
serverGrowth: {
max: 45,
min: 25,
},
},
{
hackDifficulty: {
max: 65,
min: 55,
},
hostname: "powerhouse-fitness",
maxRamExponent: {
max: 6,
min: 4,
},
moneyAvailable: 900000000,
networkLayer: 14,
numOpenPortsRequired: 5,
organizationName: "Powerhouse Fitness",
requiredHackingSkill: {
max: 1100,
min: 950,
},
serverGrowth: {
max: 60,
min: 50,
},
},
{
hackDifficulty: {
max: 60,
min: 40,
},
hostname: "snap-fitness",
moneyAvailable: 450000000,
networkLayer: 7,
numOpenPortsRequired: 4,
organizationName: "Snap Fitness",
requiredHackingSkill: {
max: 800,
min: 675,
},
serverGrowth: {
max: 60,
min: 40,
},
},
{
hackDifficulty: 0,
hostname: "run4theh111z",
literature: [
"simulated-reality.lit",
"the-new-god.lit",
],
maxRamExponent: {
max: 9,
min: 5,
},
moneyAvailable: 0,
networkLayer: 11,
numOpenPortsRequired: 4,
organizationName: "The Runners",
requiredHackingSkill: {
max: 550,
min: 505,
},
serverGrowth: 0,
specialName: "BitRunners Server",
},
{
hackDifficulty: 0,
hostname: "I.I.I.I",
literature: ["democracy-is-dead.lit"],
maxRamExponent: {
max: 8,
min: 4,
},
moneyAvailable: 0,
networkLayer: 5,
numOpenPortsRequired: 3,
organizationName: "I.I.I.I",
requiredHackingSkill: {
max: 365,
min: 340,
},
serverGrowth: 0,
specialName: "The Black Hand Server",
},
{
hackDifficulty: 0,
hostname: "avmnite-02h",
literature: ["democracy-is-dead.lit"],
maxRamExponent: {
max: 7,
min: 4,
},
moneyAvailable: 0,
networkLayer: 4,
numOpenPortsRequired: 2,
organizationName: "NiteSec",
requiredHackingSkill: {
max: 220,
min: 202,
},
serverGrowth: 0,
specialName: "NiteSec Server",
},
{
hackDifficulty: 0,
hostname: ".",
maxRamExponent: 4,
moneyAvailable: 0,
networkLayer: 13,
numOpenPortsRequired: 4,
organizationName: ".",
requiredHackingSkill: {
max: 550,
min: 505,
},
serverGrowth: 0,
specialName: "The Dark Army Server",
},
{
hackDifficulty: 0,
hostname: "CSEC",
literature: ["democracy-is-dead.lit"],
maxRamExponent: 3,
moneyAvailable: 0,
networkLayer: 2,
numOpenPortsRequired: 1,
organizationName: "CyberSec",
requiredHackingSkill: {
max: 60,
min: 51,
},
serverGrowth: 0,
specialName: "CyberSec Server",
},
{
hackDifficulty: 0,
hostname: "The-Cave",
literature: ["alpha-omega.lit"],
moneyAvailable: 0,
networkLayer: 15,
numOpenPortsRequired: 5,
organizationName: "Helios",
requiredHackingSkill: 925,
serverGrowth: 0,
specialName: "Daedalus Server",
},
{
hackDifficulty: 0,
hostname: "w0r1d_d43m0n",
moneyAvailable: 0,
numOpenPortsRequired: 5,
organizationName: "w0r1d_d43m0n",
requiredHackingSkill: 3000,
serverGrowth: 0,
specialName: "w0r1d_d43m0n",
},
];
/***/ }),
/* 125 */
/*!**********************************!*\
!*** ./utils/InfiltrationBox.js ***!
\**********************************/
/*! exports provided: infiltrationBoxCreate */
/*! exports used: infiltrationBoxCreate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return infiltrationBoxCreate; });
/* harmony import */ var _src_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/BitNodeMultipliers */ 10);
/* harmony import */ var _src_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_src_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _src_Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../src/Constants */ 1);
/* harmony import */ var _src_Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_src_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _src_Faction_Faction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Faction/Faction */ 54);
/* harmony import */ var _src_Faction_Faction__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_src_Faction_Faction__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _src_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../src/Faction/Factions */ 15);
/* harmony import */ var _src_Faction_Factions__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_src_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../src/Player */ 0);
/* harmony import */ var _DialogBox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DialogBox */ 9);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 16);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./StringHelperFunctions */ 3);
/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__);
//Keep track of last faction
var lastFac = "";
/* InfiltrationBox.js */
function infiltrationBoxClose() {
var box = document.getElementById("infiltration-box-container");
box.style.display = "none";
}
function infiltrationBoxOpen() {
var box = document.getElementById("infiltration-box-container");
box.style.display = "flex";
}
function infiltrationSetText(txt) {
var textBox = document.getElementById("infiltration-box-text");
textBox.innerHTML = txt;
}
//ram argument is in GB
function infiltrationBoxCreate(inst) {
//Gain exp
var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel;
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainHackingExp(inst.hackingExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainStrengthExp(inst.strExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainDefenseExp(inst.defExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainDexterityExp(inst.dexExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainAgilityExp(inst.agiExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainCharismaExp(inst.chaExpGained * expMultiplier);
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainIntelligenceExp(inst.intExpGained * expMultiplier);
const expGainText = ["You gained:",
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.hackingExpGained * expMultiplier, 3)} hacking exp`,
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.strExpGained * expMultiplier, 3)} str exp`,
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.defExpGained * expMultiplier, 3)} def exp`,
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.dexExpGained * expMultiplier, 3)} dex exp`,
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.agiExpGained * expMultiplier, 3)} agi exp`,
`${Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.chaExpGained * expMultiplier, 3)} cha exp`].join("\n");
var totalValue = 0;
for (var i = 0; i < inst.secretsStolen.length; ++i) {
totalValue += inst.secretsStolen[i];
}
if (totalValue == 0) {
Object(_DialogBox__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("You successfully escaped the facility but you did not steal " +
"anything of worth when infiltrating.<br><br>" + expGainText);
return;
}
var facValue = totalValue * _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].faction_rep_mult *
_src_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _src_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
var moneyValue = totalValue * _src_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * _src_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
infiltrationSetText("You can sell the classified documents and secrets " +
"you stole from " + inst.companyName + " for <span class='money-gold'>$" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(moneyValue, 2) + "</span> on the black market or you can give it " +
"to a faction to gain <span class='light-yellow'>" + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(facValue, 3) + " reputation</span> with " +
"that faction.");
var selector = document.getElementById("infiltration-faction-select");
selector.innerHTML = "";
for (let i = 0; i < _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions.length; ++i) {
if (_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions[i] === "Bladeburners") { continue; }
if (_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].inGang() && _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gang.facName === _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions[i]) { continue; }
selector.innerHTML += "<option value='" + _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions[i] +
"'>" + _src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].factions[i] + "</option>";
}
//Set initial value, if applicable
if (lastFac !== "") {
for (let i = 0; i < selector.options.length; ++i) {
if (selector.options[i].value === lastFac) {
selector.selectedIndex = i;
break;
}
}
}
var sellButton = Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("infiltration-box-sell");
setTimeout(function() {
sellButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
_src_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(moneyValue);
Object(_DialogBox__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("You sold the classified information you stole from " + inst.companyName +
" for <span class='money-gold'>$" + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(moneyValue, 2) + "</span> on the black market!<br><br>" +
expGainText);
infiltrationBoxClose();
return false;
});
}, 750);
var factionButton = Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("infiltration-box-faction");
setTimeout(function() {
factionButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var facName = selector.options[selector.selectedIndex].value;
lastFac = facName;
var faction = _src_Faction_Factions__WEBPACK_IMPORTED_MODULE_3__["Factions"][facName];
if (faction == null) {
Object(_DialogBox__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("Error finding faction. This is a bug please report to developer");
return false;
}
faction.playerReputation += facValue;
Object(_DialogBox__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("You gave the classified information you stole from " + inst.companyName +
" to " + facName + " and gained <span class='light-yellow'>" + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(facValue, 3) + " reputation</span> with the faction. <br><br>" +
expGainText);
infiltrationBoxClose();
return false;
});
}, 750);
infiltrationBoxOpen();
}
/***/ }),
/* 126 */
/*!*****************************!*\
!*** ./src/Infiltration.js ***!
\*****************************/
/*! exports provided: beginInfiltration */
/*! exports used: beginInfiltration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return beginInfiltration; });
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10);
/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 0);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox */ 9);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 16);
/* 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_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 14);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_InfiltrationBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/InfiltrationBox */ 125);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 3);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__);
/* Infiltration.js
*
* Kill
* Knockout (nonlethal)
* Stealth Knockout (nonlethal)
* Assassinate
*
* Hack Security
* Destroy Security
* Sneak past Security
*
* Pick the locked door
*
* Bribe security
*
* Escape
*/
let InfiltrationScenarios = {
Guards: "You see an armed security guard patrolling the area.",
TechOnly: "The area is equipped with a state-of-the-art security system: cameras, laser tripwires, and sentry turrets.",
TechOrLockedDoor: "The area is equipped with a state-of-the-art security system. There is a locked door on the side of the " +
"room that can be used to bypass security.",
Bots: "You see a few security bots patrolling the area.",
}
function InfiltrationInstance(companyName, startLevel, val, maxClearance, diff) {
this.companyName = companyName;
this.clearanceLevel = 0;
this.maxClearanceLevel = maxClearance;
this.securityLevel = startLevel;
this.difficulty = diff; //Affects how much security level increases. Represents a percentage
this.baseValue = val; //Base value of company secrets
this.secretsStolen = []; //Numbers representing value of stolen secrets
this.hackingExpGained = 0;
this.strExpGained = 0;
this.defExpGained = 0;
this.dexExpGained = 0;
this.agiExpGained = 0;
this.chaExpGained = 0;
this.intExpGained = 0;
}
InfiltrationInstance.prototype.gainHackingExp = function(amt) {
if (isNaN(amt)) {return;}
this.hackingExpGained += amt;
}
InfiltrationInstance.prototype.gainStrengthExp = function(amt) {
if (isNaN(amt)) {return;}
this.strExpGained += amt;
}
InfiltrationInstance.prototype.gainDefenseExp = function(amt) {
if (isNaN(amt)) {return;}
this.defExpGained += amt;
}
InfiltrationInstance.prototype.gainDexterityExp = function(amt) {
if (isNaN(amt)) {return;}
this.dexExpGained += amt;
}
InfiltrationInstance.prototype.gainAgilityExp = function(amt) {
if (isNaN(amt)) {return;}
this.agiExpGained += amt;
}
InfiltrationInstance.prototype.gainCharismaExp = function(amt) {
if (isNaN(amt)) {return;}
this.chaExpGained += amt;
}
InfiltrationInstance.prototype.gainIntelligenceExp = function(amt) {
if (isNaN(amt)) {return;}
this.intExpGained += amt;
}
function beginInfiltration(companyName, startLevel, val, maxClearance, diff) {
var inst = new InfiltrationInstance(companyName, startLevel, val, maxClearance, diff);
clearInfiltrationStatusText();
nextInfiltrationLevel(inst);
}
function endInfiltration(inst, success) {
if (success) {Object(_utils_InfiltrationBox__WEBPACK_IMPORTED_MODULE_7__[/* infiltrationBoxCreate */ "a"])(inst);}
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].loadLocationContent();
}
function nextInfiltrationLevel(inst) {
++inst.clearanceLevel;
updateInfiltrationLevelText(inst);
//Buttons
var killButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
var knockoutButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
var stealthKnockoutButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
var assassinateButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
var hackSecurityButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
var destroySecurityButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
var sneakButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
var pickdoorButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
var bribeButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
var escapeButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
killButton.style.display = "none";
knockoutButton.style.display = "none";
stealthKnockoutButton.style.display = "none";
assassinateButton.style.display = "none";
hackSecurityButton.style.display = "none";
destroySecurityButton.style.display = "none";
sneakButton.style.display = "none";
pickdoorButton.style.display = "none";
bribeButton.style.display = "none";
escapeButton.style.display = "none";
var rand = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(0, 5); //This needs to change if more scenarios are added
var scenario = null;
switch (rand) {
case 1:
scenario = InfiltrationScenarios.TechOnly;
hackSecurityButton.style.display = "block";
destroySecurityButton.style.display = "block";
sneakButton.style.display = "block";
escapeButton.style.display = "block";
break;
case 2:
scenario = InfiltrationScenarios.TechOrLockedDoor;
hackSecurityButton.style.display = "block";
destroySecurityButton.style.display = "block";
sneakButton.style.display = "block";
pickdoorButton.style.display = "block";
escapeButton.style.display = "block";
break;
case 3:
scenario = InfiltrationScenarios.Bots;
killButton.style.display = "block";
killButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationKill(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> killed the security bots! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
"level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense));
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to kill the security bots. The bots fight back " +
"and raise the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
assassinateButton.style.display = "block";
assassinateButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> assassinated the security bots without being detected!");
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to assassinate the security bots. The bots have not detected " +
"you but are now more alert for an intruder. The facility's security level " +
"has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
hackSecurityButton.style.display = "block";
sneakButton.style.display = "block";
escapeButton.style.display = "block";
break;
default: //0, 4-5
scenario = InfiltrationScenarios.Guards;
killButton.style.display = "block";
killButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationKill(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> killed the security guard! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
"level has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].karma -= 3;
++_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense));
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to kill the security guard. The guard fights back " +
"and raises the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level has increased by " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
knockoutButton.style.display = "block";
stealthKnockoutButton.style.display = "block";
assassinateButton.style.display = "block";
assassinateButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> assassinated the security guard without being detected!");
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].karma -= 3;
++_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to assassinate the security guard. The guard has not detected " +
"you but is now more alert for an intruder. The facility's security level " +
"has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
sneakButton.style.display = "block";
bribeButton.style.display = "block";
escapeButton.style.display = "block";
break;
}
knockoutButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationKnockout(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> knocked out the security guard! " +
"Unfortunately you made a lot of noise and alerted other security.");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense));
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
stealthKnockoutButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationStealthKnockout(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> knocked out the security guard without making " +
"any noise!");
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense));
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to stealthily knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
hackSecurityButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationHack(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> hacked and disabled the security system!");
writeInfiltrationStatusText("The facility's security level increased by " + ((res[1]*100) - 100).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to hack the security system. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
destroySecurityButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationDestroySecurity(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> and violently destroy the security system!");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to destroy the security system. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
sneakButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationSneak(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> sneak past the security undetected!");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> and were detected while trying to sneak past security! The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
pickdoorButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationPickLockedDoor(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> pick the locked door!");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to pick the locked door. The facility's security level " +
"increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
bribeButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var bribeAmt = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationBribeBaseAmount * inst.clearanceLevel;
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].money.lt(bribeAmt)) {
writeInfiltrationStatusText("You do not have enough money to bribe the guard. " +
"You need $" + bribeAmt);
return false;
}
var res = attemptInfiltrationBribe(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> bribed a guard to let you through " +
"to the next clearance level for $" + bribeAmt);
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].loseMoney(bribeAmt);
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to bribe a guard! The guard is alerting " +
"other security guards about your presence! The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
escapeButton.addEventListener("click", function(e) {
if (!e.isTrusted) {return false;}
var res = attemptInfiltrationEscape(inst);
if (res[0]) {
writeInfiltrationStatusText("You <span class='success'>SUCCESSFULLY</span> escape from the facility with the stolen classified " +
"documents and company secrets!");
endInfiltration(inst, true);
return false;
} else {
writeInfiltrationStatusText("You <span class='failure'>FAILED</span> to escape from the facility. You took 1 damage. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].takeDamage(1)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
updateInfiltrationButtons(inst, scenario);
writeInfiltrationStatusText("");
writeInfiltrationStatusText("You are now on clearance level " + inst.clearanceLevel + ".<br>" +
scenario);
}
function endInfiltrationLevel(inst) {
//Check if you gained any secrets
if (inst.clearanceLevel % 5 == 0) {
var baseSecretValue = inst.baseValue * inst.clearanceLevel / 2;
var secretValue = baseSecretValue * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].faction_rep_mult *
_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
var secretMoneyValue = baseSecretValue * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
inst.secretsStolen.push(baseSecretValue);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You found and stole a set of classified documents from the company. " +
"These classified secrets could probably be sold for money (<span class='money-gold'>$" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(secretMoneyValue, 2) + "</span>), or they " +
"could be given to factions for reputation (<span class='light-yellow'>" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(secretValue, 3) + " rep</span>)");
}
//Increase security level based on difficulty
inst.securityLevel *= (1 + (inst.difficulty / 100));
writeInfiltrationStatusText("You move on to the facility's next clearance level. This " +
"clearance level has " + inst.difficulty + "% higher security");
//If this is max level, force endInfiltration
if (inst.clearanceLevel >= inst.maxClearanceLevel) {
endInfiltration(inst, true);
} else {
nextInfiltrationLevel(inst);
}
}
function writeInfiltrationStatusText(txt) {
var statusTxt = document.getElementById("infiltration-status-text");
statusTxt.innerHTML += (txt + "<br>");
statusTxt.parentElement.scrollTop = statusTxt.scrollHeight;
}
function clearInfiltrationStatusText() {
document.getElementById("infiltration-status-text").innerHTML = "";
}
function updateInfiltrationLevelText(inst) {
var totalValue = 0;
var totalMoneyValue = 0;
for (var i = 0; i < inst.secretsStolen.length; ++i) {
totalValue += (inst.secretsStolen[i] * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].faction_rep_mult *
_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep);
totalMoneyValue += inst.secretsStolen[i] * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
}
var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel;
// TODO: fix this to not rely on <pre> and whitespace for formatting...
/* eslint-disable no-irregular-whitespace */
document.getElementById("infiltration-level-text").innerHTML =
"Facility name:    " + inst.companyName + "<br>" +
"Clearance Level:  " + inst.clearanceLevel + "<br>" +
"Security Level:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.securityLevel, 3) + "<br><br>" +
"Total value of stolen secrets<br>" +
"Reputation:       <span class='light-yellow'>" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(totalValue, 3) + "</span><br>" +
"Money:           <span class='money-gold'>$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(totalMoneyValue, 2) + "</span><br><br>" +
"Hack exp gained:  " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.hackingExpGained * expMultiplier, 3) + "<br>" +
"Str exp gained:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.strExpGained * expMultiplier, 3) + "<br>" +
"Def exp gained:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.defExpGained * expMultiplier, 3) + "<br>" +
"Dex exp gained:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.dexExpGained * expMultiplier, 3) + "<br>" +
"Agi exp gained:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.agiExpGained * expMultiplier, 3) + "<br>" +
"Cha exp gained:   " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(inst.chaExpGained * expMultiplier, 3);
/* eslint-enable no-irregular-whitespace */
}
function updateInfiltrationButtons(inst, scenario) {
var killChance = getInfiltrationKillChance(inst);
var knockoutChance = getInfiltrationKnockoutChance(inst);
var stealthKnockoutChance = getInfiltrationStealthKnockoutChance(inst);
var assassinateChance = getInfiltrationAssassinateChance(inst);
var destroySecurityChance = getInfiltrationDestroySecurityChance(inst);
var hackChance = getInfiltrationHackChance(inst);
var sneakChance = getInfiltrationSneakChance(inst);
var lockpickChance = getInfiltrationPickLockedDoorChance(inst);
var bribeChance = getInfiltrationBribeChance(inst);
var escapeChance = getInfiltrationEscapeChance(inst);
document.getElementById("infiltration-escape").innerHTML = "Escape" +
"<span class='tooltiptext'>" +
"Attempt to escape the facility with the classified secrets and " +
"documents you have stolen. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(escapeChance*100, 2) + "% chance of success. If you fail, " +
"the security level will increase by 5%.</span>";
switch(scenario) {
case InfiltrationScenarios.TechOrLockedDoor:
document.getElementById("infiltration-pickdoor").innerHTML = "Lockpick" +
"<span class='tooltiptext'>" +
"Attempt to pick the locked door. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(lockpickChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increased by 1%. If you fail, the " +
"security level will increase by 3%.</span>";
case InfiltrationScenarios.TechOnly:
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack" +
"<span class='tooltiptext'>" +
"Attempt to hack and disable the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, " +
"the security level will increase by 5%.</span>";
document.getElementById("infiltration-destroysecurity").innerHTML = "Destroy security" +
"<span class='tooltiptext'>" +
"Attempt to violently destroy the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(destroySecurityChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, the " +
"security level will increase by 10%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
break;
case InfiltrationScenarios.Bots:
document.getElementById("infiltration-kill").innerHTML = "Destroy bots" +
"<span class='tooltiptext'>" +
"Attempt to destroy the security bots through combat. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(killChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, " +
"the security level will increase by 10%. </span>";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate bots" +
"<span class='tooltiptext'>" +
"Attempt to stealthily destroy the security bots through assassination. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. </span>";
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack bots" +
"<span class='tooltiptext'>" +
"Attempt to disable the security bots by hacking them. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, " +
"the security level will increase by 5%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security bots. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
break;
case InfiltrationScenarios.Guards:
default:
document.getElementById("infiltration-kill").innerHTML = "Kill" +
"<span class='tooltiptext'>" +
"Attempt to kill the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(killChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, " +
"the security level will decrease by 10%. </span>";
document.getElementById("infiltration-knockout").innerHTML = "Knockout" +
"<span class='tooltiptext'>" +
"Attempt to knockout the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(knockoutChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, the " +
"security level will increase by 10%. </span>";
document.getElementById("infiltration-stealthknockout").innerHTML = "Stealth Knockout" +
"<span class='tooltiptext'>" +
"Attempt to stealthily knockout the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(stealthKnockoutChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. </span>";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate" +
"<span class='tooltiptext'>" +
"Attempt to assassinate the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 5%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
document.getElementById("infiltration-bribe").innerHTML = "Bribe" +
"<span class='tooltiptext'>" +
"Attempt to bribe the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(bribeChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 15%. </span>";
break;
}
}
let intWgt = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].IntelligenceInfiltrationWeight;
//Kill
//Success: 5%, Failure 10%, -Karma
function attemptInfiltrationKill(inst) {
var chance = getInfiltrationKillChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationKillChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility) / (1.45 * lvl));
}
//Knockout
//Success: 3%, Failure: 10%
function attemptInfiltrationKnockout(inst) {
var chance = getInfiltrationKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
return [true, 1.03];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility) / (1.7 * lvl));
}
//Stealth knockout
//Success: 0%, Failure: 10%
function attemptInfiltrationStealthKnockout(inst) {
var chance = getInfiltrationStealthKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 60) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 60) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationStealthKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(0.55 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength +
2 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
2 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility +
intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence) / (3 * lvl));
}
//Assassination
//Success: 0%, Failure: 5%, -Karma
function attemptInfiltrationAssassinate(inst) {
var chance = getInfiltrationAssassinateChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 55) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 55) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationAssassinateChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
0.5 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility +
intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence) / (2 * lvl));
}
//Destroy security
//Success: 5%, Failure: 10%
function attemptInfiltrationDestroySecurity(inst) {
var chance = getInfiltrationDestroySecurityChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationDestroySecurityChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].strength +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility) / (2 * lvl));
}
//Hack security
//Success: 3%, Failure: 5%
function attemptInfiltrationHack(inst) {
var chance = getInfiltrationHackChance(inst);
inst.gainHackingExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_exp_mult;
inst.gainIntelligenceExp(inst.securityLevel / 680);
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
return [true, 1.03];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationHackChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill +
(intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence)) / lvl);
}
//Sneak past security
//Success: 0%, Failure: 8%
function attemptInfiltrationSneak(inst) {
var chance = getInfiltrationSneakChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.08;
return [false, 1.08];
}
}
function getInfiltrationSneakChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility +
0.5 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence) / (2 * lvl));
}
//Pick locked door
//Success: 1%, Failure: 3%
function attemptInfiltrationPickLockedDoor(inst) {
var chance = getInfiltrationPickLockedDoorChance(inst);
inst.gainDexterityExp(inst.securityLevel / 25) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.01;
return [true, 1.01];
} else {
inst.securityLevel *= 1.03;
return [false, 1.03];
}
}
function getInfiltrationPickLockedDoorChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence) / lvl);
}
//Bribe
//Success: 0%, Failure: 15%,
function attemptInfiltrationBribe(inst) {
var chance = getInfiltrationBribeChance(inst);
inst.gainCharismaExp(inst.securityLevel / 8) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].charisma_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.15;
return [false, 1.15];
}
}
function getInfiltrationBribeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].charisma) / lvl);
}
//Escape
//Failure: 5%
function attemptInfiltrationEscape(inst) {
var chance = getInfiltrationEscapeChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationEscapeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(2 * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].agility +
_Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].dexterity +
intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].intelligence) / lvl);
}
/***/ }),
/* 127 */
/*!******************************************!*\
!*** ./utils/uiHelpers/clearSelector.ts ***!
\******************************************/
/*! no static exports found */
/*! exports used: clearSelector */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Clears all <option> elements from a <select>.
* @param selector The <select> element
*/
function clearSelector(selector) {
for (let i = selector.options.length - 1; i >= 0; i--) {
selector.remove(i);
}
}
exports.clearSelector = clearSelector;
/***/ }),
/* 128 */,
/* 129 */,
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */,
/* 137 */,
/* 138 */,
/* 139 */,
/* 140 */,
/* 141 */,
/* 142 */,
/* 143 */
/*!***********************!*\
!*** ./css/gang.scss ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 144 */,
/* 145 */
/*!******************************!*\
!*** ./css/bladeburner.scss ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 146 */,
/* 147 */
/*!************************************!*\
!*** ./css/companymanagement.scss ***!
\************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 148 */,
/* 149 */
/*!***************************!*\
!*** ./css/missions.scss ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 150 */,
/* 151 */
/*!*************************!*\
!*** ./css/loader.scss ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 152 */,
/* 153 */
/*!**************************************!*\
!*** ./css/interactivetutorial.scss ***!
\**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 154 */,
/* 155 */
/*!*****************************!*\
!*** ./css/popupboxes.scss ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 156 */,
/* 157 */
/*!*********************************!*\
!*** ./css/workinprogress.scss ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 158 */,
/* 159 */
/*!****************************!*\
!*** ./css/menupages.scss ***!
\****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 160 */,
/* 161 */
/*!***************************!*\
!*** ./css/terminal.scss ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 162 */,
/* 163 */
/*!************************************!*\
!*** ./css/characteroverview.scss ***!
\************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 164 */,
/* 165 */
/*!***************************!*\
!*** ./css/mainmenu.scss ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 166 */,
/* 167 */
/*!**************************!*\
!*** ./css/buttons.scss ***!
\**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 168 */,
/* 169 */
/*!*************************!*\
!*** ./css/styles.scss ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 170 */,
/* 171 */,
/* 172 */,
/* 173 */,
/* 174 */,
/* 175 */,
/* 176 */,
/* 177 */,
/* 178 */
/*!**********************!*\
!*** ./netscript.js ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
//This file should be copied into brace/mode/netscript.js
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
},
DocCommentHighlightRules.getTagRule(),
{
defaultToken : "comment.doc",
caseInsensitive: true
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getTagRule = function(start) {
return {
token : "comment.doc.tag.storage.type",
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
};
}
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define("ace/mode/netscript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*";
let NetscriptFunctions =
"hack|sleep|grow|weaken|growthAnalyze|print|tprint|scan|nuke|brutessh|" +
"ftpcrack|" +
"clearLog|disableLog|enableLog|isLogEnabled|getScriptLogs|" +
"relaysmtp|httpworm|sqlinject|run|exec|spawn|kill|killall|exit|" +
"scp|ls|ps|hasRootAccess|" +
"getIp|getHackingMultipliers|getBitNodeMultipliers|getStats|isBusy|" +
"getHacknetMultipliers|" +
"getHostname|getHackingLevel|getServerMoneyAvailable|getServerMaxMoney|" +
"getServerGrowth|getServerSecurityLevel|getServerBaseSecurityLevel|" +
"getServerMinSecurityLevel|" +
"getServerRequiredHackingLevel|getServerNumPortsRequired|getServerRam|" +
"serverExists|fileExists|isRunning|" +
"deleteServer|getPurchasedServers|" +
"getPurchasedServerLimit|getPurchasedServerMaxRam|" +
"getPurchasedServerCost|" +
"purchaseServer|round|write|tryWrite|read|peek|clear|rm|getPortHandle|" +
"scriptRunning|scriptKill|getScriptName|getScriptRam|" +
"getHackTime|getGrowTime|getWeakenTime|getScriptIncome|getScriptExpGain|" +
"getTimeSinceLastAug|prompt|" +
// Singularity Functions
"universityCourse|getCharacterInformation|" +
"gymWorkout|travelToCity|purchaseTor|purchaseProgram|upgradeHomeRam|" +
"getUpgradeHomeRamCost|workForCompany|applyToCompany|getCompanyRep|" +
"getCompanyFavor|stopAction|getFactionFavor|" +
"getFavorToDonate|getFactionFavorGain|getCompanyFavorGain|" +
"checkFactionInvitations|joinFaction|workForFaction|getFactionRep|" +
"donateToFaction|" +
"createProgram|commitCrime|getCrimeChance|getOwnedAugmentations|" +
"getOwnedSourceFiles|getAugmentationsFromFaction|" +
"getAugmentationCost|purchaseAugmentation|" +
"installAugmentations|" +
// TIX API
"getStockPrice|getStockPosition|getStockSymbols|buyStock|sellStock|" +
"shortStock|sellShort|" +
"placeOrder|cancelOrder|getStockVolatility|getStockForecast|" +
"purchase4SMarketData|purchase4SMarketDataTixApi|" +
// Hacknet Node API
"hacknet|numNodes|purchaseNode|getPurchaseNodeCost|getNodeStats|" +
"upgradeLevel|upgradeRam|upgradeCore|getLevelUpgradeCost|" +
"getRamUpgradeCost|getCoreUpgradeCost|" +
// Gang API
"gang|" +
"getMemberNames|getGangInformation|getMemberInformation|canRecruitMember|" +
"recruitMember|getTaskNames|setMemberTask|getEquipmentNames|" +
"getEquipmentCost|getEquipmentType|purchaseEquipment|ascendMember|" +
"setTerritoryWarfare|" +
"getChanceToWinClash|getBonusTime|" +
// Bladeburner API
"bladeburner|getContractNames|getOperationNames|getBlackOpNames|" +
"getGeneralActionNames|getSkillNames|startAction|stopBladeburnerAction|" +
"getActionTime|getActionEstimatedSuccessChance|getActionCountRemaining|" +
"getActionMaxLevel|getActionCurrentLevel|getActionAutolevel|" +
"getActionRepGain|setActionAutolevel|setActionLevel|" +
"getRank|getSkillPoints|getSkillLevel|getSkillUpgradeCost|" +
"upgradeSkill|getTeamSize|getCity|" +
"setTeamSize|getCityEstimatedPopulation|getCityEstimatedCommunities|" +
"getCityChaos|switchCity|getStamina|joinBladeburnerFaction|getBonusTime|" +
// Coding Contract API
"codingcontract|attempt|getContractType|getData|getDescription|" +
"getNumTriesRemaining";
var NetscriptHighlightRules = function(options) {
var keywordMapper = this.createKeywordMapper({
"variable.language":
"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors
"Namespace|QName|XML|XMLList|" + // E4X
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors
"SyntaxError|TypeError|URIError|" +
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
"isNaN|parseFloat|parseInt|" +
"ns|" + NetscriptFunctions +"|" +
"JSON|Math|" + // Other
"this|arguments|prototype|window|document" , // Pseudo
"keyword":
"const|yield|import|get|set|async|await|" +
"break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
"__parent__|__count__|escape|unescape|with|__proto__|" +
"class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
"storage.type":
"const|let|var|function",
"constant.language":
"null|Infinity|NaN|undefined",
"support.function":
"alert",
"constant.language.boolean": "true|false"
}, "identifier");
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"u{[0-9a-fA-F]{1,6}}|" + // es6 unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-7][0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
this.$rules = {
"no_regex" : [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("no_regex"),
{
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, {
token : [
"storage.type", "punctuation.operator", "support.function",
"punctuation.operator", "entity.name.function", "text","keyword.operator"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
"text", "paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "punctuation.operator",
"text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"text", "text", "storage.type", "text", "paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "start"
}, {
token : ["support.constant"],
regex : /that\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
}, {
token : keywordMapper,
regex : identifierRe
}, {
token : "punctuation.operator",
regex : /[.](?![.])/,
next : "property"
}, {
token : "keyword.operator",
regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/,
next : "start"
}, {
token : "punctuation.operator",
regex : /[?:,;.]/,
next : "start"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "start"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token: "comment",
regex: /^#!.*$/
}
],
property: [{
token : "text",
regex : "\\s+"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()",
next: "function_arguments"
}, {
token : "punctuation.operator",
regex : /[.](?![.])/
}, {
token : "support.function",
regex : "/|" + NetscriptFunctions + "|/"
}, {
token : "support.function",
regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : "support.function.dom",
regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : "support.constant",
regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : "identifier",
regex : identifierRe
}, {
regex: "",
token: "empty",
next: "no_regex"
}
],
"start": [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("start"),
{
token: "string.regexp",
regex: "\\/",
next: "regex"
}, {
token : "text",
regex : "\\s+|^$",
next : "start"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp",
regex: "/[sxngimy]*",
next: "no_regex"
}, {
token : "invalid",
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
}, {
token : "constant.language.escape",
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
}, {
token : "constant.language.delimiter",
regex: /\|/
}, {
token: "constant.language.escape",
regex: /\[\^?/,
next: "regex_character_class"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp"
}
],
"regex_character_class": [
{
token: "regexp.charclass.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "constant.language.escape",
regex: "]",
next: "regex"
}, {
token: "constant.language.escape",
regex: "-"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp.charachterclass"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe
}, {
token: "punctuation.operator",
regex: "[, ]+"
}, {
token: "punctuation.operator",
regex: "$"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qqstring"
}, {
token : "string",
regex : '"|$',
next : "no_regex"
}, {
defaultToken: "string"
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qstring"
}, {
token : "string",
regex : "'|$",
next : "no_regex"
}, {
defaultToken: "string"
}
]
};
if (!options || !options.noES6) {
this.$rules.no_regex.unshift({
regex: "[{}]", onMatch: function(val, state, stack) {
this.next = val == "{" ? this.nextState : "";
if (val == "{" && stack.length) {
stack.unshift("start", state);
}
else if (val == "}" && stack.length) {
stack.shift();
this.next = stack.shift();
if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1)
return "paren.quasi.end";
}
return val == "{" ? "paren.lparen" : "paren.rparen";
},
nextState: "start"
}, {
token : "string.quasi.start",
regex : /`/,
push : [{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "paren.quasi.start",
regex : /\${/,
push : "start"
}, {
token : "string.quasi.end",
regex : /`/,
next : "pop"
}, {
defaultToken: "string.quasi"
}]
});
if (!options || options.jsx != false)
JSX.call(this);
}
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
this.normalizeRules();
};
oop.inherits(NetscriptHighlightRules, TextHighlightRules);
function JSX() {
var tagRegex = identifierRe.replace("\\d", "\\d\\-");
var jsxTag = {
onMatch : function(val, state, stack) {
var offset = val.charAt(1) == "/" ? 2 : 1;
if (offset == 1) {
if (state != this.nextState)
stack.unshift(this.next, this.nextState, 0);
else
stack.unshift(this.next);
stack[2]++;
} else if (offset == 2) {
if (state == this.nextState) {
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.shift();
stack.shift();
}
}
}
return [{
type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml",
value: val.slice(0, offset)
}, {
type: "meta.tag.tag-name.xml",
value: val.substr(offset)
}];
},
regex : "</?" + tagRegex + "",
next: "jsxAttributes",
nextState: "jsx"
};
this.$rules.start.unshift(jsxTag);
var jsxJsRule = {
regex: "{",
token: "paren.quasi.start",
push: "start"
};
this.$rules.jsx = [
jsxJsRule,
jsxTag,
{include : "reference"},
{defaultToken: "string"}
];
this.$rules.jsxAttributes = [{
token : "meta.tag.punctuation.tag-close.xml",
regex : "/?>",
onMatch : function(value, currentState, stack) {
if (currentState == stack[0])
stack.shift();
if (value.length == 2) {
if (stack[0] == this.nextState)
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.splice(0, 2);
}
}
this.next = stack[0] || "start";
return [{type: this.token, value: value}];
},
nextState: "jsx"
},
jsxJsRule,
comments("jsxAttributes"),
{
token : "entity.other.attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
token : "text.tag-whitespace.xml",
regex : "\\s+"
}, {
token : "string.attribute-value.xml",
regex : "'",
stateName : "jsx_attr_q",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
stateName : "jsx_attr_qq",
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
},
jsxTag
];
this.$rules.reference = [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}];
}
function comments(next) {
return [
{
token : "comment", // multi line comment
regex : /\/\*/,
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "\\*\\/", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}, {
token : "comment",
regex : "\\/\\/",
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "$|^", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}
];
}
exports.NetscriptHighlightRules = NetscriptHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../../lib/oop");
var Range = acequire("../../range").Range;
var BaseFoldMode = acequire("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/netscript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/netscript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var TextMode = acequire("./text").Mode;
var NetscriptHighlightRules = acequire("./netscript_highlight_rules").NetscriptHighlightRules;
var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = acequire("../worker/worker_client").WorkerClient;
var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = acequire("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = NetscriptHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], __webpack_require__(/*! brace/worker/javascript */ 179), "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/netscript";
}).call(Mode.prototype);
exports.Mode = Mode;
});
/***/ }),
/* 179 */,
/* 180 */,
/* 181 */,
/* 182 */,
/* 183 */
/*!*****************************************!*\
!*** ./src/data/codingcontracttypes.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 14);
/* Helper functions for Coding Contract implementations */
function removeBracketsFromArrayString(str) {
let strCpy = str;
if (strCpy.startsWith("[")) {
strCpy = strCpy.slice(1);
}
if (strCpy.endsWith("]")) {
strCpy = strCpy.slice(0, -1);
}
return strCpy;
}
function convert2DArrayToString(arr) {
const components = [];
arr.forEach((e) => {
let s = e.toString();
s = ["[", s, "]"].join("");
components.push(s);
});
return components.join(",")
.replace(/\s/g, "");
}
exports.codingContractTypesMetadata = [
{
desc: (n) => {
return ["A prime factor is a factor that is a prime number.",
`What is the largest prime factor of ${n}?`].join(" ");
},
difficulty: 1,
gen: () => {
return getRandomInt_1.getRandomInt(500, 1e9);
},
name: "Find Largest Prime Factor",
numTries: 10,
solver: (data, ans) => {
let fac = 2;
let n = data;
while (n > fac) {
if (n % fac === 0) {
n = Math.round(n / fac);
fac = 2;
}
else {
++fac;
}
}
return fac === parseInt(ans, 10);
},
},
{
desc: (n) => {
return ["Given the following integer array, find the contiguous subarray",
"(containing at least one number) which has the largest sum and return that sum.",
"'Sum' refers to the sum of all the numbers in the subarray.",
`${n.toString()}`].join(" ");
},
difficulty: 1,
gen: () => {
const len = getRandomInt_1.getRandomInt(5, 40);
const arr = [];
arr.length = len;
for (let i = 0; i < len; ++i) {
arr[i] = getRandomInt_1.getRandomInt(-10, 10);
}
return arr;
},
name: "Subarray with Maximum Sum",
numTries: 10,
solver: (data, ans) => {
const nums = data.slice();
for (let i = 1; i < nums.length; i++) {
nums[i] = Math.max(nums[i], nums[i] + nums[i - 1]);
}
return parseInt(ans, 10) === Math.max(...nums);
},
},
{
desc: (n) => {
return ["It is possible write four as a sum in exactly four different ways:\n\n",
" 3 + 1\n",
" 2 + 2\n",
" 2 + 1 + 1\n",
" 1 + 1 + 1 + 1\n\n",
`How many different ways can the number ${n} be written as a sum of at least`,
"two positive integers?"].join(" ");
},
difficulty: 1.5,
gen: () => {
return getRandomInt_1.getRandomInt(8, 100);
},
name: "Total Ways to Sum",
numTries: 10,
solver: (data, ans) => {
const ways = [1];
ways.length = data + 1;
ways.fill(0, 1);
for (let i = 1; i < data; ++i) {
for (let j = i; j <= data; ++j) {
ways[j] += ways[j - i];
}
}
return ways[data] === parseInt(ans, 10);
},
},
{
desc: (n) => {
let d = ["Given the following array of array of numbers representing a 2D matrix,",
"return the elements of the matrix as an array in spiral order:\n\n"].join(" ");
for (const line of n) {
d += `${line.toString()},\n`;
}
d += ["\nHere is an example of what spiral order should be:",
"\nExample:",
" [\n",
" [1, 2, 3],\n",
" [4, 5, 6],\n",
" [7, 8, 9]\n",
" ] should result in [1, 2, 3, 6, 9, 8 ,7, 4, 5]\n\n",
"Note that the matrix will not always be square:\n",
" [\n",
" [1, 2, 3, 4]\n",
" [5, 6, 7, 8]\n",
" [9, 10, 11, 12]\n",
" ] should result in [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7"].join(" ");
return d;
},
difficulty: 2,
gen: () => {
const m = getRandomInt_1.getRandomInt(1, 10);
const n = getRandomInt_1.getRandomInt(1, 10);
const matrix = [];
matrix.length = m;
for (let i = 0; i < m; ++i) {
matrix[i] = [];
matrix[i].length = n;
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
matrix[i][j] = getRandomInt_1.getRandomInt(1, 50);
}
}
return matrix;
},
name: "Spiralize Matrix",
numTries: 10,
solver: (data, ans) => {
const spiral = [];
const m = data.length;
const n = data[0].length;
let u = 0;
let d = m - 1;
let l = 0;
let r = n - 1;
let k = 0;
while (true) {
// Up
for (let col = l; col <= r; col++) {
spiral[k] = data[u][col];
++k;
}
if (++u > d) {
break;
}
// Right
for (let row = u; row <= d; row++) {
spiral[k] = data[row][r];
++k;
}
if (--r < l) {
break;
}
// Down
for (let col = r; col >= l; col--) {
spiral[k] = data[d][col];
++k;
}
if (--d < u) {
break;
}
// Left
for (let row = d; row >= u; row--) {
spiral[k] = data[row][l];
++k;
}
if (++l > r) {
break;
}
}
const sanitizedPlayerAns = removeBracketsFromArrayString(ans)
.replace(/\s/g, "");
const playerAns = sanitizedPlayerAns.split(",");
for (let i = 0; i < playerAns.length; ++i) {
playerAns[i] = parseInt(playerAns[i], 10);
}
if (spiral.length !== playerAns.length) {
return false;
}
for (let i = 0; i < spiral.length; ++i) {
if (spiral[i] !== playerAns[i]) {
return false;
}
}
return true;
},
},
{
desc: (arr) => {
return ["You are given the following array of integers:\n\n",
`${arr}\n\n`,
"Each element in the array represents your MAXIMUM jump length",
"at that position. This means that if you are at position i and your",
"maximum jump length is n, you can jump to any position from",
"i to i+n.",
"\n\nAssuming you are initially positioned",
"at the start of the array, determine whether you are",
"able to reach the last index exactly.\n\n",
"Your answer should be submitted as 1 or 0, representing true and false respectively"].join(" ");
},
difficulty: 2.5,
gen: () => {
const len = getRandomInt_1.getRandomInt(1, 25);
const arr = [];
arr.length = len;
for (let i = 0; i < arr.length; ++i) {
if (Math.random() < 0.2) {
arr[i] = 0; // 20% chance of being 0
}
else {
arr[i] = getRandomInt_1.getRandomInt(0, 10);
}
}
return arr;
},
name: "Array Jumping Game",
numTries: 1,
solver: (data, ans) => {
const n = data.length;
let i = 0;
for (let reach = 0; i < n && i <= reach; ++i) {
reach = Math.max(i + data[i], reach);
}
const solution = (i === n);
if (ans === "1" && solution) {
return true;
}
if (ans === "0" && !solution) {
return true;
}
return false;
},
},
{
desc: (arr) => {
return ["Given the following array of array of numbers representing a list of",
"intervals, merge all overlapping intervals.\n\n",
`[${convert2DArrayToString(arr)}]\n\n`,
"Example:\n\n",
"[[1, 3], [8, 10], [2, 6], [10, 16]]\n\n",
"would merge into [[1, 6], [8, 16]].\n\n",
"The intervals must be returned in ASCENDING order.",
"You can assume that in an interval, the first number will always be",
"smaller than the second."].join(" ");
},
difficulty: 3,
gen: () => {
const intervals = [];
const numIntervals = getRandomInt_1.getRandomInt(1, 20);
for (let i = 0; i < numIntervals; ++i) {
const start = getRandomInt_1.getRandomInt(1, 25);
const end = start + getRandomInt_1.getRandomInt(1, 10);
intervals.push([start, end]);
}
return intervals;
},
name: "Merge Overlapping Intervals",
numTries: 15,
solver: (data, ans) => {
const intervals = data.slice();
intervals.sort((a, b) => {
return a[0] - b[0];
});
const result = [];
let start = intervals[0][0];
let end = intervals[0][1];
for (const interval of intervals) {
if (interval[0] <= end) {
end = Math.max(end, interval[1]);
}
else {
result.push([start, end]);
start = interval[0];
end = interval[1];
}
}
result.push([start, end]);
const sanitizedResult = convert2DArrayToString(result);
const sanitizedAns = ans.replace(/\s/g, "");
return (sanitizedResult === sanitizedAns ||
sanitizedResult === removeBracketsFromArrayString(sanitizedAns));
},
},
{
desc: (data) => {
return ["Given the following string containing only digits, return",
"an array with all possible valid IP address combinations",
"that can be created from the string:\n\n",
`${data}\n\n`,
"Note that an octet cannot begin with a '0' unless the number",
"itself is actually 0. For example, '192.168.010.1' is not a valid IP.\n\n",
"Examples:\n\n",
"25525511135 -> [255.255.11.135, 255.255.111.35]\n",
"1938718066 -> [193.87.180.66]"].join(" ");
},
difficulty: 3,
gen: () => {
let str = "";
for (let i = 0; i < 4; ++i) {
const num = getRandomInt_1.getRandomInt(0, 255);
const convNum = num.toString();
str += convNum;
}
return str;
},
name: "Generate IP Addresses",
numTries: 10,
solver: (data, ans) => {
const ret = [];
for (let a = 1; a <= 3; ++a) {
for (let b = 1; b <= 3; ++b) {
for (let c = 1; c <= 3; ++c) {
for (let d = 1; d <= 3; ++d) {
if (a + b + c + d === data.length) {
const A = parseInt(data.substring(0, a), 10);
const B = parseInt(data.substring(a, a + b), 10);
const C = parseInt(data.substring(a + b, a + b + c), 10);
const D = parseInt(data.substring(a + b + c, a + b + c + d), 10);
if (A <= 255 && B <= 255 && C <= 255 && D <= 255) {
const ip = [A.toString(), ".",
B.toString(), ".",
C.toString(), ".",
D.toString()].join("");
if (ip.length === data.length + 3) {
ret.push(ip);
}
}
}
}
}
}
}
const sanitizedAns = removeBracketsFromArrayString(ans)
.replace(/\s/g, "");
const ansArr = sanitizedAns.split(",");
if (ansArr.length !== ret.length) {
return false;
}
for (const ipInAns of ansArr) {
if (!ret.includes(ipInAns)) {
return false;
}
}
return true;
},
},
{
desc: (data) => {
return ["You are given the following array of stock prices (which are numbers)",
"where the i-th element represents the stock price on day i:\n\n",
`${data}\n\n`,
"Determine the maximum possible profit you can earn using at most",
"one transaction (i.e. you can only buy and sell the stock once). If no profit can be made",
"then the answer should be 0. Note",
"that you have to buy the stock before you can sell it"].join(" ");
},
difficulty: 1,
gen: () => {
const len = getRandomInt_1.getRandomInt(1, 50);
const arr = [];
arr.length = len;
for (let i = 0; i < len; ++i) {
arr[i] = getRandomInt_1.getRandomInt(1, 200);
}
return arr;
},
name: "Algorithmic Stock Trader I",
numTries: 5,
solver: (data, ans) => {
let maxCur = 0;
let maxSoFar = 0;
for (let i = 1; i < data.length; ++i) {
maxCur = Math.max(0, maxCur += data[i] - data[i - 1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar.toString() === ans;
},
},
{
desc: (data) => {
return ["You are given the following array of stock prices (which are numbers)",
"where the i-th element represents the stock price on day i:\n\n",
`${data}\n\n`,
"Determine the maximum possible profit you can earn using as many",
"transactions as you'd like. A transaction is defined as buying",
"and then selling one share of the stock. Note that you cannot",
"engage in multiple transactions at once. In other words, you",
"must sell the stock before you buy it again.\n\n",
"If no profit can be made, then the answer should be 0"].join(" ");
},
difficulty: 2,
gen: () => {
const len = getRandomInt_1.getRandomInt(1, 50);
const arr = [];
arr.length = len;
for (let i = 0; i < len; ++i) {
arr[i] = getRandomInt_1.getRandomInt(1, 200);
}
return arr;
},
name: "Algorithmic Stock Trader II",
numTries: 10,
solver: (data, ans) => {
let profit = 0;
for (let p = 1; p < data.length; ++p) {
profit += Math.max(data[p] - data[p - 1], 0);
}
return profit.toString() === ans;
},
},
{
desc: (data) => {
return ["You are given the following array of stock prices (which are numbers)",
"where the i-th element represents the stock price on day i:\n\n",
`${data}\n\n`,
"Determine the maximum possible profit you can earn using at most",
"two transactions. A transaction is defined as buying",
"and then selling one share of the stock. Note that you cannot",
"engage in multiple transactions at once. In other words, you",
"must sell the stock before you buy it again.\n\n",
"If no profit can be made, then the answer should be 0"].join(" ");
},
difficulty: 5,
gen: () => {
const len = getRandomInt_1.getRandomInt(1, 50);
const arr = [];
arr.length = len;
for (let i = 0; i < len; ++i) {
arr[i] = getRandomInt_1.getRandomInt(1, 200);
}
return arr;
},
name: "Algorithmic Stock Trader III",
numTries: 10,
solver: (data, ans) => {
let hold1 = Number.MIN_SAFE_INTEGER;
let hold2 = Number.MIN_SAFE_INTEGER;
let release1 = 0;
let release2 = 0;
for (const price of data) {
release2 = Math.max(release2, hold2 + price);
hold2 = Math.max(hold2, release1 - price);
release1 = Math.max(release1, hold1 + price);
hold1 = Math.max(hold1, price * -1);
}
return release2.toString() === ans;
},
},
];
/***/ }),
/* 184 */
/*!***********************************************!*\
!*** ./src/Company/data/CompaniesMetadata.ts ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Locations_1 = __webpack_require__(/*! ../../Locations */ 5);
const posNames = __webpack_require__(/*! ./CompanyPositionNames */ 34);
// Create Objects containing Company Positions by category
// Will help in metadata construction later
const AllSoftwarePositions = {};
const AllITPositions = {};
const AllNetworkEngineerPositions = {};
const AllTechnologyPositions = {};
const AllBusinessPositions = {};
const AllAgentPositions = {};
const AllSecurityPositions = {};
const AllSoftwareConsultantPositions = {};
const AllBusinessConsultantPositions = {};
const SoftwarePositionsUpToHeadOfEngineering = {};
const SoftwarePositionsUpToLeadDeveloper = {};
const BusinessPositionsUpToOperationsManager = {};
const WaiterOnly = {};
const EmployeeOnly = {};
const PartTimeWaiterOnly = {};
const PartTimeEmployeeOnly = {};
const OperationsManagerOnly = {};
const CEOOnly = {};
posNames.SoftwareCompanyPositions.forEach((e) => {
AllSoftwarePositions[e] = true;
AllTechnologyPositions[e] = true;
});
posNames.ITCompanyPositions.forEach((e) => {
AllITPositions[e] = true;
AllTechnologyPositions[e] = true;
});
posNames.NetworkEngineerCompanyPositions.forEach((e) => {
AllNetworkEngineerPositions[e] = true;
AllTechnologyPositions[e] = true;
});
AllTechnologyPositions[posNames.SecurityEngineerCompanyPositions[0]] = true;
posNames.BusinessCompanyPositions.forEach((e) => {
AllBusinessPositions[e] = true;
});
posNames.SecurityCompanyPositions.forEach((e) => {
AllSecurityPositions[e] = true;
});
posNames.AgentCompanyPositions.forEach((e) => {
AllAgentPositions[e] = true;
});
posNames.SoftwareConsultantCompanyPositions.forEach((e) => {
AllSoftwareConsultantPositions[e] = true;
});
posNames.BusinessConsultantCompanyPositions.forEach((e) => {
AllBusinessConsultantPositions[e] = true;
});
for (let i = 0; i < posNames.SoftwareCompanyPositions.length; ++i) {
const e = posNames.SoftwareCompanyPositions[i];
if (i <= 5) {
SoftwarePositionsUpToHeadOfEngineering[e] = true;
}
if (i <= 3) {
SoftwarePositionsUpToLeadDeveloper[e] = true;
}
}
for (let i = 0; i < posNames.BusinessCompanyPositions.length; ++i) {
const e = posNames.BusinessCompanyPositions[i];
if (i <= 3) {
BusinessPositionsUpToOperationsManager[e] = true;
}
}
WaiterOnly[posNames.MiscCompanyPositions[0]] = true;
EmployeeOnly[posNames.MiscCompanyPositions[1]] = true;
PartTimeWaiterOnly[posNames.PartTimeCompanyPositions[0]] = true;
PartTimeEmployeeOnly[posNames.PartTimeCompanyPositions[1]] = true;
OperationsManagerOnly[posNames.BusinessCompanyPositions[3]] = true;
CEOOnly[posNames.BusinessCompanyPositions[5]] = true;
// Metadata
exports.companiesMetadata = [
{
name: Locations_1.Locations.AevumECorp,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 3,
salaryMultiplier: 3,
jobStatReqOffset: 249,
},
{
name: Locations_1.Locations.Sector12MegaCorp,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 3,
salaryMultiplier: 3,
jobStatReqOffset: 249,
},
{
name: Locations_1.Locations.AevumBachmanAndAssociates,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.6,
salaryMultiplier: 2.6,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.Sector12BladeIndustries,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.75,
salaryMultiplier: 2.75,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.VolhavenNWO,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.75,
salaryMultiplier: 2.75,
jobStatReqOffset: 249,
},
{
name: Locations_1.Locations.AevumClarkeIncorporated,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.25,
salaryMultiplier: 2.25,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.VolhavenOmniTekIncorporated,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.25,
salaryMultiplier: 2.25,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.Sector12FourSigma,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.5,
salaryMultiplier: 2.5,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.ChongqingKuaiGongInternational,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 2.2,
salaryMultiplier: 2.2,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.AevumFulcrumTechnologies,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions),
expMultiplier: 2,
salaryMultiplier: 2,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.IshimaStormTechnologies,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllSoftwareConsultantPositions, AllBusinessPositions),
expMultiplier: 1.8,
salaryMultiplier: 1.8,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.NewTokyoDefComm,
info: "",
companyPositions: Object.assign({}, CEOOnly, AllTechnologyPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.75,
salaryMultiplier: 1.75,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.VolhavenHeliosLabs,
info: "",
companyPositions: Object.assign({}, CEOOnly, AllTechnologyPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.8,
salaryMultiplier: 1.8,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.NewTokyoVitaLife,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.8,
salaryMultiplier: 1.8,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.Sector12IcarusMicrosystems,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.9,
salaryMultiplier: 1.9,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.Sector12UniversalEnergy,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions),
expMultiplier: 2,
salaryMultiplier: 2,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.AevumGalacticCybersystems,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.9,
salaryMultiplier: 1.9,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.AevumAeroCorp,
info: "",
companyPositions: Object.assign({}, CEOOnly, OperationsManagerOnly, AllTechnologyPositions, AllSecurityPositions),
expMultiplier: 1.7,
salaryMultiplier: 1.7,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.VolhavenOmniaCybersystems,
info: "",
companyPositions: Object.assign({}, CEOOnly, OperationsManagerOnly, AllTechnologyPositions, AllSecurityPositions),
expMultiplier: 1.7,
salaryMultiplier: 1.7,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.ChongqingSolarisSpaceSystems,
info: "",
companyPositions: Object.assign({}, CEOOnly, OperationsManagerOnly, AllTechnologyPositions, AllSecurityPositions),
expMultiplier: 1.7,
salaryMultiplier: 1.7,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.Sector12DeltaOne,
info: "",
companyPositions: Object.assign({}, CEOOnly, OperationsManagerOnly, AllTechnologyPositions, AllSecurityPositions),
expMultiplier: 1.6,
salaryMultiplier: 1.6,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.NewTokyoGlobalPharmaceuticals,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions, AllSecurityPositions),
expMultiplier: 1.8,
salaryMultiplier: 1.8,
jobStatReqOffset: 224,
},
{
name: Locations_1.Locations.IshimaNovaMedical,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllBusinessPositions, AllSoftwareConsultantPositions, AllSecurityPositions),
expMultiplier: 1.75,
salaryMultiplier: 1.75,
jobStatReqOffset: 199,
},
{
name: Locations_1.Locations.Sector12CIA,
info: "",
companyPositions: Object.assign({}, SoftwarePositionsUpToHeadOfEngineering, AllNetworkEngineerPositions, AllITPositions, AllSecurityPositions, AllAgentPositions),
expMultiplier: 2,
salaryMultiplier: 2,
jobStatReqOffset: 149,
},
{
name: Locations_1.Locations.Sector12NSA,
info: "",
companyPositions: Object.assign({}, SoftwarePositionsUpToHeadOfEngineering, AllNetworkEngineerPositions, AllITPositions, AllSecurityPositions, AllAgentPositions),
expMultiplier: 2,
salaryMultiplier: 2,
jobStatReqOffset: 149,
},
{
name: Locations_1.Locations.AevumWatchdogSecurity,
info: "",
companyPositions: Object.assign({}, SoftwarePositionsUpToHeadOfEngineering, AllNetworkEngineerPositions, AllITPositions, AllSecurityPositions, AllAgentPositions, AllSoftwareConsultantPositions),
expMultiplier: 1.5,
salaryMultiplier: 1.5,
jobStatReqOffset: 124,
},
{
name: Locations_1.Locations.VolhavenLexoCorp,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllSoftwareConsultantPositions, AllBusinessPositions, AllSecurityPositions),
expMultiplier: 1.4,
salaryMultiplier: 1.4,
jobStatReqOffset: 99,
},
{
name: Locations_1.Locations.AevumRhoConstruction,
info: "",
companyPositions: Object.assign({}, SoftwarePositionsUpToLeadDeveloper, BusinessPositionsUpToOperationsManager),
expMultiplier: 1.3,
salaryMultiplier: 1.3,
jobStatReqOffset: 49,
},
{
name: Locations_1.Locations.Sector12AlphaEnterprises,
info: "",
companyPositions: Object.assign({}, SoftwarePositionsUpToLeadDeveloper, BusinessPositionsUpToOperationsManager, AllSoftwareConsultantPositions),
expMultiplier: 1.5,
salaryMultiplier: 1.5,
jobStatReqOffset: 99,
},
{
name: Locations_1.Locations.AevumPolice,
info: "",
companyPositions: Object.assign({}, AllSecurityPositions, SoftwarePositionsUpToLeadDeveloper),
expMultiplier: 1.3,
salaryMultiplier: 1.3,
jobStatReqOffset: 99,
},
{
name: Locations_1.Locations.VolhavenSysCoreSecurities,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions),
expMultiplier: 1.3,
salaryMultiplier: 1.3,
jobStatReqOffset: 124,
},
{
name: Locations_1.Locations.VolhavenCompuTek,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions),
expMultiplier: 1.2,
salaryMultiplier: 1.2,
jobStatReqOffset: 74,
},
{
name: Locations_1.Locations.AevumNetLinkTechnologies,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions),
expMultiplier: 1.2,
salaryMultiplier: 1.2,
jobStatReqOffset: 99,
},
{
name: Locations_1.Locations.Sector12CarmichaelSecurity,
info: "",
companyPositions: Object.assign({}, AllTechnologyPositions, AllAgentPositions, AllSecurityPositions),
expMultiplier: 1.2,
salaryMultiplier: 1.2,
jobStatReqOffset: 74,
},
{
name: Locations_1.Locations.Sector12FoodNStuff,
info: "",
companyPositions: Object.assign({}, EmployeeOnly, PartTimeEmployeeOnly),
expMultiplier: 1,
salaryMultiplier: 1,
jobStatReqOffset: 0,
},
{
name: Locations_1.Locations.Sector12JoesGuns,
info: "",
companyPositions: Object.assign({}, EmployeeOnly, PartTimeEmployeeOnly),
expMultiplier: 1,
salaryMultiplier: 1,
jobStatReqOffset: 0,
},
{
name: Locations_1.Locations.IshimaOmegaSoftware,
info: "",
companyPositions: Object.assign({}, AllSoftwarePositions, AllSoftwareConsultantPositions, AllITPositions),
expMultiplier: 1.1,
salaryMultiplier: 1.1,
jobStatReqOffset: 49,
},
{
name: Locations_1.Locations.NewTokyoNoodleBar,
info: "",
companyPositions: Object.assign({}, WaiterOnly, PartTimeWaiterOnly),
expMultiplier: 1,
salaryMultiplier: 1,
jobStatReqOffset: 0,
},
];
/***/ }),
/* 185 */
/*!******************************************************!*\
!*** ./src/Company/data/CompanyPositionsMetadata.ts ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const posNames = __webpack_require__(/*! ./CompanyPositionNames */ 34);
exports.companyPositionMetadata = [
{
name: posNames.SoftwareCompanyPositions[0],
nextPosition: posNames.SoftwareCompanyPositions[1],
baseSalary: 33,
charismaEffectiveness: 15,
charismaExpGain: 0.02,
hackingEffectiveness: 85,
hackingExpGain: 0.05,
reqdHacking: 1,
repMultiplier: 0.9,
},
{
name: posNames.SoftwareCompanyPositions[1],
nextPosition: posNames.SoftwareCompanyPositions[2],
baseSalary: 80,
charismaEffectiveness: 15,
charismaExpGain: 0.05,
hackingEffectiveness: 85,
hackingExpGain: 0.1,
reqdHacking: 51,
reqdReputation: 8e3,
repMultiplier: 1.1,
},
{
name: posNames.SoftwareCompanyPositions[2],
nextPosition: posNames.SoftwareCompanyPositions[3],
baseSalary: 165,
charismaEffectiveness: 20,
charismaExpGain: 0.08,
hackingEffectiveness: 80,
hackingExpGain: 0.4,
reqdCharisma: 51,
reqdHacking: 251,
reqdReputation: 40e3,
repMultiplier: 1.3,
},
{
name: posNames.SoftwareCompanyPositions[3],
nextPosition: posNames.SoftwareCompanyPositions[4],
baseSalary: 500,
charismaEffectiveness: 25,
charismaExpGain: 0.1,
hackingEffectiveness: 75,
hackingExpGain: 0.8,
reqdCharisma: 151,
reqdHacking: 401,
reqdReputation: 200e3,
repMultiplier: 1.5,
},
{
name: posNames.SoftwareCompanyPositions[4],
nextPosition: posNames.SoftwareCompanyPositions[5],
baseSalary: 800,
charismaEffectiveness: 25,
charismaExpGain: 0.5,
hackingEffectiveness: 75,
hackingExpGain: 1,
reqdCharisma: 251,
reqdHacking: 501,
reqdReputation: 400e3,
repMultiplier: 1.6,
},
{
name: posNames.SoftwareCompanyPositions[5],
nextPosition: posNames.SoftwareCompanyPositions[6],
baseSalary: 1650,
charismaEffectiveness: 25,
charismaExpGain: 0.5,
hackingEffectiveness: 75,
hackingExpGain: 1.1,
reqdCharisma: 251,
reqdHacking: 501,
reqdReputation: 800e3,
repMultiplier: 1.6,
},
{
name: posNames.SoftwareCompanyPositions[6],
nextPosition: posNames.SoftwareCompanyPositions[7],
baseSalary: 2310,
charismaEffectiveness: 30,
charismaExpGain: 0.6,
hackingEffectiveness: 70,
hackingExpGain: 1.2,
reqdCharisma: 401,
reqdHacking: 601,
reqdReputation: 1.6e6,
repMultiplier: 1.75,
},
{
name: posNames.SoftwareCompanyPositions[7],
nextPosition: null,
baseSalary: 2640,
charismaEffectiveness: 35,
charismaExpGain: 1,
hackingEffectiveness: 65,
hackingExpGain: 1.5,
reqdCharisma: 501,
reqdHacking: 751,
reqdReputation: 3.2e6,
repMultiplier: 2,
},
{
name: posNames.ITCompanyPositions[0],
nextPosition: posNames.ITCompanyPositions[1],
baseSalary: 26,
charismaEffectiveness: 10,
charismaExpGain: 0.01,
hackingEffectiveness: 90,
hackingExpGain: 0.04,
reqdHacking: 1,
repMultiplier: 0.9,
},
{
name: posNames.ITCompanyPositions[1],
nextPosition: posNames.ITCompanyPositions[2],
baseSalary: 66,
charismaEffectiveness: 15,
charismaExpGain: 0.02,
hackingEffectiveness: 85,
hackingExpGain: 0.08,
reqdHacking: 26,
reqdReputation: 7e3,
repMultiplier: 1.1,
},
{
name: posNames.ITCompanyPositions[2],
nextPosition: posNames.ITCompanyPositions[3],
baseSalary: 132,
charismaEffectiveness: 20,
charismaExpGain: 0.1,
hackingEffectiveness: 80,
hackingExpGain: 0.3,
reqdCharisma: 51,
reqdHacking: 151,
reqdReputation: 35e3,
repMultiplier: 1.3,
},
{
name: posNames.ITCompanyPositions[3],
nextPosition: posNames.SoftwareCompanyPositions[5],
baseSalary: 410,
charismaEffectiveness: 20,
charismaExpGain: 0.2,
hackingEffectiveness: 80,
hackingExpGain: 0.5,
reqdCharisma: 76,
reqdHacking: 251,
reqdReputation: 175e3,
repMultiplier: 1.4,
},
{
name: posNames.SecurityEngineerCompanyPositions[0],
nextPosition: posNames.SoftwareCompanyPositions[5],
baseSalary: 121,
charismaEffectiveness: 15,
charismaExpGain: 0.05,
hackingEffectiveness: 85,
hackingExpGain: 0.4,
reqdCharisma: 26,
reqdHacking: 151,
reqdReputation: 35e3,
repMultiplier: 1.2,
},
{
name: posNames.NetworkEngineerCompanyPositions[0],
nextPosition: posNames.NetworkEngineerCompanyPositions[1],
baseSalary: 121,
charismaEffectiveness: 15,
charismaExpGain: 0.05,
hackingEffectiveness: 85,
hackingExpGain: 0.4,
reqdCharisma: 26,
reqdHacking: 151,
reqdReputation: 35e3,
repMultiplier: 1.2,
},
{
name: posNames.NetworkEngineerCompanyPositions[1],
nextPosition: posNames.SoftwareCompanyPositions[5],
baseSalary: 410,
charismaEffectiveness: 20,
charismaExpGain: 0.1,
hackingEffectiveness: 80,
hackingExpGain: 0.5,
reqdCharisma: 76,
reqdHacking: 251,
reqdReputation: 175e3,
repMultiplier: 1.3,
},
{
name: posNames.BusinessCompanyPositions[0],
nextPosition: posNames.BusinessCompanyPositions[1],
baseSalary: 46,
charismaEffectiveness: 90,
charismaExpGain: 0.08,
hackingEffectiveness: 10,
hackingExpGain: 0.01,
reqdCharisma: 1,
reqdHacking: 1,
repMultiplier: 0.9,
},
{
name: posNames.BusinessCompanyPositions[1],
nextPosition: posNames.BusinessCompanyPositions[2],
baseSalary: 100,
charismaEffectiveness: 85,
charismaExpGain: 0.15,
hackingEffectiveness: 15,
hackingExpGain: 0.02,
reqdCharisma: 51,
reqdHacking: 6,
reqdReputation: 8e3,
repMultiplier: 1.1,
},
{
name: posNames.BusinessCompanyPositions[2],
nextPosition: posNames.BusinessCompanyPositions[3],
baseSalary: 200,
charismaEffectiveness: 85,
charismaExpGain: 0.3,
hackingEffectiveness: 15,
hackingExpGain: 0.02,
reqdCharisma: 101,
reqdHacking: 51,
reqdReputation: 40e3,
repMultiplier: 1.3,
},
{
name: posNames.BusinessCompanyPositions[3],
nextPosition: posNames.BusinessCompanyPositions[4],
baseSalary: 660,
charismaEffectiveness: 85,
charismaExpGain: 0.4,
hackingEffectiveness: 15,
hackingExpGain: 0.02,
reqdCharisma: 226,
reqdHacking: 51,
reqdReputation: 200e3,
repMultiplier: 1.5,
},
{
name: posNames.BusinessCompanyPositions[4],
nextPosition: posNames.BusinessCompanyPositions[5],
baseSalary: 1950,
charismaEffectiveness: 90,
charismaExpGain: 1,
hackingEffectiveness: 10,
hackingExpGain: 0.05,
reqdCharisma: 501,
reqdHacking: 76,
reqdReputation: 800e3,
repMultiplier: 1.6,
},
{
name: posNames.BusinessCompanyPositions[5],
nextPosition: null,
baseSalary: 3900,
charismaEffectiveness: 90,
charismaExpGain: 1.5,
hackingEffectiveness: 10,
hackingExpGain: 0.05,
reqdCharisma: 751,
reqdHacking: 101,
reqdReputation: 3.2e6,
repMultiplier: 1.75,
},
{
name: posNames.SecurityCompanyPositions[0],
nextPosition: posNames.SecurityCompanyPositions[1],
baseSalary: 82,
hackingEffectiveness: 5,
strengthEffectiveness: 20,
defenseEffectiveness: 20,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 15,
hackingExpGain: 0.02,
strengthExpGain: 0.08,
defenseExpGain: 0.08,
dexterityExpGain: 0.08,
agilityExpGain: 0.08,
charismaExpGain: 0.04,
reqdHacking: 11,
reqdStrength: 101,
reqdDefense: 101,
reqdDexterity: 101,
reqdAgility: 101,
reqdCharisma: 51,
reqdReputation: 8e3,
repMultiplier: 1,
},
{
name: posNames.SecurityCompanyPositions[1],
nextPosition: null,
baseSalary: 460,
hackingEffectiveness: 5,
strengthEffectiveness: 20,
defenseEffectiveness: 20,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 15,
hackingExpGain: 0.02,
strengthExpGain: 0.1,
defenseExpGain: 0.1,
dexterityExpGain: 0.1,
agilityExpGain: 0.1,
charismaExpGain: 0.1,
reqdHacking: 101,
reqdStrength: 301,
reqdDefense: 301,
reqdDexterity: 301,
reqdAgility: 301,
reqdCharisma: 151,
reqdReputation: 36e3,
repMultiplier: 1.25,
},
{
name: posNames.SecurityCompanyPositions[2],
nextPosition: posNames.SecurityCompanyPositions[3],
baseSalary: 50,
hackingEffectiveness: 5,
strengthEffectiveness: 20,
defenseEffectiveness: 20,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 15,
hackingExpGain: 0.01,
strengthExpGain: 0.04,
defenseExpGain: 0.04,
dexterityExpGain: 0.04,
agilityExpGain: 0.04,
charismaExpGain: 0.02,
reqdStrength: 51,
reqdDefense: 51,
reqdDexterity: 51,
reqdAgility: 51,
reqdCharisma: 1,
repMultiplier: 1,
},
{
name: posNames.SecurityCompanyPositions[3],
nextPosition: posNames.SecurityCompanyPositions[4],
baseSalary: 195,
hackingEffectiveness: 10,
strengthEffectiveness: 20,
defenseEffectiveness: 20,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 10,
hackingExpGain: 0.02,
strengthExpGain: 0.1,
defenseExpGain: 0.1,
dexterityExpGain: 0.1,
agilityExpGain: 0.1,
charismaExpGain: 0.05,
reqdHacking: 26,
reqdStrength: 151,
reqdDefense: 151,
reqdDexterity: 151,
reqdAgility: 151,
reqdCharisma: 51,
reqdReputation: 8e3,
repMultiplier: 1.1,
},
{
name: posNames.SecurityCompanyPositions[4],
nextPosition: posNames.SecurityCompanyPositions[5],
baseSalary: 660,
hackingEffectiveness: 10,
strengthEffectiveness: 15,
defenseEffectiveness: 15,
dexterityEffectiveness: 15,
agilityEffectiveness: 15,
charismaEffectiveness: 30,
hackingExpGain: 0.02,
strengthExpGain: 0.12,
defenseExpGain: 0.12,
dexterityExpGain: 0.12,
agilityExpGain: 0.12,
charismaExpGain: 0.1,
reqdHacking: 26,
reqdStrength: 251,
reqdDefense: 251,
reqdDexterity: 251,
reqdAgility: 251,
reqdCharisma: 101,
reqdReputation: 36e3,
repMultiplier: 1.25,
},
{
name: posNames.SecurityCompanyPositions[5],
nextPosition: null,
baseSalary: 1320,
hackingEffectiveness: 10,
strengthEffectiveness: 15,
defenseEffectiveness: 15,
dexterityEffectiveness: 15,
agilityEffectiveness: 15,
charismaEffectiveness: 30,
hackingExpGain: 0.05,
strengthExpGain: 0.15,
defenseExpGain: 0.15,
dexterityExpGain: 0.15,
agilityExpGain: 0.15,
charismaExpGain: 0.15,
reqdHacking: 51,
reqdStrength: 501,
reqdDefense: 501,
reqdDexterity: 501,
reqdAgility: 501,
reqdCharisma: 151,
reqdReputation: 144e3,
repMultiplier: 1.4,
},
{
name: posNames.AgentCompanyPositions[0],
nextPosition: posNames.AgentCompanyPositions[1],
baseSalary: 330,
hackingEffectiveness: 10,
strengthEffectiveness: 15,
defenseEffectiveness: 15,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 20,
hackingExpGain: 0.04,
strengthExpGain: 0.08,
defenseExpGain: 0.08,
dexterityExpGain: 0.08,
agilityExpGain: 0.08,
charismaExpGain: 0.05,
reqdHacking: 101,
reqdStrength: 101,
reqdDefense: 101,
reqdDexterity: 101,
reqdAgility: 101,
reqdCharisma: 101,
reqdReputation: 8e3,
repMultiplier: 1,
},
{
name: posNames.AgentCompanyPositions[1],
nextPosition: posNames.AgentCompanyPositions[2],
baseSalary: 990,
hackingEffectiveness: 15,
strengthEffectiveness: 15,
defenseEffectiveness: 15,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 15,
hackingExpGain: 0.1,
strengthExpGain: 0.15,
defenseExpGain: 0.15,
dexterityExpGain: 0.15,
agilityExpGain: 0.15,
charismaExpGain: 0.1,
reqdHacking: 201,
reqdStrength: 251,
reqdDefense: 251,
reqdDexterity: 251,
reqdAgility: 251,
reqdCharisma: 201,
reqdReputation: 32e3,
repMultiplier: 1.25,
},
{
name: posNames.AgentCompanyPositions[2],
nextPosition: null,
baseSalary: 2000,
hackingEffectiveness: 15,
strengthEffectiveness: 15,
defenseEffectiveness: 15,
dexterityEffectiveness: 20,
agilityEffectiveness: 20,
charismaEffectiveness: 15,
hackingExpGain: 0.15,
strengthExpGain: 0.2,
defenseExpGain: 0.2,
dexterityExpGain: 0.2,
agilityExpGain: 0.2,
charismaExpGain: 0.15,
reqdHacking: 251,
reqdStrength: 501,
reqdDefense: 501,
reqdDexterity: 501,
reqdAgility: 501,
reqdCharisma: 251,
reqdReputation: 162e3,
repMultiplier: 1.5,
},
{
name: posNames.MiscCompanyPositions[0],
nextPosition: null,
baseSalary: 22,
strengthEffectiveness: 10,
dexterityEffectiveness: 10,
agilityEffectiveness: 10,
charismaEffectiveness: 70,
strengthExpGain: 0.02,
defenseExpGain: 0.02,
dexterityExpGain: 0.02,
agilityExpGain: 0.02,
charismaExpGain: 0.05,
repMultiplier: 1,
},
{
name: posNames.MiscCompanyPositions[1],
nextPosition: null,
baseSalary: 22,
strengthEffectiveness: 10,
dexterityEffectiveness: 10,
agilityEffectiveness: 10,
charismaEffectiveness: 70,
strengthExpGain: 0.02,
defenseExpGain: 0.02,
dexterityExpGain: 0.02,
agilityExpGain: 0.02,
charismaExpGain: 0.04,
repMultiplier: 1,
},
{
name: posNames.SoftwareConsultantCompanyPositions[0],
nextPosition: posNames.SoftwareConsultantCompanyPositions[1],
baseSalary: 66,
hackingEffectiveness: 80,
charismaEffectiveness: 20,
hackingExpGain: 0.08,
charismaExpGain: 0.03,
reqdHacking: 51,
repMultiplier: 1,
},
{
name: posNames.SoftwareConsultantCompanyPositions[1],
nextPosition: null,
baseSalary: 132,
hackingEffectiveness: 75,
charismaEffectiveness: 25,
hackingExpGain: 0.25,
charismaExpGain: 0.06,
reqdHacking: 251,
reqdCharisma: 51,
repMultiplier: 1.2,
},
{
name: posNames.BusinessConsultantCompanyPositions[0],
nextPosition: posNames.BusinessConsultantCompanyPositions[1],
baseSalary: 66,
hackingEffectiveness: 20,
charismaEffectiveness: 80,
hackingExpGain: 0.015,
charismaExpGain: 0.15,
reqdHacking: 6,
reqdCharisma: 51,
repMultiplier: 1,
},
{
name: posNames.BusinessConsultantCompanyPositions[1],
nextPosition: null,
baseSalary: 525,
hackingEffectiveness: 15,
charismaEffectiveness: 85,
hackingExpGain: 0.015,
charismaExpGain: 0.3,
reqdHacking: 51,
reqdCharisma: 226,
repMultiplier: 1.2,
},
{
name: posNames.PartTimeCompanyPositions[0],
nextPosition: null,
baseSalary: 20,
strengthEffectiveness: 10,
dexterityEffectiveness: 10,
agilityEffectiveness: 10,
charismaEffectiveness: 70,
strengthExpGain: 0.0075,
defenseExpGain: 0.0075,
dexterityExpGain: 0.0075,
agilityExpGain: 0.0075,
charismaExpGain: 0.04,
repMultiplier: 1,
},
{
name: posNames.PartTimeCompanyPositions[1],
nextPosition: null,
baseSalary: 20,
strengthEffectiveness: 10,
dexterityEffectiveness: 10,
agilityEffectiveness: 10,
charismaEffectiveness: 70,
strengthExpGain: 0.0075,
defenseExpGain: 0.0075,
dexterityExpGain: 0.0075,
agilityExpGain: 0.0075,
charismaExpGain: 0.03,
repMultiplier: 1,
},
];
/***/ }),
/* 186 */,
/* 187 */,
/* 188 */,
/* 189 */,
/* 190 */,
/* 191 */,
/* 192 */,
/* 193 */,
/* 194 */,
/* 195 */,
/* 196 */,
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */,
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */,
/* 217 */,
/* 218 */,
/* 219 */,
/* 220 */,
/* 221 */,
/* 222 */
/*!**********************!*\
!*** util (ignored) ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 223 */
/*!**********************!*\
!*** util (ignored) ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports) {
/* (ignored) */
/***/ })
/******/ ]);
//# sourceMappingURL=engine.bundle.js.map