" +
"In this game you control a set of Nodes and use them to try and defeat an enemy. Your Nodes " +
"are colored blue, while the enemy's are red. There are also other nodes on the map colored gray " +
"that initially belong to neither you nor the enemy. The goal of the game is " +
"to capture all of the enemy's Database nodes within the time limit. " +
"If you fail to do this, you will lose.
" +
"Each Node has three stats: Attack, Defense, and HP. There are five different actions that " +
"a Node can take:
" +
"Attack - Targets an enemy Node and lowers its HP. The effectiveness is determined by the owner's Attack, the Player's " +
"hacking level, and the enemy's defense.
" +
"Scan - Targets an enemy Node and lowers its Defense. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the " +
"enemy's defense.
" +
"Weaken - Targets an enemy Node and lowers its Attack. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the enemy's " +
"defense.
" +
"Fortify - Raises the Node's Defense. The effectiveness is determined by your hacking level.
" +
"Overflow - Raises the Node's Attack but lowers its Defense. The effectiveness is determined by your hacking level.
" +
"Note that when determining the effectiveness of the above actions, the TOTAL Attack or Defense of the team is used, not just the " +
"Attack/Defense of the individual Node that is performing the action.
" +
"To capture a Node, you must lower its HP down to 0.
" +
"There are six different types of Nodes:
" +
"CPU Core - These are your main Nodes that are used to perform actions. Capable of performing every action
" +
"Firewall - Nodes with high defense. These Nodes can 'Fortify'
" +
"Database - A special type of Node. The player's objective is to conquer all of the enemy's Database Nodes within " +
"the time limit. These Nodes cannot perform any actions
" +
"Spam - Conquering one of these Nodes will slow the enemy's trace, giving the player additional time to complete " +
"the mission. These Nodes cannot perform any actions
" +
"Transfer - Conquering one of these nodes will increase the Attack of all of your CPU Cores by a small fixed percentage. " +
"These Nodes are capable of performing every action except the 'Attack' action
" +
"Shield - Nodes with high defense. These Nodes can 'Fortify'
" +
"To assign an action to a Node, you must first select one of your Nodes. This can be done by simply clicking on it. Double-clicking " +
"a node will select all of your Nodes of the same type (e.g. select all CPU Core Nodes or all Transfer Nodes). Note that only Nodes " +
"that can perform actions (CPU Core, Transfer, Shield, Firewall) can be selected. Selected Nodes will be denoted with a white highlight. After selecting a Node or multiple Nodes, " +
"select its action using the Action Buttons near the top of the screen. Every action also has a corresponding keyboard " +
"shortcut.
" +
"For certain actions such as attacking, scanning, and weakening, the Node performing the action must have a target. To target " +
"another node, simply click-and-drag from the 'source' Node to a target. A Node can only have one target, and you can target " +
"any Node that is adjacent to one of your Nodes (immediately above, below, or to the side. NOT diagonal). Furthermore, only CPU Cores and Transfer Nodes " +
"can target, since they are the only ones that can perform the related actions. To remove a target, you can simply click on the line that represents " +
"the connection between one of your Nodes and its target. Alternatively, you can select the 'source' Node and click the 'Drop Connection' button, " +
"or press 'd'.
" +
"Other Notes:
" +
"-Whenever a miscellenaous Node (not owned by the player or enemy) is conquered, the defense of all remaining miscellaneous Nodes that " +
"are not actively being targeted will increase by a fixed percentage.
" +
"-Whenever a Node is conquered, its stats are significantly reduced
" +
"-Miscellaneous Nodes slowly raise their defense over time
" +
"-Nodes slowly regenerate health over time.",
// Time-related constants
MillisecondsPer20Hours: 72000000,
GameCyclesPer20Hours: 72000000 / 200,
MillisecondsPer10Hours: 36000000,
GameCyclesPer10Hours: 36000000 / 200,
MillisecondsPer8Hours: 28800000,
GameCyclesPer8Hours: 28800000 / 200,
MillisecondsPer4Hours: 14400000,
GameCyclesPer4Hours: 14400000 / 200,
MillisecondsPer2Hours: 7200000,
GameCyclesPer2Hours: 7200000 / 200,
MillisecondsPerHour: 3600000,
GameCyclesPerHour: 3600000 / 200,
MillisecondsPerHalfHour: 1800000,
GameCyclesPerHalfHour: 1800000 / 200,
MillisecondsPerQuarterHour: 900000,
GameCyclesPerQuarterHour: 900000 / 200,
MillisecondsPerFiveMinutes: 300000,
GameCyclesPerFiveMinutes: 300000 / 200,
// Player Work & Action
FactionWorkHacking: "Faction Hacking Work",
FactionWorkField: "Faction Field Work",
FactionWorkSecurity: "Faction Security Work",
WorkTypeCompany: "Working for Company",
WorkTypeCompanyPartTime: "Working for Company part-time",
WorkTypeFaction: "Working for Faction",
WorkTypeCreateProgram: "Working on Create a Program",
WorkTypeStudyClass: "Studying or Taking a class at university",
WorkTypeCrime: "Committing a crime",
ClassStudyComputerScience: "studying Computer Science",
ClassDataStructures: "taking a Data Structures course",
ClassNetworks: "taking a Networks course",
ClassAlgorithms: "taking an Algorithms course",
ClassManagement: "taking a Management course",
ClassLeadership: "taking a Leadership course",
ClassGymStrength: "training your strength at a gym",
ClassGymDefense: "training your defense at a gym",
ClassGymDexterity: "training your dexterity at a gym",
ClassGymAgility: "training your agility at a gym",
ClassDataStructuresBaseCost: 40,
ClassNetworksBaseCost: 80,
ClassAlgorithmsBaseCost: 320,
ClassManagementBaseCost: 160,
ClassLeadershipBaseCost: 320,
ClassGymBaseCost: 120,
ClassStudyComputerScienceBaseExp: 0.5,
ClassDataStructuresBaseExp: 1,
ClassNetworksBaseExp: 2,
ClassAlgorithmsBaseExp: 4,
ClassManagementBaseExp: 2,
ClassLeadershipBaseExp: 4,
CrimeShoplift: "shoplift",
CrimeRobStore: "rob a store",
CrimeMug: "mug someone",
CrimeLarceny: "commit larceny",
CrimeDrugs: "deal drugs",
CrimeBondForgery: "forge corporate bonds",
CrimeTraffickArms: "traffick illegal arms",
CrimeHomicide: "commit homicide",
CrimeGrandTheftAuto: "commit grand theft auto",
CrimeKidnap: "kidnap someone for ransom",
CrimeAssassination: "assassinate a high-profile target",
CrimeHeist: "pull off the ultimate heist",
// Coding Contract
// TODO: Move this into Coding contract implementation?
CodingContractBaseFactionRepGain: 2500,
CodingContractBaseCompanyRepGain: 4000,
CodingContractBaseMoneyGain: 75e6,
// BitNode/Source-File related stuff
TotalNumBitNodes: 24,
LatestUpdate: `
v0.52.9 - 2021-07-27 Less lag! (hydroflame & community)
-------------------------------------------
** Active Scripts page **
* Now less laggy, has pagination.
** File diagnostic **
* Added a popup found under options that shows the files you own and how
large they are. This help find bugs and leftover massive logs files.
** Corporation **
* Added safeguard against a very specific bug that causes NaN money. I'm
still not sure what the root cause is but it should prevent corp from
breaking.
** Netscript **
* tprintf is a new function that doesn't print the filename.
** Misc. **
* Infiltration kills you if you try to automate it. (@threehams)
* Fix beautify button not working
* Added bladeburner_analysis_mult to getPlayer() (@brusby)
* Fixed joining bladeburner via netscript functions. (@omuretsu)
* All bladeburner actions are click-to-copy
* nerf noodle bar
`,
/*
*/
};
/***/ }),
/* 12 */
/*!*******************************************!*\
!*** ./src/Augmentation/Augmentations.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Augmentations = void 0;
exports.Augmentations = {};
/***/ }),
/* 13 */
/*!*****************************!*\
!*** ./utils/DialogBox.tsx ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.dialogBoxCreate = exports.MessagePopup = void 0;
const createPopup_1 = __webpack_require__(/*! ../src/ui/React/createPopup */ 41);
const getRandomInt_1 = __webpack_require__(/*! ./helpers/getRandomInt */ 45);
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
function MessagePopup(props) {
return (react_1.default.createElement(react_1.default.Fragment, null, props.content));
}
exports.MessagePopup = MessagePopup;
function dialogBoxCreate(txt, preformatted = false) {
const popupId = `popup-` + (Array.from(Array(16))).map(() => `${getRandomInt_1.getRandomInt(0, 9)}`).join('');
if (typeof txt === 'string') {
if (preformatted) {
// For text files as they are often computed data that
// shouldn't be wrapped and should retain tabstops.
createPopup_1.createPopup(popupId, MessagePopup, {
content: (react_1.default.createElement("pre", { dangerouslySetInnerHTML: { __html: txt } })),
});
}
else {
createPopup_1.createPopup(popupId, MessagePopup, {
content: (react_1.default.createElement("p", { dangerouslySetInnerHTML: { __html: txt.replace(/(?:\r\n|\r|\n)/g, ' ') } })),
});
}
}
else {
createPopup_1.createPopup(popupId, MessagePopup, {
content: txt,
});
}
}
exports.dialogBoxCreate = dialogBoxCreate;
/***/ }),
/* 14 */,
/* 15 */
/*!************************!*\
!*** ./src/engine.jsx ***!
\************************/
/*! exports provided: Engine */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; });
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Augmentation/AugmentationHelpers */ 79);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./BitNode/BitNode */ 127);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Bladeburner/Bladeburner */ 94);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ui_React_CharacterOverview__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ui/React/CharacterOverview */ 767);
/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CinematicText */ 450);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CodingContractGenerator */ 176);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Corporation/Corporation */ 122);
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _DevMenu__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./DevMenu */ 532);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 71);
/* harmony import */ var _Faction_ui_FactionList__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Faction/ui/FactionList */ 766);
/* harmony import */ var _Faction_ui_FactionList__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Faction_ui_FactionList__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _Gang_Helpers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Gang/Helpers */ 765);
/* harmony import */ var _Gang_Helpers__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_Gang_Helpers__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Bladeburner_ui_Root__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Bladeburner/ui/Root */ 764);
/* harmony import */ var _Bladeburner_ui_Root__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_ui_Root__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _Infiltration_Helper__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Infiltration/Helper */ 763);
/* harmony import */ var _Infiltration_Helper__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Infiltration_Helper__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./PersonObjects/formulas/reputation */ 109);
/* harmony import */ var _PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Fconf/FconfSettings */ 39);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Hacknet/HacknetHelpers */ 25);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./InteractiveTutorial */ 43);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Locations/data/LocationNames */ 40);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Locations/ui/Root */ 455);
/* harmony import */ var _Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Message/MessageHelpers */ 87);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Missions */ 81);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Netscript/WorkerScripts */ 112);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./NetscriptWorker */ 80);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Prestige */ 173);
/* harmony import */ var _Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Programs/ProgramHelpers */ 304);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./RedPill */ 103);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./SaveObject */ 114);
/* harmony import */ var _ScriptEditor_ui_Root__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./ScriptEditor/ui/Root */ 714);
/* harmony import */ var _ScriptEditor_ui_Root__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_ScriptEditor_ui_Root__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 47);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var _Milestones_MilestoneHelpers__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./Milestones/MilestoneHelpers */ 701);
/* harmony import */ var _Milestones_MilestoneHelpers__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_Milestones_MilestoneHelpers__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./Terminal */ 74);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./PersonObjects/Sleeve/Sleeve */ 178);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var _PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./PersonObjects/Sleeve/SleeveUI */ 451);
/* harmony import */ var _PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var _PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./PersonObjects/Resleeving/ResleevingUI */ 526);
/* harmony import */ var _PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./ui/createStatusText */ 141);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var _ui_CharacterInfo__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./ui/CharacterInfo */ 700);
/* harmony import */ var _ui_CharacterInfo__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_ui_CharacterInfo__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./ui/setSettingsLabels */ 699);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./ui/React/Hashes */ 126);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_51__);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./ui/React/Reputation */ 59);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_52___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_52__);
/* harmony import */ var _ui_ActiveScripts_Root__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ./ui/ActiveScripts/Root */ 525);
/* harmony import */ var _ui_ActiveScripts_Root__WEBPACK_IMPORTED_MODULE_53___default = /*#__PURE__*/__webpack_require__.n(_ui_ActiveScripts_Root__WEBPACK_IMPORTED_MODULE_53__);
/* harmony import */ var _ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ./ui/MainMenu/Headers */ 698);
/* harmony import */ var _ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_54__);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ./ui/MainMenu/Links */ 31);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__);
/* harmony import */ var _Diagnostic_FileDiagnosticPopup__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ./Diagnostic/FileDiagnosticPopup */ 697);
/* harmony import */ var _Diagnostic_FileDiagnosticPopup__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_Diagnostic_FileDiagnosticPopup__WEBPACK_IMPORTED_MODULE_56__);
/* harmony import */ var _ui_React_createPopup__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ./ui/React/createPopup */ 41);
/* harmony import */ var _ui_React_createPopup__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_ui_React_createPopup__WEBPACK_IMPORTED_MODULE_57__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__);
/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ../utils/GameOptions */ 303);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 91);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ../utils/uiHelpers/removeLoadingScreen */ 524);
/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_61__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 44);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__);
/* harmony import */ var _Exploits_tampering__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ./Exploits/tampering */ 863);
/* harmony import */ var _Exploits_tampering__WEBPACK_IMPORTED_MODULE_63___default = /*#__PURE__*/__webpack_require__.n(_Exploits_tampering__WEBPACK_IMPORTED_MODULE_63__);
/* harmony import */ var _Exploits_unclickable__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ./Exploits/unclickable */ 862);
/* harmony import */ var _Exploits_unclickable__WEBPACK_IMPORTED_MODULE_64___default = /*#__PURE__*/__webpack_require__.n(_Exploits_unclickable__WEBPACK_IMPORTED_MODULE_64__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_65___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_65__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_66___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_66__);
/**
* Game engine. Handles the main game loop as well as the main UI pages
*
* TODO: Separate UI functionality into its own component
*/
/**
* Shortcuts to navigate through the game
* Alt-t - Terminal
* Alt-c - Character
* Alt-e - Script editor
* Alt-s - Active scripts
* Alt-h - Hacknet Nodes
* Alt-w - City
* Alt-j - Job
* Alt-r - Travel Agency of current city
* Alt-p - Create program
* Alt-f - Factions
* Alt-a - Augmentations
* Alt-u - Tutorial
* Alt-o - Options
*/
$(document).keydown(function (e) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].DisableHotkeys === true) {
return;
}
if (!_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].isWorking && !_RedPill__WEBPACK_IMPORTED_MODULE_33__["redPillFlag"] && !_Missions__WEBPACK_IMPORTED_MODULE_26__[/* inMission */ "c"] && !_CinematicText__WEBPACK_IMPORTED_MODULE_7__[/* cinematicTextFlag */ "a"]) {
if (e.keyCode == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].T && e.altKey) {
e.preventDefault();
Engine.loadTerminalContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].C && e.altKey) {
e.preventDefault();
Engine.loadCharacterContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].E && e.altKey) {
e.preventDefault();
Engine.loadScriptEditorContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].S && e.altKey) {
e.preventDefault();
Engine.loadActiveScriptsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].H && e.altKey) {
e.preventDefault();
Engine.loadHacknetNodesContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].W && e.altKey) {
e.preventDefault();
Engine.loadLocationContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].J && e.altKey) {
e.preventDefault();
Engine.loadJobContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].R && e.altKey) {
e.preventDefault();
Engine.loadTravelContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].P && e.altKey) {
e.preventDefault();
Engine.loadCreateProgramContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].F && e.altKey) {
// Overriden by Fconf
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal) && _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_20__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
return;
}
e.preventDefault();
Engine.loadFactionsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].A && e.altKey) {
e.preventDefault();
Engine.loadAugmentationsContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].U && e.altKey) {
e.preventDefault();
Engine.loadTutorialContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].B && e.altKey) {
e.preventDefault();
Engine.loadBladeburnerContent();
} else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].G && e.altKey) {
e.preventDefault();
Engine.loadGangContent();
}
}
if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_62__["KEY"].O && e.altKey) {
e.preventDefault();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_59__[/* gameOptionsBoxOpen */ "b"])();
}
});
const Engine = {
// Clickable objects
Clickables: {
// Main menu buttons
saveMainMenuButton: null,
deleteMainMenuButton: null
},
// Display objects
// TODO-Refactor this into its own component
Display: {
// Main menu content
terminalContent: null,
characterContent: null,
scriptEditorContent: null,
activeScriptsContent: null,
hacknetNodesContent: null,
createProgramContent: null,
factionsContent: null,
factionContent: null,
augmentationsContent: null,
milestonesContent: null,
tutorialContent: null,
infiltrationContent: null,
stockMarketContent: null,
gangContent: null,
bladeburnerContent: null,
locationContent: null,
workInProgressContent: null,
redPillContent: null,
cinematicTextContent: null,
missionContent: null,
// Character info
characterInfo: null
},
indexedDb: undefined,
// Time variables (milliseconds unix epoch time)
_lastUpdate: new Date().getTime(),
_idleSpeed: 200,
// Speed (in ms) at which the main loop is updated
loadTerminalContent: function () {
Engine.hideAllContent();
Engine.Display.terminalContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Terminal.classList.add("active");
},
loadCharacterContent: function () {
Engine.hideAllContent();
Engine.Display.characterContent.style.display = "block";
Engine.updateCharacterInfo();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CharacterInfo);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Stats.classList.add("active");
},
loadScriptEditorContent: function (filename = "", code = "") {
Engine.hideAllContent();
Engine.Display.scriptEditorContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ScriptEditor);
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_ScriptEditor_ui_Root__WEBPACK_IMPORTED_MODULE_35__["Root"], {
filename: filename,
code: code,
player: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"],
engine: this
}), Engine.Display.scriptEditorContent);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ScriptEditor.classList.add("active");
},
loadActiveScriptsContent: function () {
Engine.hideAllContent();
Engine.Display.activeScriptsContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ActiveScripts);
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_ui_ActiveScripts_Root__WEBPACK_IMPORTED_MODULE_53__["ActiveScriptsRoot"], {
p: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"],
workerScripts: _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_27__["workerScripts"]
}), Engine.Display.activeScriptsContent);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ActiveScripts.classList.add("active");
},
loadHacknetNodesContent: function () {
Engine.hideAllContent();
Engine.Display.hacknetNodesContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].HacknetNodes);
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* renderHacknetNodesUI */ "q"])();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].HacknetNodes.classList.add("active");
},
loadCreateProgramContent: function () {
Engine.hideAllContent();
Engine.Display.createProgramContent.style.display = "block";
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_32__[/* displayCreateProgramContent */ "a"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CreateProgram);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].CreateProgram.classList.add("active");
},
loadFactionsContent: function () {
Engine.hideAllContent();
Engine.Display.factionsContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Factions);
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_Faction_ui_FactionList__WEBPACK_IMPORTED_MODULE_15__["FactionList"], {
player: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"],
engine: this
}), Engine.Display.factionsContent);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Factions.classList.add("active");
},
loadFactionContent: function () {
Engine.hideAllContent();
Engine.Display.factionContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Faction);
},
loadAugmentationsContent: function () {
Engine.hideAllContent();
Engine.Display.augmentationsContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Augmentations);
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_2__[/* displayAugmentationsContent */ "c"])(Engine.Display.augmentationsContent);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Augmentations.classList.add("active");
},
loadMilestonesContent: function () {
Engine.hideAllContent();
Engine.Display.milestonesContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Milestones);
Object(_Milestones_MilestoneHelpers__WEBPACK_IMPORTED_MODULE_41__["displayMilestonesContent"])();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Milestones.classList.add("active");
},
loadTutorialContent: function () {
Engine.hideAllContent();
Engine.Display.tutorialContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Tutorial);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Tutorial.classList.add("active");
},
loadDevMenuContent: function () {
Engine.hideAllContent();
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_12__[/* createDevMenu */ "b"])();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].DevMenu);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].DevMenu.classList.add("active");
},
loadLocationContent: function (initiallyInCity = true) {
Engine.hideAllContent();
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].City.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24__["LocationRoot"], {
initiallyInCity: initiallyInCity,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadTravelContent: function () {
// Same as loadLocationContent() except first set the location to the travel agency,
// and make sure that the 'City' main menu link doesnt become 'active'
Engine.hideAllContent();
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gotoLocation(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_23__["LocationName"].TravelAgency);
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Travel.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24__["LocationRoot"], {
initiallyInCity: false,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadJobContent: function () {
// Same as loadLocationContent(), except first set the location to the job.
// Make sure that the 'City' main menu link doesnt become 'active'
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].companyName == "") {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__["dialogBoxCreate"])("You do not currently have a job! You can visit various companies " + "in the city and try to find a job.");
return;
}
Engine.hideAllContent();
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gotoLocation(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].companyName);
Engine.Display.locationContent.style.display = "block";
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Job.classList.add("active");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Location);
const rootComponent = react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_Locations_ui_Root__WEBPACK_IMPORTED_MODULE_24__["LocationRoot"], {
initiallyInCity: false,
engine: Engine,
p: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]
});
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(rootComponent, Engine.Display.locationContent);
},
loadWorkInProgressContent: function () {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["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_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["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_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CinematicText);
},
loadInfiltrationContent: function (name, difficulty, maxLevel) {
Engine.hideAllContent();
const mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.infiltrationContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Infiltration);
Object(_Infiltration_Helper__WEBPACK_IMPORTED_MODULE_18__["displayInfiltrationContent"])(this, _Player__WEBPACK_IMPORTED_MODULE_30__["Player"], name, difficulty, maxLevel);
},
loadStockMarketContent: function () {
Engine.hideAllContent();
Engine.Display.stockMarketContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].StockMarket);
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__["displayStockMarketContent"])();
},
loadGangContent: function () {
Engine.hideAllContent();
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].inGang()) {
Engine.Display.gangContent.style.display = "block";
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Gang);
Object(_Gang_Helpers__WEBPACK_IMPORTED_MODULE_16__["displayGangContent"])(this, _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gang, _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} else {
Engine.loadTerminalContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["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_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Mission);
},
loadCorporationContent: function () {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Corporation);
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation.createUI(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
}
},
loadBladeburnerContent: function () {
if (!(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__["Bladeburner"])) return;
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Bladeburner);
Engine.Display.bladeburnerContent.style.display = "block";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_Bladeburner_ui_Root__WEBPACK_IMPORTED_MODULE_17__["Root"], {
bladeburner: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner,
player: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"],
engine: this
}), Engine.Display.bladeburnerContent);
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Bladeburner.classList.add("active");
},
loadSleevesContent: function () {
// This is for Duplicate Sleeves page, not Re-sleeving @ Vita Life
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Sleeves);
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44__["createSleevesPage"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__["exceptionAlert"])(e);
}
},
loadResleevingContent: function () {
try {
Engine.hideAllContent();
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Resleeves);
Object(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_45__["createResleevesPage"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__["exceptionAlert"])(e);
}
},
// Helper function that hides all content
hideAllContent: function () {
Engine.Display.terminalContent.style.display = "none";
Engine.Display.characterContent.style.display = "none";
Engine.Display.scriptEditorContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.scriptEditorContent);
Engine.Display.activeScriptsContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.activeScriptsContent);
Engine.Display.infiltrationContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.infiltrationContent);
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* clearHacknetNodesUI */ "a"])();
Engine.Display.createProgramContent.style.display = "none";
Engine.Display.factionsContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.factionsContent);
Engine.Display.factionContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.factionContent);
Engine.Display.augmentationsContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.augmentationsContent);
Engine.Display.milestonesContent.style.display = "none";
Engine.Display.tutorialContent.style.display = "none";
Engine.Display.locationContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.locationContent);
Engine.Display.gangContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.gangContent);
Engine.Display.bladeburnerContent.style.display = "none";
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.unmountComponentAtNode(Engine.Display.bladeburnerContent);
Engine.Display.workInProgressContent.style.display = "none";
Engine.Display.redPillContent.style.display = "none";
Engine.Display.cinematicTextContent.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_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation.clearUI(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
}
Object(_PersonObjects_Resleeving_ResleevingUI__WEBPACK_IMPORTED_MODULE_45__["clearResleevesPage"])();
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44__["clearSleevesPage"])(); // Make nav menu tabs inactive
Engine.inactivateMainMenuLinks(); // Close dev menu
Object(_DevMenu__WEBPACK_IMPORTED_MODULE_12__[/* closeDevMenu */ "a"])();
},
// Remove 'active' css class from all main menu links
inactivateMainMenuLinks: function () {
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Terminal.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ScriptEditor.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ActiveScripts.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].CreateProgram.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Stats.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Factions.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Augmentations.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].HacknetNodes.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Sleeves.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].City.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Travel.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Job.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].StockMarket.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Gang.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Bladeburner.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Corporation.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Gang.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Milestones.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Tutorial.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Options.classList.remove("active");
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].DevMenu.classList.remove("active");
},
displayCharacterOverviewInfo: function () {
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_ui_React_CharacterOverview__WEBPACK_IMPORTED_MODULE_6__[/* CharacterOverviewComponent */ "a"], null), document.getElementById('character-overview-text'));
const save = document.getElementById("character-overview-save-button");
const flashClass = "flashing-button";
if (!_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].AutosaveInterval) {
save.classList.add(flashClass);
} else {
save.classList.remove(flashClass);
}
},
/// Display character info
updateCharacterInfo: function () {
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(Object(_ui_CharacterInfo__WEBPACK_IMPORTED_MODULE_47__["CharacterInfo"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]), Engine.Display.characterInfo);
},
// Main Game Loop
idleTimer: function () {
// Get time difference
const _thisUpdate = new Date().getTime();
let diff = _thisUpdate - Engine._lastUpdate;
const 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_30__["Player"].lastUpdate = _thisUpdate - offset;
Engine.updateGame(diff);
}
window.requestAnimationFrame(Engine.idleTimer);
},
updateGame: function (numCycles = 1) {
const time = numCycles * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode = 0;
}
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode += time; // Start Manual hack
if (_Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].actionStarted === true) {
Engine._totalActionTime = _Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].actionTime;
Engine._actionTimeLeft = _Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].actionTime;
Engine._actionInProgress = true;
Engine._actionProgressBarCount = 1;
Engine._actionProgressStr = "[ ]";
Engine._actionTimeStr = "Time left: ";
_Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].actionStarted = false;
} // Working
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].isWorking) {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workForFaction(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].createProgramWork(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].takeClass(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].commitCrime(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workPartTime(numCycles);
} else {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].work(numCycles);
}
} // Update stock prices
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__["processStockPrices"])(numCycles);
} // Gang, if applicable
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gang.process(numCycles, _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} // Mission
if (_Missions__WEBPACK_IMPORTED_MODULE_26__[/* inMission */ "c"] && _Missions__WEBPACK_IMPORTED_MODULE_26__[/* currMission */ "b"]) {
_Missions__WEBPACK_IMPORTED_MODULE_26__[/* currMission */ "b"].process(numCycles);
} // Corporation
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
// Stores cycles in a "buffer". Processed separately using Engine Counters
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation.storeCycles(numCycles);
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__["Bladeburner"]) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner.storeCycles(numCycles);
} // Sleeves
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_43__["Sleeve"]) {
const expForOtherSleeves = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[i].process(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], numCycles); // This sleeve earns experience for other sleeves
if (expForOtherSleeves == null) {
continue;
}
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves.length; ++j) {
if (j === i) {
continue;
}
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[j].gainExperience(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], expForOtherSleeves, numCycles, true);
}
}
} // Counters
Engine.decrementAllCounters(numCycles);
Engine.checkCounters(); // Manual hacks
if (Engine._actionInProgress == true) {
Engine.updateHackProgress(numCycles);
} // Update the running time of all active scripts
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_28__[/* updateOnlineScriptTimes */ "f"])(numCycles); // Hacknet Nodes
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* processHacknetEarnings */ "j"])(numCycles);
},
/**
* Counters for the main event loop. Represent the number of game cycles that
* are required for something to happen. These counters are in game cycles,
* which is once every 200ms
*/
Counters: {
autoSaveCounter: 300,
updateSkillLevelsCounter: 10,
updateDisplays: 3,
updateDisplaysMed: 9,
updateDisplaysLong: 15,
updateActiveScriptsDisplay: 5,
createProgramNotifications: 10,
augmentationsNotifications: 10,
checkFactionInvitations: 100,
passiveFactionGrowth: 5,
messages: 150,
mechanicProcess: 5,
// Processes certain mechanics (Corporation, Bladeburner)
contractGeneration: 3000 // Generate Coding Contracts
},
decrementAllCounters: function (numCycles = 1) {
for (var counter in Engine.Counters) {
if (Engine.Counters.hasOwnProperty(counter)) {
Engine.Counters[counter] = Engine.Counters[counter] - numCycles;
}
}
},
/**
* Checks if any counters are 0. If they are, executes whatever
* is necessary and then resets the counter
*/
checkCounters: function () {
if (Engine.Counters.autoSaveCounter <= 0) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].AutosaveInterval == null) {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].AutosaveInterval = 60;
}
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].AutosaveInterval === 0) {
Engine.Counters.autoSaveCounter = Infinity;
} else {
Engine.Counters.autoSaveCounter = _Settings_Settings__WEBPACK_IMPORTED_MODULE_37__["Settings"].AutosaveInterval * 5;
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].saveGame(Engine.indexedDb);
}
}
if (Engine.Counters.updateSkillLevelsCounter <= 0) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].updateSkillLevels();
Engine.Counters.updateSkillLevelsCounter = 10;
}
if (Engine.Counters.updateActiveScriptsDisplay <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ActiveScripts)) {
react_dom__WEBPACK_IMPORTED_MODULE_66___default.a.render(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(_ui_ActiveScripts_Root__WEBPACK_IMPORTED_MODULE_53__["ActiveScriptsRoot"], {
p: _Player__WEBPACK_IMPORTED_MODULE_30__["Player"],
workerScripts: _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_27__["workerScripts"]
}), Engine.Display.activeScriptsContent);
}
Engine.Counters.updateActiveScriptsDisplay = 5;
}
if (Engine.Counters.updateDisplays <= 0) {
Engine.displayCharacterOverviewInfo();
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].HacknetNodes)) {
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* renderHacknetNodesUI */ "q"])();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CreateProgram)) {
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_32__[/* displayCreateProgramContent */ "a"])();
} else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Sleeves)) {
Object(_PersonObjects_Sleeve_SleeveUI__WEBPACK_IMPORTED_MODULE_44__["updateSleevesPage"])();
}
Engine.Counters.updateDisplays = 3;
}
if (Engine.Counters.updateDisplaysMed <= 0) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CharacterInfo)) {
Engine.updateCharacterInfo();
}
Engine.Counters.updateDisplaysMed = 9;
}
if (Engine.Counters.createProgramNotifications <= 0) {
var num = Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_32__[/* getNumAvailableCreateProgram */ "b"])();
var elem = document.getElementById("create-program-notification");
if (num > 0) {
elem.innerHTML = num;
elem.setAttribute("class", "notification-on");
} else {
elem.innerHTML = "";
elem.setAttribute("class", "notification-off");
}
Engine.Counters.createProgramNotifications = 10;
}
if (Engine.Counters.augmentationsNotifications <= 0) {
var num = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].queuedAugmentations.length;
var elem = document.getElementById("augmentations-notification");
if (num > 0) {
elem.innerHTML = num;
elem.setAttribute("class", "notification-on");
} else {
elem.innerHTML = "";
elem.setAttribute("class", "notification-off");
}
Engine.Counters.augmentationsNotifications = 10;
}
if (Engine.Counters.checkFactionInvitations <= 0) {
var invitedFactions = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].checkForFactionInvitations();
if (invitedFactions.length > 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstFacInvRecvd === false) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstFacInvRecvd = true;
document.getElementById("factions-tab").style.display = "list-item";
document.getElementById("character-menu-header").click();
document.getElementById("character-menu-header").click();
}
var randFaction = invitedFactions[Math.floor(Math.random() * invitedFactions.length)];
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_14__["inviteToFaction"])(randFaction);
}
const num = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].factionInvitations.length;
const elem = document.getElementById("factions-notification");
if (num > 0) {
elem.innerHTML = num;
elem.setAttribute("class", "notification-on");
} else {
elem.innerHTML = "";
elem.setAttribute("class", "notification-off");
}
Engine.Counters.checkFactionInvitations = 100;
}
if (Engine.Counters.passiveFactionGrowth <= 0) {
var adjustedCycles = Math.floor(5 - Engine.Counters.passiveFactionGrowth);
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_14__["processPassiveFactionRepGain"])(adjustedCycles);
Engine.Counters.passiveFactionGrowth = 5;
}
if (Engine.Counters.messages <= 0) {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_25__[/* checkForMessagesToSend */ "b"])();
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill].owned) {
Engine.Counters.messages = 4500; // 15 minutes for Red pill message
} else {
Engine.Counters.messages = 150;
}
}
if (Engine.Counters.mechanicProcess <= 0) {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation.process(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__["Bladeburner"]) {
try {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner.process(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} catch (e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__["exceptionAlert"])("Exception caught in Bladeburner.process(): " + e);
}
}
Engine.Counters.mechanicProcess = 5;
}
if (Engine.Counters.contractGeneration <= 0) {
// X% chance of a contract being generated
if (Math.random() <= 0.25) {
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_8__["generateRandomContract"])();
}
Engine.Counters.contractGeneration = 3000;
}
},
// Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly
// TODO Refactor this into Terminal module
_totalActionTime: 0,
_actionTimeLeft: 0,
_actionTimeStr: "Time left: ",
_actionProgressStr: "[ ]",
_actionProgressBarCount: 1,
_actionInProgress: false,
updateHackProgress: function (numCycles = 1) {
var timeElapsedMilli = numCycles * Engine._idleSpeed;
Engine._actionTimeLeft -= timeElapsedMilli / 1000; // Substract idle speed (ms)
Engine._actionTimeLeft = Math.max(Engine._actionTimeLeft, 0); // Calculate percent filled
var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100); // Update progress bar
while (Engine._actionProgressBarCount * 2 <= percent) {
Engine._actionProgressStr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["replaceAt"])(Engine._actionProgressStr, Engine._actionProgressBarCount, "|");
Engine._actionProgressBarCount += 1;
} // Update hack time remaining
Engine._actionTimeStr = "Time left: " + Math.max(0, Math.round(Engine._actionTimeLeft)).toString() + "s";
document.getElementById("hack-progress").innerHTML = Engine._actionTimeStr; // Dynamically update progress bar
document.getElementById("hack-progress-bar").innerHTML = Engine._actionProgressStr.replace(/ /g, " "); // Once percent is 100, the hack is completed
if (percent >= 100) {
Engine._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].finishAction();
}
},
/**
* Collapses a main menu header. Used when initializing the game.
* @param elems {HTMLElement[]} Elements under header
*/
closeMainMenuHeader: function (elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = null;
elems[i].style.opacity = 0;
elems[i].style.pointerEvents = "none";
}
},
/**
* Expands a main menu header. Used when initializing the game.
* @param elems {HTMLElement[]} Elements under header
*/
openMainMenuHeader: function (elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = elems[i].scrollHeight + "px";
elems[i].style.display = "block";
}
},
/**
* Used in game when clicking on a main menu header (NOT used for initialization)
* @param open {boolean} Whether header is being opened or closed
* @param elems {HTMLElement[]} li Elements under header
* @param links {HTMLElement[]} a elements under header
*/
toggleMainMenuHeader: function (open, elems, links) {
for (var i = 0; i < elems.length; ++i) {
if (open) {
elems[i].style.opacity = 1;
elems[i].style.maxHeight = elems[i].scrollHeight + "px";
} else {
elems[i].style.opacity = 0;
elems[i].style.maxHeight = null;
}
}
for (var i = 0; i < links.length; ++i) {
if (open) {
links[i].style.opacity = 1;
links[i].style.maxHeight = links[i].scrollHeight + "px";
links[i].style.pointerEvents = "auto";
} else {
links[i].style.opacity = 0;
links[i].style.maxHeight = null;
links[i].style.pointerEvents = "none";
}
}
},
load: function (saveString) {
// Initialize main menu accordion panels to all start as "open"
const terminal = document.getElementById("terminal-tab");
const createScript = document.getElementById("create-script-tab");
const activeScripts = document.getElementById("active-scripts-tab");
const createProgram = document.getElementById("create-program-tab");
const stats = document.getElementById("stats-tab");
const factions = document.getElementById("factions-tab");
const augmentations = document.getElementById("augmentations-tab");
const hacknetnodes = document.getElementById("hacknet-nodes-tab");
const city = document.getElementById("city-tab");
const travel = document.getElementById("travel-tab");
const job = document.getElementById("job-tab");
const stockmarket = document.getElementById("stock-market-tab");
const bladeburner = document.getElementById("bladeburner-tab");
const corp = document.getElementById("corporation-tab");
const gang = document.getElementById("gang-tab");
const milestones = document.getElementById("milestones-tab");
const tutorial = document.getElementById("tutorial-tab");
const options = document.getElementById("options-tab");
const dev = document.getElementById("dev-tab"); // Load game from save or create new game
if (Object(_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* loadGame */ "a"])(saveString)) {
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_4__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
Engine.setDisplayElements(); // Sets variables for important DOM elements
Engine.init(); // Initialize buttons, work, etc.
Object(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__["updateSourceFileFlags"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_2__[/* initAugmentations */ "d"])(); // Also calls Player.reapplyAllAugmentations()
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].reapplyAllSourceFiles();
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__["initSymbolToStockMap"])();
} // Calculate the number of cycles have elapsed while offline
Engine._lastUpdate = new Date().getTime();
const lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].lastUpdate;
const timeOffline = Engine._lastUpdate - lastUpdate;
const numCyclesOffline = Math.floor(timeOffline / Engine._idleSpeed);
let offlineReputation = 0;
const offlineHackingIncome = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].moneySourceA.hacking / _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug * timeOffline * 0.75;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gainMoney(offlineHackingIncome); // Process offline progress
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_28__[/* loadAllRunningScripts */ "b"])(); // This also takes care of offline production for those scripts
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].isWorking) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].focus = true;
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workForFaction(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].createProgramWork(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].takeClass(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].commitCrime(numCyclesOffline);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workPartTime(numCyclesOffline);
} else {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].work(numCyclesOffline);
}
} else {
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].factions.length; i++) {
const facName = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].factions[i];
if (!_Faction_Factions__WEBPACK_IMPORTED_MODULE_13__["Factions"].hasOwnProperty(facName)) continue;
const faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_13__["Factions"][facName];
if (!faction.isMember) continue; // No rep for special factions.
const info = faction.getInfo();
if (!info.offersWork()) continue; // No rep for gangs.
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].getGangName() === facName) continue;
const hRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19__["getHackingWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], faction);
const sRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19__["getFactionSecurityWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], faction);
const fRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_19__["getFactionFieldWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], faction); // can be infinite, doesn't matter.
const reputationRate = Math.max(hRep, sRep, fRep) / _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].factions.length;
const rep = reputationRate * numCyclesOffline;
faction.playerReputation += rep;
offlineReputation += rep;
}
} // Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* processHacknetEarnings */ "j"])(numCyclesOffline);
const hacknetProdInfo = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* hasHacknetServers */ "h"])() ? react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_65___default.a.Fragment, null, Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_51__["Hashes"])(offlineProductionFromHacknetNodes), " hashes") : Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_50__["Money"])(offlineProductionFromHacknetNodes); // Passive faction rep gain offline
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_14__["processPassiveFactionRepGain"])(numCyclesOffline); // Stock Market offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_40__["processStockPrices"])(numCyclesOffline);
} // Gang progress for BitNode 2
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].inGang()) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].gang.process(numCyclesOffline, _Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
} // Corporation offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation.storeCycles(numCyclesOffline);
} // Bladeburner offline progress
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__["Bladeburner"]) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner.storeCycles(numCyclesOffline);
} // Sleeves offline progress
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_43__["Sleeve"]) {
const expForOtherSleeves = _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[i].process(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], numCyclesOffline); // This sleeve earns experience for other sleeves
if (expForOtherSleeves == null) {
continue;
}
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves.length; ++j) {
if (j === i) {
continue;
}
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].sleeves[j].gainExperience(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], expForOtherSleeves, numCyclesOffline, true);
}
}
} // Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug = 0;
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode == null) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode = 0;
}
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].totalPlaytime += time;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastAug += time;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].playtimeSinceLastBitnode += time;
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].lastUpdate = Engine._lastUpdate;
Engine.start(); // Run main game loop and Scripts loop
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_61__["removeLoadingScreen"])();
const timeOfflineString = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["convertTimeMsToTimeElapsedString"])(time);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_65___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_65___default.a.Fragment, null, "Offline for ", timeOfflineString, ". While you were offline, your scripts generated ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_50__["Money"])(offlineHackingIncome), ", your Hacknet Nodes generated ", hacknetProdInfo, " and you gained ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_52__["Reputation"])(offlineReputation), " divided amongst your factions.")); // Close main menu accordions for loaded game
var visibleMenuTabs = [terminal, createScript, activeScripts, stats, hacknetnodes, city, milestones, tutorial, options, dev];
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstFacInvRecvd) {
visibleMenuTabs.push(factions);
} else {
factions.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstAugPurchased) {
visibleMenuTabs.push(augmentations);
} else {
augmentations.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].companyName !== "") {
visibleMenuTabs.push(job);
} else {
job.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstTimeTraveled) {
visibleMenuTabs.push(travel);
} else {
travel.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].firstProgramAvailable) {
visibleMenuTabs.push(createProgram);
} else {
createProgram.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].hasWseAccount) {
visibleMenuTabs.push(stockmarket);
} else {
stockmarket.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_5__["Bladeburner"]) {
visibleMenuTabs.push(bladeburner);
} else {
bladeburner.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_10__["Corporation"]) {
visibleMenuTabs.push(corp);
} else {
corp.style.display = "none";
}
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].inGang()) {
visibleMenuTabs.push(gang);
} else {
gang.style.display = "none";
}
Engine.closeMainMenuHeader(visibleMenuTabs);
} else {
// No save found, start new game
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_4__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]);
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_39__["initSpecialServerIps"])();
Engine.setDisplayElements(); // Sets variables for important DOM elements
Engine.start(); // Run main game loop and Scripts loop
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].init();
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_36__["initForeignServers"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].getHomeComputer());
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_9__["initCompanies"])();
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_13__["initFactions"])();
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_2__[/* initAugmentations */ "d"])();
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_25__[/* initMessages */ "c"])();
Object(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_38__["updateSourceFileFlags"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"]); // Open main menu accordions for new game
const hackingHdr = document.getElementById("hacking-menu-header");
hackingHdr.classList.toggle("opened");
const characterHdr = document.getElementById("character-menu-header");
characterHdr.classList.toggle("opened");
const worldHdr = document.getElementById("world-menu-header");
worldHdr.classList.toggle("opened");
const helpHdr = document.getElementById("help-menu-header");
helpHdr.classList.toggle("opened"); // Hide tabs that wont be revealed until later
factions.style.display = "none";
augmentations.style.display = "none";
job.style.display = "none";
stockmarket.style.display = "none";
travel.style.display = "none";
createProgram.style.display = "none";
bladeburner.style.display = "none";
corp.style.display = "none";
gang.style.display = "none";
dev.style.display = "none";
Engine.openMainMenuHeader([terminal, createScript, activeScripts, stats, hacknetnodes, city, milestones, tutorial, options]); // Start interactive tutorial
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_22__["iTutorialStart"])();
Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_61__["removeLoadingScreen"])();
} // Initialize labels on game settings
Object(_ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_49__[/* setSettingsLabels */ "a"])();
_Terminal__WEBPACK_IMPORTED_MODULE_42__[/* Terminal */ "a"].resetTerminalInput();
},
setDisplayElements: function () {
// Content elements
Engine.Display.terminalContent = document.getElementById("terminal-container");
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal);
Engine.Display.characterContent = document.getElementById("character-container");
Engine.Display.characterContent.style.display = "none";
Engine.Display.scriptEditorContent = document.getElementById("script-editor-container");
Engine.Display.scriptEditorContent.style.display = "none";
Engine.Display.activeScriptsContent = document.getElementById("active-scripts-container");
Engine.Display.activeScriptsContent.style.display = "none";
Engine.Display.hacknetNodesContent = document.getElementById("hacknet-nodes-container");
Engine.Display.hacknetNodesContent.style.display = "none";
Engine.Display.createProgramContent = document.getElementById("create-program-container");
Engine.Display.createProgramContent.style.display = "none";
Engine.Display.factionsContent = document.getElementById("factions-container");
Engine.Display.factionsContent.style.display = "none";
Engine.Display.factionContent = document.getElementById("faction-container");
Engine.Display.factionContent.style.display = "none";
Engine.Display.augmentationsContent = document.getElementById("augmentations-container");
Engine.Display.augmentationsContent.style.display = "none";
Engine.Display.milestonesContent = document.getElementById("milestones-container");
Engine.Display.milestonesContent.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.gangContent = document.getElementById("gang-container");
Engine.Display.gangContent.style.display = "none";
Engine.Display.bladeburnerContent = document.getElementById("gang-container");
Engine.Display.bladeburnerContent.style.display = "none";
Engine.Display.missionContent = document.getElementById("mission-container");
Engine.Display.missionContent.style.display = "none"; // Character info
Engine.Display.characterInfo = document.getElementById("character-content"); // Location page (page that shows up when you visit a specific location in World)
Engine.Display.locationContent = document.getElementById("location-container");
Engine.Display.locationContent.style.display = "none"; // Work In Progress
Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container");
Engine.Display.workInProgressContent.style.display = "none"; // Red Pill / Hack World Daemon
Engine.Display.redPillContent = document.getElementById("red-pill-container");
Engine.Display.redPillContent.style.display = "none"; // Cinematic Text
Engine.Display.cinematicTextContent = document.getElementById("cinematic-text-container");
Engine.Display.cinematicTextContent.style.display = "none"; // Initialize references to main menu links
if (!Object(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["initializeMainMenuLinks"])()) {
const errorMsg = "Failed to initialize Main Menu Links. Please try refreshing the page. " + "If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
},
// Initialization
init: function () {
// Import game link
document.getElementById("import-game-link").onclick = function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].importGame();
}; // Initialize Main Menu Headers (this must be done after initializing the links)
if (!Object(_ui_MainMenu_Headers__WEBPACK_IMPORTED_MODULE_54__["initializeMainMenuHeaders"])(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"], "development" === "development")) {
const errorMsg = "Failed to initialize Main Menu Headers. Please try refreshing the page. " + "If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_60__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Terminal.addEventListener("click", function () {
Engine.loadTerminalContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ScriptEditor.addEventListener("click", function () {
Engine.loadScriptEditorContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].ActiveScripts.addEventListener("click", function () {
Engine.loadActiveScriptsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].CreateProgram.addEventListener("click", function () {
Engine.loadCreateProgramContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Stats.addEventListener("click", function () {
Engine.loadCharacterContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Factions.addEventListener("click", function () {
Engine.loadFactionsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Augmentations.addEventListener("click", function () {
Engine.loadAugmentationsContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].HacknetNodes.addEventListener("click", function () {
Engine.loadHacknetNodesContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Sleeves.addEventListener("click", function () {
Engine.loadSleevesContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Sleeves.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].City.addEventListener("click", function () {
Engine.loadLocationContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Travel.addEventListener("click", function () {
Engine.loadTravelContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Job.addEventListener("click", function () {
Engine.loadJobContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].StockMarket.addEventListener("click", function () {
Engine.loadStockMarketContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].StockMarket.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Bladeburner.addEventListener("click", function () {
Engine.loadBladeburnerContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Corporation.addEventListener("click", function () {
Engine.loadCorporationContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Corporation.classList.add("active");
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Gang.addEventListener("click", function () {
Engine.loadGangContent();
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Gang.classList.add('active');
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Milestones.addEventListener("click", function () {
Engine.loadMilestonesContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].Tutorial.addEventListener("click", function () {
Engine.loadTutorialContent();
return false;
});
_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_55__["MainMenuLinks"].DevMenu.addEventListener("click", function () {
if (true) {
Engine.loadDevMenuContent();
}
return false;
}); // Active scripts list
Engine.ActiveScriptsList = document.getElementById("active-scripts-list"); // Save, Delete, Import/Export buttons
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].saveGame(Engine.indexedDb);
return false;
});
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].deleteGame(Engine.indexedDb);
return false;
});
document.getElementById("export-game-link").addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].exportGame();
return false;
}); // Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function () {
_SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].saveGame(Engine.indexedDb);
return false;
});
document.getElementById("character-overview-options-button").addEventListener("click", function () {
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_59__[/* gameOptionsBoxOpen */ "b"])();
return false;
}); // Create Program buttons
Object(_Programs_ProgramHelpers__WEBPACK_IMPORTED_MODULE_32__[/* initCreateProgramButtons */ "c"])(); // Message at the top of terminal
Object(_Terminal__WEBPACK_IMPORTED_MODULE_42__[/* postNetburnerText */ "b"])(); // Player was working cancel button
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].isWorking) {
var cancelButton = document.getElementById("work-in-progress-cancel-button");
cancelButton.addEventListener("click", function () {
if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeFaction) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishFactionWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCreateProgram) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishCreateProgramWork(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeStudyClass) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishClass();
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCrime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishCrime(true);
} else if (_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCompanyPartTime) {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishWorkPartTime();
} else {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].finishWork(true);
}
});
const focusButton = document.getElementById("work-in-progress-something-else-button");
focusButton.style.visibility = "hidden";
const focusable = [_Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeFaction, _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCompanyPartTime, _Constants__WEBPACK_IMPORTED_MODULE_11__["CONSTANTS"].WorkTypeCompany];
if (focusable.includes(_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].workType)) {
focusButton.style.visibility = "visible";
focusButton.addEventListener("click", function () {
_Player__WEBPACK_IMPORTED_MODULE_30__["Player"].stopFocusing();
});
}
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("milestones-menu-link").removeAttribute("class");
document.getElementById("tutorial-menu-link").removeAttribute("class"); // Copy Save Data to Clipboard
document.getElementById("copy-save-to-clipboard-link").addEventListener("click", function () {
const saveString = _SaveObject__WEBPACK_IMPORTED_MODULE_34__[/* saveObject */ "b"].getSaveString();
if (!navigator.clipboard) {
// Async Clipboard API not supported, so we'll use this using the
// textarea and document.execCommand('copy') trick
const textArea = document.createElement("textarea");
textArea.value = saveString;
textArea.setAttribute("readonly", '');
textArea.style.position = 'absolute';
textArea.left = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand("copy");
if (successful) {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__["createStatusText"])("Copied save to clipboard");
} else {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__["createStatusText"])("Failed to copy save");
}
} catch (e) {
console.error("Unable to copy save data to clipboard using document.execCommand('copy')");
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__["createStatusText"])("Failed to copy save");
}
document.body.removeChild(textArea);
} else {
// Use the Async Clipboard API
navigator.clipboard.writeText(saveString).then(function () {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__["createStatusText"])("Copied save to clipboard");
}, function (err) {
console.error(err);
console.error("Unable to copy save data to clipboard using Async API");
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_46__["createStatusText"])("Failed to copy save");
});
}
}); // DEBUG Delete active Scripts on home
document.getElementById("debug-delete-scripts-link").addEventListener("click", function () {
for (const hostname of Object.keys(_Server_AllServers__WEBPACK_IMPORTED_MODULE_36__["AllServers"])) {
_Server_AllServers__WEBPACK_IMPORTED_MODULE_36__["AllServers"][hostname].runningScripts = [];
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__["dialogBoxCreate"])("Forcefully deleted all running scripts. Please save and refresh page.");
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_59__[/* gameOptionsBoxClose */ "a"])();
return false;
}); // DEBUG Soft Reset
document.getElementById("debug-soft-reset").addEventListener("click", function () {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_58__["dialogBoxCreate"])("Soft Reset!");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_31__[/* prestigeAugmentation */ "a"])();
Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_59__[/* gameOptionsBoxClose */ "a"])();
return false;
}); // DEBUG File diagnostic
document.getElementById("debug-files").addEventListener("click", function () {
Object(_ui_React_createPopup__WEBPACK_IMPORTED_MODULE_57__["createPopup"])("debug-files-diagnostic-popup", _Diagnostic_FileDiagnosticPopup__WEBPACK_IMPORTED_MODULE_56__["FileDiagnosticPopup"], {});
return false;
});
},
start: function () {
// Run main loop
Engine.idleTimer();
}
};
var 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.error("Error opening indexedDB: ");
console.error(e);
return Engine.load(null); // Try to load from localstorage
};
indexedDbRequest.onsuccess = function (e) {
Engine.indexedDb = e.target.result;
var transaction = Engine.indexedDb.transaction(["savestring"]);
var objectStore = transaction.objectStore("savestring");
var request = objectStore.get("save");
request.onerror = function (e) {
console.error("Error in Database request to get savestring: " + e);
return Engine.load(null); // Try to load from localstorage
};
request.onsuccess = function () {
Engine.load(request.result);
};
};
indexedDbRequest.onupgradeneeded = function (e) {
const db = e.target.result;
db.createObjectStore("savestring");
};
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 16 */
/*!*******************************************!*\
!*** ./src/Augmentation/Augmentation.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Augmentation = void 0;
// Class definition for a single Augmentation object
const React = __importStar(__webpack_require__(/*! react */ 0));
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const Factions_1 = __webpack_require__(/*! ../Faction/Factions */ 17);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
function generateStatsDescription(mults, programs, startingMoney) {
const f = (x, decimals = 0) => {
// look, I don't know how to make a "smart decimals"
// todo, make it smarter
if (x === 1.0777 - 1)
return "7.77%";
if (x === 1.777 - 1)
return "77.7%";
return numeralFormat_1.numeralWrapper.formatPercentage(x, decimals);
};
let desc = React.createElement(React.Fragment, null, "Effects:");
if (mults.hacking_mult &&
mults.hacking_mult == mults.strength_mult &&
mults.hacking_mult == mults.defense_mult &&
mults.hacking_mult == mults.dexterity_mult &&
mults.hacking_mult == mults.agility_mult &&
mults.hacking_mult == mults.charisma_mult) {
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_mult - 1),
" all skills");
}
else {
if (mults.hacking_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_mult - 1),
" hacking skill");
if (mults.strength_mult &&
mults.strength_mult == mults.defense_mult &&
mults.strength_mult == mults.dexterity_mult &&
mults.strength_mult == mults.agility_mult) {
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.strength_mult - 1),
" combat skills");
}
else {
if (mults.strength_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.strength_mult - 1),
" strength skill");
if (mults.defense_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.defense_mult - 1),
" defense skill");
if (mults.dexterity_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.dexterity_mult - 1),
" dexterity skill");
if (mults.agility_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.agility_mult - 1),
" agility skill");
}
if (mults.charisma_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.charisma_mult - 1),
" Charisma skill");
}
if (mults.hacking_exp_mult &&
mults.hacking_exp_mult === mults.strength_exp_mult &&
mults.hacking_exp_mult === mults.defense_exp_mult &&
mults.hacking_exp_mult === mults.dexterity_exp_mult &&
mults.hacking_exp_mult === mults.agility_exp_mult &&
mults.hacking_exp_mult === mults.charisma_exp_mult) {
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_exp_mult - 1),
" exp for all skills");
}
else {
if (mults.hacking_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_exp_mult - 1),
" hacking exp");
if (mults.strength_exp_mult &&
mults.strength_exp_mult === mults.defense_exp_mult &&
mults.strength_exp_mult === mults.dexterity_exp_mult &&
mults.strength_exp_mult === mults.agility_exp_mult) {
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.strength_exp_mult - 1),
" combat exp");
}
else {
if (mults.strength_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.strength_exp_mult - 1),
" strength exp");
if (mults.defense_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.defense_exp_mult - 1),
" defense exp");
if (mults.dexterity_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.dexterity_exp_mult - 1),
" dexterity exp");
if (mults.agility_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.agility_exp_mult - 1),
" agility exp");
}
if (mults.charisma_exp_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.charisma_exp_mult - 1),
" charisma exp");
}
if (mults.hacking_speed_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_speed_mult - 1),
" faster hacking");
if (mults.hacking_chance_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_chance_mult - 1),
" hack() success chance");
if (mults.hacking_money_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_money_mult - 1),
" hack() power");
if (mults.hacking_grow_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacking_grow_mult - 1),
" grow() power");
if (mults.faction_rep_mult &&
mults.faction_rep_mult === mults.company_rep_mult) {
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.faction_rep_mult - 1),
" reputation from factions and companies");
}
else {
if (mults.faction_rep_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.faction_rep_mult - 1),
" reputation from factions");
if (mults.company_rep_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.company_rep_mult - 1),
" reputation from companies");
}
if (mults.crime_money_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.crime_money_mult - 1),
" crime money");
if (mults.crime_success_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.crime_success_mult - 1),
" crime success rate");
if (mults.work_money_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.work_money_mult - 1),
" work money");
if (mults.hacknet_node_money_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.hacknet_node_money_mult - 1),
" hacknet production");
if (mults.hacknet_node_purchase_cost_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"-",
f(-(mults.hacknet_node_purchase_cost_mult - 1)),
" hacknet nodes cost");
if (mults.hacknet_node_level_cost_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"-",
f(-(mults.hacknet_node_level_cost_mult - 1)),
" hacknet nodes upgrade cost");
if (mults.bladeburner_max_stamina_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.bladeburner_max_stamina_mult - 1),
" Bladeburner Max Stamina");
if (mults.bladeburner_stamina_gain_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.bladeburner_stamina_gain_mult - 1),
" Bladeburner Stamina gain");
if (mults.bladeburner_analysis_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.bladeburner_analysis_mult - 1),
" Bladeburner Field Analysis effectiveness");
if (mults.bladeburner_success_chance_mult)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"+",
f(mults.bladeburner_success_chance_mult - 1),
" Bladeburner Contracts and Operations success chance");
if (startingMoney)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"Start with ",
Money_1.Money(startingMoney),
" after installing Augmentations.");
if (programs)
desc = React.createElement(React.Fragment, null,
desc,
React.createElement("br", null),
"Start with ",
programs.join(' and '),
" after installing Augmentations.");
return desc;
}
class Augmentation {
constructor(params = { info: "", moneyCost: 0, name: "", repCost: 0 }) {
// How much money this costs to buy
this.baseCost = 0;
// How much faction reputation is required to unlock this
this.baseRepRequirement = 0;
// Any Augmentation not immediately available in BitNode-1 is special (e.g. Bladeburner augs)
this.isSpecial = false;
// Augmentation level - for repeatable Augs like NeuroFlux Governor
this.level = 0;
// Name of Augmentation
this.name = "";
// Whether the player owns this Augmentation
this.owned = false;
// Array of names of all prerequisites
this.prereqs = [];
// Multipliers given by this Augmentation. Must match the property name in
// The Player/Person classes
this.mults = {};
// Initial cost. Doesn't change when you purchase multiple Augmentation
this.startingCost = 0;
this.name = params.name;
this.info = params.info;
this.prereqs = params.prereqs ? params.prereqs : [];
this.baseRepRequirement = params.repCost * BitNodeMultipliers_1.BitNodeMultipliers.AugmentationRepCost;
this.baseCost = params.moneyCost * BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost;
this.startingCost = this.baseCost;
if (params.isSpecial) {
this.isSpecial = true;
}
this.level = 0;
// Set multipliers
if (params.hacking_mult) {
this.mults.hacking_mult = params.hacking_mult;
}
if (params.strength_mult) {
this.mults.strength_mult = params.strength_mult;
}
if (params.defense_mult) {
this.mults.defense_mult = params.defense_mult;
}
if (params.dexterity_mult) {
this.mults.dexterity_mult = params.dexterity_mult;
}
if (params.agility_mult) {
this.mults.agility_mult = params.agility_mult;
}
if (params.charisma_mult) {
this.mults.charisma_mult = params.charisma_mult;
}
if (params.hacking_exp_mult) {
this.mults.hacking_exp_mult = params.hacking_exp_mult;
}
if (params.strength_exp_mult) {
this.mults.strength_exp_mult = params.strength_exp_mult;
}
if (params.defense_exp_mult) {
this.mults.defense_exp_mult = params.defense_exp_mult;
}
if (params.dexterity_exp_mult) {
this.mults.dexterity_exp_mult = params.dexterity_exp_mult;
}
if (params.agility_exp_mult) {
this.mults.agility_exp_mult = params.agility_exp_mult;
}
if (params.charisma_exp_mult) {
this.mults.charisma_exp_mult = params.charisma_exp_mult;
}
if (params.hacking_chance_mult) {
this.mults.hacking_chance_mult = params.hacking_chance_mult;
}
if (params.hacking_speed_mult) {
this.mults.hacking_speed_mult = params.hacking_speed_mult;
}
if (params.hacking_money_mult) {
this.mults.hacking_money_mult = params.hacking_money_mult;
}
if (params.hacking_grow_mult) {
this.mults.hacking_grow_mult = params.hacking_grow_mult;
}
if (params.company_rep_mult) {
this.mults.company_rep_mult = params.company_rep_mult;
}
if (params.faction_rep_mult) {
this.mults.faction_rep_mult = params.faction_rep_mult;
}
if (params.crime_money_mult) {
this.mults.crime_money_mult = params.crime_money_mult;
}
if (params.crime_success_mult) {
this.mults.crime_success_mult = params.crime_success_mult;
}
if (params.work_money_mult) {
this.mults.work_money_mult = params.work_money_mult;
}
if (params.hacknet_node_money_mult) {
this.mults.hacknet_node_money_mult = params.hacknet_node_money_mult;
}
if (params.hacknet_node_purchase_cost_mult) {
this.mults.hacknet_node_purchase_cost_mult = params.hacknet_node_purchase_cost_mult;
}
if (params.hacknet_node_ram_cost_mult) {
this.mults.hacknet_node_ram_cost_mult = params.hacknet_node_ram_cost_mult;
}
if (params.hacknet_node_core_cost_mult) {
this.mults.hacknet_node_core_cost_mult = params.hacknet_node_core_cost_mult;
}
if (params.hacknet_node_level_cost_mult) {
this.mults.hacknet_node_level_cost_mult = params.hacknet_node_level_cost_mult;
}
if (params.bladeburner_max_stamina_mult) {
this.mults.bladeburner_max_stamina_mult = params.bladeburner_max_stamina_mult;
}
if (params.bladeburner_stamina_gain_mult) {
this.mults.bladeburner_stamina_gain_mult = params.bladeburner_stamina_gain_mult;
}
if (params.bladeburner_analysis_mult) {
this.mults.bladeburner_analysis_mult = params.bladeburner_analysis_mult;
}
if (params.bladeburner_success_chance_mult) {
this.mults.bladeburner_success_chance_mult = params.bladeburner_success_chance_mult;
}
if (params.stats)
this.stats = params.stats;
else
this.stats = generateStatsDescription(this.mults, params.programs, params.startingMoney);
}
// Adds this Augmentation to the specified Factions
addToFactions(factionList) {
for (let i = 0; i < factionList.length; ++i) {
const faction = Factions_1.Factions[factionList[i]];
if (faction == null) {
console.warn(`In Augmentation.addToFactions(), could not find faction with this name: ${factionList[i]}`);
continue;
}
faction.augmentations.push(this.name);
}
}
// Adds this Augmentation to all Factions
addToAllFactions() {
for (const fac in Factions_1.Factions) {
if (Factions_1.Factions.hasOwnProperty(fac)) {
const facObj = Factions_1.Factions[fac];
if (facObj == null) {
console.warn(`Invalid Faction object in addToAllFactions(). Key value: ${fac}`);
continue;
}
facObj.augmentations.push(this.name);
}
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("Augmentation", this);
}
// Initiatizes a Augmentation object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Augmentation, value.data);
}
}
exports.Augmentation = Augmentation;
JSONReviver_1.Reviver.constructors.Augmentation = Augmentation;
/***/ }),
/* 17 */
/*!*********************************!*\
!*** ./src/Faction/Factions.ts ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetFaction = exports.initFactions = exports.factionExists = exports.AddToFactions = exports.loadFactions = exports.Factions = void 0;
/**
* Initialization and manipulation of the Factions object, which stores data
* about all Factions in the game
*/
const Faction_1 = __webpack_require__(/*! ./Faction */ 125);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 695);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
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() {
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;
/***/ }),
/* 18 */
/*!**************************************!*\
!*** ./src/ui/navigationTracking.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.routing = exports.Page = void 0;
/**
* The full-screen page the player is currently be on.
* These pages are mutually exclusive.
*/
var Page;
(function (Page) {
/**
* (Default) The terminal is where the player issues all commands, executes scripts, etc.
*/
Page["Terminal"] = "Terminal";
/**
* Displays most of the statistics about the player.
*/
Page["CharacterInfo"] = "CharacterInfo";
/**
* The console for editing Netscript files.
*/
Page["ScriptEditor"] = "ScriptEditor";
/**
* Monitor the scripts currently executing across the servers.
*/
Page["ActiveScripts"] = "ActiveScripts";
/**
* View, purchase, and upgrade Hacknet nodes.
*/
Page["HacknetNodes"] = "HacknetNodes";
/**
* The list of programs the player could potentially build.
*/
Page["CreateProgram"] = "CreateProgram";
/**
* The list of all factions, and invites, available to the player.
*/
Page["Factions"] = "Factions";
/**
* Information about a specific faction.
*/
Page["Faction"] = "Faction";
/**
* The list of installed, and yet-to-be installed, augmentations the player has purchased.
*/
Page["Augmentations"] = "Augmentations";
/**
* List of milestones that players should follow.
*/
Page["Milestones"] = "Milestones";
/**
* A collection of in-game material to learn about the game.
*/
Page["Tutorial"] = "Tutorial";
/**
* A collection of items to manipulate the state of the game. Useful for development.
*/
Page["DevMenu"] = "Dev Menu";
/**
* Visiting a location in the world
*/
Page["Location"] = "Location";
/**
* A blocking page to show the player they are currently doing some action (building a program, working, etc.).
*/
Page["workInProgress"] = "WorkInProgress";
/**
* A special screen to show the player they've reached a certain point in the game.
*/
Page["RedPill"] = "RedPill";
/**
* A special screen to show the player they've reached a certain point in the game.
*/
Page["CinematicText"] = "CinematicText";
/**
* Mini-game to infiltrate a company, gaining experience from successful progress.
*/
Page["Infiltration"] = "Infiltration";
/**
* View the in-game stock market.
*/
Page["StockMarket"] = "StockMarket";
/**
* Manage gang actions and members.
*/
Page["Gang"] = "Gang";
/**
* Perform missions for a Faction.
*/
Page["Mission"] = "Mission";
/**
* Manage a corporation.
*/
Page["Corporation"] = "Corporation";
/**
* Manage special Bladeburner activities.
*/
Page["Bladeburner"] = "Bladeburner";
/**
* Manage your Sleeves
*/
Page["Sleeves"] = "Sleeves";
/**
* Purchase Resleeves
*/
Page["Resleeves"] = "Re-sleeving";
})(Page = exports.Page || (exports.Page = {}));
/**
* This class keeps track of player navigation/routing within the game.
*/
class Routing {
constructor() {
/**
* Tracking the what page the user is currently on.
*/
this.currentPage = null;
}
/**
* Determines if the player is currently on the specified page.
* @param page The page to compare against the current state.
*/
isOn(page) {
return this.currentPage === page;
}
/**
* Routes the player to the appropriate page.
* @param page The page to navigate to.
*/
navigateTo(page) {
this.currentPage = page;
}
}
/**
* The routing instance for tracking page navigation.
*/
exports.routing = new Routing();
/***/ }),
/* 19 */
/*!*******************************************!*\
!*** ./src/BitNode/BitNodeMultipliers.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BitNodeMultipliers = void 0;
/**
* The multipliers that are influenced by current Bitnode progression.
*/
// tslint:disable-next-line:variable-name
exports.BitNodeMultipliers = {
HackingLevelMultiplier: 1,
StrengthLevelMultiplier: 1,
DefenseLevelMultiplier: 1,
DexterityLevelMultiplier: 1,
AgilityLevelMultiplier: 1,
CharismaLevelMultiplier: 1,
ServerGrowthRate: 1,
ServerMaxMoney: 1,
ServerStartingMoney: 1,
ServerStartingSecurity: 1,
ServerWeakenRate: 1,
HomeComputerRamCost: 1,
PurchasedServerCost: 1,
PurchasedServerLimit: 1,
PurchasedServerMaxRam: 1,
CompanyWorkMoney: 1,
CrimeMoney: 1,
HacknetNodeMoney: 1,
ManualHackMoney: 1,
ScriptHackMoney: 1,
ScriptHackMoneyGain: 1,
CodingContractMoney: 1,
ClassGymExpGain: 1,
CompanyWorkExpGain: 1,
CrimeExpGain: 1,
FactionWorkExpGain: 1,
HackExpGain: 1,
FactionPassiveRepGain: 1,
FactionWorkRepGain: 1,
RepToDonateToFaction: 1,
AugmentationMoneyCost: 1,
AugmentationRepCost: 1,
InfiltrationMoney: 1,
InfiltrationRep: 1,
FourSigmaMarketDataCost: 1,
FourSigmaMarketDataApiCost: 1,
CorporationValuation: 1,
BladeburnerRank: 1,
BladeburnerSkillCost: 1,
DaedalusAugsRequirement: 1,
GangKarmaRequirement: 1,
};
/***/ }),
/* 20 */
/*!**********************************!*\
!*** ./src/Server/AllServers.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadAllServers = exports.prestigeAllServers = exports.initForeignServers = exports.AddToAllServers = exports.createUniqueRandomIp = exports.ipExists = exports.AllServers = void 0;
const Server_1 = __webpack_require__(/*! ./Server */ 488);
const SpecialServerIps_1 = __webpack_require__(/*! ./SpecialServerIps */ 38);
const servers_1 = __webpack_require__(/*! ./data/servers */ 1060);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 399);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
/**
* Map of all Servers that exist in the game
* Key (string) = IP
* Value = Server object
*/
exports.AllServers = {};
function ipExists(ip) {
return (exports.AllServers[ip] != null);
}
exports.ipExists = ipExists;
function createUniqueRandomIp() {
const ip = IPAddress_1.createRandomIp();
// If the Ip already exists, recurse to create a new one
if (ipExists(ip)) {
return IPAddress_1.createRandomIp();
}
return ip;
}
exports.createUniqueRandomIp = createUniqueRandomIp;
// Saftely add a Server to the AllServers map
function AddToAllServers(server) {
const serverIp = server.ip;
if (ipExists(serverIp)) {
console.warn(`IP of server that's being added: ${serverIp}`);
console.warn(`Hostname of the server thats being added: ${server.hostname}`);
console.warn(`The server that already has this IP is: ${exports.AllServers[serverIp].hostname}`);
throw new Error("Error: Trying to add a server with an existing IP");
}
exports.AllServers[serverIp] = server;
}
exports.AddToAllServers = AddToAllServers;
function initForeignServers(homeComputer) {
/* Create a randomized network for all the foreign servers */
//Groupings for creating a randomized network
const networkLayers = [];
for (let i = 0; i < 15; i++) {
networkLayers.push([]);
}
// Essentially any property that is of type 'number | IMinMaxRange'
const propertiesToPatternMatch = [
"hackDifficulty",
"moneyAvailable",
"requiredHackingSkill",
"serverGrowth",
];
const toNumber = (value) => {
switch (typeof value) {
case 'number':
return value;
case 'object':
return getRandomInt_1.getRandomInt(value.min, value.max);
default:
throw Error(`Do not know how to convert the type '${typeof value}' to a number`);
}
};
for (const metadata of servers_1.serverMetadata) {
const serverParams = {
hostname: metadata.hostname,
ip: createUniqueRandomIp(),
numOpenPortsRequired: metadata.numOpenPortsRequired,
organizationName: metadata.organizationName,
};
if (metadata.maxRamExponent !== undefined) {
serverParams.maxRam = Math.pow(2, toNumber(metadata.maxRamExponent));
}
for (const prop of propertiesToPatternMatch) {
if (metadata[prop] !== undefined) {
serverParams[prop] = toNumber(metadata[prop]);
}
}
const server = new Server_1.Server(serverParams);
for (const filename of (metadata.literature || [])) {
server.messages.push(filename);
}
if (metadata.specialName !== undefined) {
SpecialServerIps_1.SpecialServerIps.addIp(metadata.specialName, server.ip);
}
AddToAllServers(server);
if (metadata.networkLayer !== undefined) {
networkLayers[toNumber(metadata.networkLayer) - 1].push(server);
}
}
/* Create a randomized network for all the foreign servers */
const linkComputers = (server1, server2) => {
server1.serversOnNetwork.push(server2.ip);
server2.serversOnNetwork.push(server1.ip);
};
const getRandomArrayItem = (arr) => arr[Math.floor(Math.random() * arr.length)];
const linkNetworkLayers = (network1, selectServer) => {
for (const server of network1) {
linkComputers(server, selectServer());
}
};
// Connect the first tier of servers to the player's home computer
linkNetworkLayers(networkLayers[0], () => homeComputer);
for (let i = 1; i < networkLayers.length; i++) {
linkNetworkLayers(networkLayers[i], () => getRandomArrayItem(networkLayers[i - 1]));
}
}
exports.initForeignServers = initForeignServers;
function prestigeAllServers() {
for (const member in exports.AllServers) {
delete exports.AllServers[member];
}
exports.AllServers = {};
}
exports.prestigeAllServers = prestigeAllServers;
function loadAllServers(saveString) {
exports.AllServers = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadAllServers = loadAllServers;
/***/ }),
/* 21 */,
/* 22 */
/*!*************************************!*\
!*** ./src/Server/ServerHelpers.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBackdoorInstalled = exports.getServerOnNetwork = exports.getServer = exports.GetServerByHostname = exports.prestigeHomeComputer = exports.processSingleServerGrowth = exports.numCycleForGrowth = exports.safetlyCreateUniqueServer = void 0;
const AllServers_1 = __webpack_require__(/*! ./AllServers */ 20);
const Server_1 = __webpack_require__(/*! ./Server */ 488);
const grow_1 = __webpack_require__(/*! ./formulas/grow */ 522);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const Programs_1 = __webpack_require__(/*! ../Programs/Programs */ 30);
const LiteratureNames_1 = __webpack_require__(/*! ../Literature/data/LiteratureNames */ 144);
const isValidNumber_1 = __webpack_require__(/*! ../utils/helpers/isValidNumber */ 1059);
const isValidIPAddress_1 = __webpack_require__(/*! ../../utils/helpers/isValidIPAddress */ 679);
/**
* Constructs a new server, while also ensuring that the new server
* does not have a duplicate hostname/ip.
*/
function safetlyCreateUniqueServer(params) {
if (params.ip != null && AllServers_1.ipExists(params.ip)) {
params.ip = AllServers_1.createUniqueRandomIp();
}
if (GetServerByHostname(params.hostname) != null) {
// Use a for loop to ensure that we don't get suck in an infinite loop somehow
let hostname = params.hostname;
for (let i = 0; i < 200; ++i) {
hostname = `${params.hostname}-${i}`;
if (GetServerByHostname(hostname) == null) {
break;
}
}
params.hostname = hostname;
}
return new Server_1.Server(params);
}
exports.safetlyCreateUniqueServer = safetlyCreateUniqueServer;
/**
* Returns the number of "growth cycles" needed to grow the specified server by the
* specified amount.
* @param server - Server being grown
* @param growth - How much the server is being grown by, in DECIMAL form (e.g. 1.5 rather than 50)
* @param p - Reference to Player object
* @returns Number of "growth cycles" needed
*/
function numCycleForGrowth(server, growth, p) {
let ajdGrowthRate = 1 + (Constants_1.CONSTANTS.ServerBaseGrowthRate - 1) / server.hackDifficulty;
if (ajdGrowthRate > Constants_1.CONSTANTS.ServerMaxGrowthRate) {
ajdGrowthRate = Constants_1.CONSTANTS.ServerMaxGrowthRate;
}
const serverGrowthPercentage = server.serverGrowth / 100;
const cycles = Math.log(growth) / (Math.log(ajdGrowthRate) * p.hacking_grow_mult * serverGrowthPercentage * BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate);
return cycles;
}
exports.numCycleForGrowth = numCycleForGrowth;
//Applied server growth for a single server. Returns the percentage growth
function processSingleServerGrowth(server, threads, p, cores = 1) {
let serverGrowth = grow_1.calculateServerGrowth(server, threads, p, cores);
if (serverGrowth < 1) {
console.warn("serverGrowth calculated to be less than 1");
serverGrowth = 1;
}
const oldMoneyAvailable = server.moneyAvailable;
server.moneyAvailable *= serverGrowth;
// in case of data corruption
if (isValidNumber_1.isValidNumber(server.moneyMax) && isNaN(server.moneyAvailable)) {
server.moneyAvailable = server.moneyMax;
}
// cap at max
if (isValidNumber_1.isValidNumber(server.moneyMax) && server.moneyAvailable > server.moneyMax) {
server.moneyAvailable = server.moneyMax;
}
// if there was any growth at all, increase security
if (oldMoneyAvailable !== server.moneyAvailable) {
//Growing increases server security twice as much as hacking
let usedCycles = numCycleForGrowth(server, server.moneyAvailable / oldMoneyAvailable, p);
usedCycles = Math.max(0, usedCycles);
server.fortify(2 * Constants_1.CONSTANTS.ServerFortifyAmount * Math.ceil(usedCycles));
}
return server.moneyAvailable / oldMoneyAvailable;
}
exports.processSingleServerGrowth = processSingleServerGrowth;
function prestigeHomeComputer(homeComp) {
const hasBitflume = homeComp.programs.includes(Programs_1.Programs.BitFlume.name);
homeComp.programs.length = 0; //Remove programs
homeComp.runningScripts = [];
homeComp.serversOnNetwork = [];
homeComp.isConnectedTo = true;
homeComp.ramUsed = 0;
homeComp.programs.push(Programs_1.Programs.NukeProgram.name);
if (hasBitflume) {
homeComp.programs.push(Programs_1.Programs.BitFlume.name);
}
//Update RAM usage on all scripts
homeComp.scripts.forEach(function (script) {
script.updateRamUsage(homeComp.scripts);
});
homeComp.messages.length = 0; //Remove .lit and .msg files
homeComp.messages.push(LiteratureNames_1.LiteratureNames.HackersStartingHandbook);
}
exports.prestigeHomeComputer = prestigeHomeComputer;
//Returns server object with corresponding hostname
// Relatively slow, would rather not use this a lot
function GetServerByHostname(hostname) {
for (const ip in AllServers_1.AllServers) {
if (AllServers_1.AllServers.hasOwnProperty(ip)) {
if (AllServers_1.AllServers[ip].hostname == hostname) {
return AllServers_1.AllServers[ip];
}
}
}
return null;
}
exports.GetServerByHostname = GetServerByHostname;
//Get server by IP or hostname. Returns null if invalid
function getServer(s) {
if (!isValidIPAddress_1.isValidIPAddress(s)) {
return GetServerByHostname(s);
}
if (AllServers_1.AllServers[s] !== undefined) {
return AllServers_1.AllServers[s];
}
return null;
}
exports.getServer = getServer;
// Returns the i-th server on the specified server's network
// A Server's serverOnNetwork property holds only the IPs. This function returns
// the actual Server object
function getServerOnNetwork(server, i) {
if (i > server.serversOnNetwork.length) {
console.error("Tried to get server on network that was out of range");
return null;
}
return AllServers_1.AllServers[server.serversOnNetwork[i]];
}
exports.getServerOnNetwork = getServerOnNetwork;
function isBackdoorInstalled(server) {
if ("backdoorInstalled" in server) {
return server.backdoorInstalled;
}
return false;
}
exports.isBackdoorInstalled = isBackdoorInstalled;
/***/ }),
/* 23 */
/*!****************************************!*\
!*** ./utils/StringHelperFunctions.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceAt = exports.generateRandomString = exports.isHTML = exports.formatNumber = exports.containsAllStrings = exports.longestCommonStart = exports.convertTimeMsToTimeElapsedString = void 0;
const isString_1 = __webpack_require__(/*! ./helpers/isString */ 72);
// Netburner String helper functions
// Replaces the character at an index with a new character
function replaceAt(base, index, character) {
return base.substr(0, index) + character + base.substr(index + character.length);
}
exports.replaceAt = replaceAt;
/*
Converts a date representing time in milliseconds to a string with the format H hours M minutes and S seconds
e.g. 10000 -> "10 seconds"
120000 -> "2 minutes and 0 seconds"
*/
function convertTimeMsToTimeElapsedString(time, showMilli = false) {
time = Math.floor(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 milliTruncSec = (() => {
let str = `${time % millisecondsPerSecond}`;
while (str.length < 3)
str = "0" + str;
return str;
})();
const seconds = showMilli ? `${secTruncMinutes}.${milliTruncSec}` : `${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 = 0) {
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;
/***/ }),
/* 24 */
/*!**********************************!*\
!*** ./src/Settings/Settings.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Settings = void 0;
const SettingEnums_1 = __webpack_require__(/*! ./SettingEnums */ 222);
const defaultSettings = {
AutosaveInterval: 60,
CodeInstructionRunTime: 50,
DisableASCIIArt: false,
DisableHotkeys: false,
DisableTextEffects: false,
Locale: "en",
MaxLogCapacity: 50,
MaxPortCapacity: 50,
SuppressBuyAugmentationConfirmation: false,
SuppressFactionInvites: false,
SuppressHospitalizationPopup: false,
SuppressMessages: false,
SuppressTravelConfirmation: false,
SuppressBladeburnerPopup: 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,
DisableASCIIArt: defaultSettings.DisableASCIIArt,
DisableHotkeys: defaultSettings.DisableHotkeys,
DisableTextEffects: defaultSettings.DisableTextEffects,
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,
SuppressBladeburnerPopup: defaultSettings.SuppressBladeburnerPopup,
MonacoTheme: 'vs-dark',
MonacoInsertSpaces: false,
init() {
Object.assign(exports.Settings, defaultSettings);
},
load(saveString) {
Object.assign(exports.Settings, JSON.parse(saveString));
},
};
/***/ }),
/* 25 */
/*!****************************************!*\
!*** ./src/Hacknet/HacknetHelpers.jsx ***!
\****************************************/
/*! exports provided: hasHacknetServers, purchaseHacknet, hasMaxNumberHacknetServers, getCostOfNextHacknetNode, getCostOfNextHacknetServer, getMaxNumberLevelUpgrades, getMaxNumberRamUpgrades, getMaxNumberCoreUpgrades, getMaxNumberCacheUpgrades, purchaseLevelUpgrade, purchaseRamUpgrade, purchaseCoreUpgrade, purchaseCacheUpgrade, renderHacknetNodesUI, clearHacknetNodesUI, processHacknetEarnings, updateHashManagerCapacity, purchaseHashUpgrade */
/*! exports used: clearHacknetNodesUI, getCostOfNextHacknetNode, getCostOfNextHacknetServer, getMaxNumberCacheUpgrades, getMaxNumberCoreUpgrades, getMaxNumberLevelUpgrades, getMaxNumberRamUpgrades, hasHacknetServers, hasMaxNumberHacknetServers, processHacknetEarnings, purchaseCacheUpgrade, purchaseCoreUpgrade, purchaseHacknet, purchaseHashUpgrade, purchaseLevelUpgrade, purchaseRamUpgrade, renderHacknetNodesUI, updateHashManagerCapacity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return hasHacknetServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return purchaseHacknet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return hasMaxNumberHacknetServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCostOfNextHacknetNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getCostOfNextHacknetServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getMaxNumberLevelUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getMaxNumberRamUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getMaxNumberCoreUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getMaxNumberCacheUpgrades; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return purchaseLevelUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return purchaseRamUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return purchaseCoreUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return purchaseCacheUpgrade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return renderHacknetNodesUI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clearHacknetNodesUI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return processHacknetEarnings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return updateHashManagerCapacity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return purchaseHashUpgrade; });
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HacknetNode */ 535);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_HacknetNode__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./formulas/HacknetNodes */ 153);
/* harmony import */ var _formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./formulas/HacknetServers */ 139);
/* harmony import */ var _formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./data/Constants */ 34);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_data_Constants__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _HacknetServer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./HacknetServer */ 78);
/* harmony import */ var _HacknetServer__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_HacknetServer__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./HashManager */ 177);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_HashManager__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./HashUpgrades */ 241);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_HashUpgrades__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../CodingContractGenerator */ 176);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../InteractiveTutorial */ 43);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./ui/Root */ 449);
/**
* Generic helper/utility functions for the Hacknet mechanic:
* - Purchase nodes/upgrades
* - Calculating maximum number of upgrades
* - Processing Hacknet earnings
* - Updating Hash Manager capacity
* - Purchasing hash upgrades
*
* TODO Should probably split the different types of functions into their own modules
*/
let hacknetNodesDiv;
function hacknetNodesInit() {
hacknetNodesDiv = document.getElementById("hacknet-nodes-container");
document.removeEventListener("DOMContentLoaded", hacknetNodesInit);
}
document.addEventListener("DOMContentLoaded", hacknetNodesInit); // Returns a boolean indicating whether the player has Hacknet Servers
// (the upgraded form of Hacknet Nodes)
function hasHacknetServers() {
return _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].bitNodeN === 9 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_12__["SourceFileFlags"][9] > 0;
}
function purchaseHacknet() {
/* INTERACTIVE TUTORIAL */
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_8__["ITutorial"].isRunning) {
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_8__["ITutorial"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_8__["iTutorialSteps"].HacknetNodesIntroduction) {
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_8__["iTutorialNextStep"])();
} else {
return;
}
}
/* END INTERACTIVE TUTORIAL */
const numOwned = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length;
if (hasHacknetServers()) {
const cost = getCostOfNextHacknetServer();
if (isNaN(cost)) {
throw new Error(`Calculated cost of purchasing HacknetServer is NaN`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return -1;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].createHacknetServer();
updateHashManagerCapacity();
return numOwned;
} else {
const cost = getCostOfNextHacknetNode();
if (isNaN(cost)) {
throw new Error(`Calculated cost of purchasing HacknetNode is NaN`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return -1;
} // Auto generate a name for the Node
const name = "hacknet-node-" + numOwned;
const node = new _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"](name, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.push(node);
return numOwned;
}
}
function hasMaxNumberHacknetServers() {
return hasHacknetServers() && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length >= _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxServers;
}
function getCostOfNextHacknetNode() {
return Object(_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_1__["calculateNodeCost"])(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length + 1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_purchase_cost_mult);
}
function getCostOfNextHacknetServer() {
return Object(_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_2__["calculateServerCost"])(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length + 1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_purchase_cost_mult);
} // Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node's level
function getMaxNumberLevelUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberLevelUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
let levelsToMax = maxLevel - nodeObj.level;
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult))) {
return levelsToMax;
}
while (min <= max) {
var curr = (min + max) / 2 | 0;
if (curr !== maxLevel && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult)) && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr + 1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
} // Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node's RAM
function getMaxNumberRamUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberRamUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateRamUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_ram_cost_mult))) {
return 0;
}
let levelsToMax;
if (nodeObj instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"]) {
levelsToMax = Math.round(Math.log2(maxLevel / nodeObj.maxRam));
} else {
levelsToMax = Math.round(Math.log2(maxLevel / nodeObj.ram));
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateRamUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_ram_cost_mult))) {
return levelsToMax;
} //We'll just loop until we find the max
for (let i = levelsToMax - 1; i >= 0; --i) {
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateRamUpgradeCost(i, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_ram_cost_mult))) {
return i;
}
}
return 0;
} // Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node's cores
function getMaxNumberCoreUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberCoreUpgrades() called without maxLevel arg`);
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
const levelsToMax = maxLevel - nodeObj.cores;
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(levelsToMax, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult))) {
return levelsToMax;
} // Use a binary search to find the max possible number of upgrades
while (min <= max) {
let curr = (min + max) / 2 | 0;
if (curr != maxLevel && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult)) && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(curr + 1, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult))) {
return Math.min(levelsToMax, curr);
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.lt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].money.gt(nodeObj.calculateCoreUpgradeCost(curr, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
} // Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node's cache
function getMaxNumberCacheUpgrades(nodeObj, maxLevel) {
if (maxLevel == null) {
throw new Error(`getMaxNumberCacheUpgrades() called without maxLevel arg`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(1))) {
return 0;
}
let min = 1;
let max = maxLevel - 1;
const levelsToMax = maxLevel - nodeObj.cache;
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(levelsToMax))) {
return levelsToMax;
} // Use a binary search to find the max possible number of upgrades
while (min <= max) {
let curr = (min + max) / 2 | 0;
if (curr != maxLevel && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr)) && !_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr + 1))) {
return Math.min(levelsToMax, curr);
} else if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr))) {
max = curr - 1;
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(nodeObj.calculateCacheUpgradeCost(curr))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
return 0;
}
function purchaseLevelUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateLevelUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_level_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"]; // If we're at max level, return false
if (node.level >= (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxLevel : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxLevel)) {
return false;
} // If the number of specified upgrades would exceed the max level, calculate
// the maximum number of upgrades and use that
if (node.level + sanitizedLevels > (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxLevel : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxLevel)) {
const diff = Math.max(0, (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxLevel : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxLevel) - node.level);
return purchaseLevelUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
node.upgradeLevel(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseRamUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateRamUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_ram_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"]; // Fail if we're already at max
if (node.ram >= (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxRam : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxRam)) {
return false;
} // If the number of specified upgrades would exceed the max RAM, calculate the
// max possible number of upgrades and use that
if (isServer) {
if (node.maxRam * Math.pow(2, sanitizedLevels) > _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxRam) {
const diff = Math.max(0, Math.log2(Math.round(_data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxRam / node.maxRam)));
return purchaseRamUpgrade(node, diff);
}
} else {
if (node.ram * Math.pow(2, sanitizedLevels) > _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxRam) {
const diff = Math.max(0, Math.log2(Math.round(_data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxRam / node.ram)));
return purchaseRamUpgrade(node, diff);
}
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
node.upgradeRam(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseCoreUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateCoreUpgradeCost(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_core_cost_mult);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
const isServer = node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"]; // Fail if we're already at max
if (node.cores >= (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxCores : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxCores)) {
return false;
} // If the specified number of upgrades would exceed the max Cores, calculate
// the max possible number of upgrades and use that
if (node.cores + sanitizedLevels > (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxCores : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxCores)) {
const diff = Math.max(0, (isServer ? _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxCores : _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetNodeConstants"].MaxCores) - node.cores);
return purchaseCoreUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
node.upgradeCore(sanitizedLevels, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
return true;
}
function purchaseCacheUpgrade(node, levels = 1) {
const sanitizedLevels = Math.round(levels);
const cost = node.calculateCacheUpgradeCost(sanitizedLevels);
if (isNaN(cost) || cost <= 0 || sanitizedLevels < 0) {
return false;
}
if (!(node instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"])) {
console.warn(`purchaseCacheUpgrade() called for a non-HacknetNode`);
return false;
} // Fail if we're already at max
if (node.cache + sanitizedLevels > _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxCache) {
const diff = Math.max(0, _data_Constants__WEBPACK_IMPORTED_MODULE_3__["HacknetServerConstants"].MaxCache - node.cache);
return purchaseCacheUpgrade(node, diff);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].canAfford(cost)) {
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].loseMoney(cost);
node.upgradeCache(sanitizedLevels);
return true;
} // Create/Refresh Hacknet Nodes UI
function renderHacknetNodesUI() {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].HacknetNodes)) {
return;
}
react_dom__WEBPACK_IMPORTED_MODULE_15___default.a.render(react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_16__[/* HacknetRoot */ "a"], null), hacknetNodesDiv);
}
function clearHacknetNodesUI() {
if (hacknetNodesDiv instanceof HTMLElement) {
react_dom__WEBPACK_IMPORTED_MODULE_15___default.a.unmountComponentAtNode(hacknetNodesDiv);
}
hacknetNodesDiv.style.display = "none";
}
function processHacknetEarnings(numCycles) {
// Determine if player has Hacknet Nodes or Hacknet Servers, then
// call the appropriate function
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length === 0) {
return 0;
}
if (hasHacknetServers()) {
return processAllHacknetServerEarnings(numCycles);
} else if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes[0] instanceof _HacknetNode__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"]) {
return processAllHacknetNodeEarnings(numCycles);
} else {
return 0;
}
}
function processAllHacknetNodeEarnings(numCycles) {
let total = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length; ++i) {
total += processSingleHacknetNodeEarnings(numCycles, _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes[i]);
}
return total;
}
function processSingleHacknetNodeEarnings(numCycles, nodeObj) {
const totalEarnings = nodeObj.process(numCycles);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].gainMoney(totalEarnings);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].recordMoneySource(totalEarnings, "hacknetnode");
return totalEarnings;
}
function processAllHacknetServerEarnings(numCycles) {
if (!(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_5__["HashManager"])) {
throw new Error(`Player does not have a HashManager (should be in 'hashManager' prop)`);
}
let hashes = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length; ++i) {
// hacknetNodes array only contains the IP addresses of the servers.
// Also, update the hash rate before processing
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes[i]];
hserver.updateHashRate(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknet_node_money_mult);
const h = hserver.process(numCycles);
hserver.totalHashesGenerated += h;
hashes += h;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.storeHashes(hashes);
return hashes;
}
function updateHashManagerCapacity() {
if (!(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_5__["HashManager"])) {
console.error(`Player does not have a HashManager`);
return;
}
const nodes = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes;
if (nodes.length === 0) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.updateCapacity(0);
return;
}
let total = 0;
for (let i = 0; i < nodes.length; ++i) {
if (typeof nodes[i] !== "string") {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.updateCapacity(0);
return;
}
const h = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][nodes[i]];
if (!(h instanceof _HacknetServer__WEBPACK_IMPORTED_MODULE_4__["HacknetServer"])) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.updateCapacity(0);
return;
}
total += h.hashCapacity;
}
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.updateCapacity(total);
}
function purchaseHashUpgrade(upgName, upgTarget) {
if (!(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_5__["HashManager"])) {
console.error(`Player does not have a HashManager`);
return false;
} // HashManager handles the transaction. This just needs to actually implement
// the effects of the upgrade
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.upgrade(upgName)) {
const upg = _HashUpgrades__WEBPACK_IMPORTED_MODULE_6__["HashUpgrades"][upgName];
switch (upgName) {
case "Sell for Money":
{
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].gainMoney(upg.value);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].recordMoneySource(upg.value, "hacknetnode");
break;
}
case "Sell for Corporation Funds":
{
// This will throw if player doesn't have a corporation
try {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].corporation.funds = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].corporation.funds.plus(upg.value);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Reduce Minimum Security":
{
try {
const target = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__["GetServerByHostname"])(upgTarget);
if (target == null) {
console.error(`Invalid target specified in purchaseHashUpgrade(): ${upgTarget}`);
return false;
}
target.changeMinimumSecurity(upg.value, true);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Increase Maximum Money":
{
try {
const target = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__["GetServerByHostname"])(upgTarget);
if (target == null) {
console.error(`Invalid target specified in purchaseHashUpgrade(): ${upgTarget}`);
return false;
}
target.changeMaximumMoney(upg.value, true);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Improve Studying":
{
// Multiplier handled by HashManager
break;
}
case "Improve Gym Training":
{
// Multiplier handled by HashManager
break;
}
case "Exchange for Corporation Research":
{
// This will throw if player doesn't have a corporation
try {
for (const division of _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].corporation.divisions) {
division.sciResearch.qty += upg.value;
}
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Exchange for Bladeburner Rank":
{
// This will throw if player isnt in Bladeburner
try {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].bladeburner.changeRank(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"], upg.value);
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Exchange for Bladeburner SP":
{
// This will throw if player isn't in Bladeburner
try {
// As long as we don't change `Bladeburner.totalSkillPoints`, this
// shouldn't affect anything else
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].bladeburner.skillPoints += upg.value;
} catch (e) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
break;
}
case "Generate Coding Contract":
{
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_7__["generateRandomContract"])();
break;
}
default:
console.warn(`Unrecognized upgrade name ${upgName}. Upgrade has no effect`);
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hashManager.refundUpgrade(upgName);
return false;
}
return true;
}
return false;
}
/***/ }),
/* 26 */,
/* 27 */
/*!********************************!*\
!*** ./src/ui/React/Money.tsx ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Money = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function Money(money) {
return React.createElement("span", { className: "money-gold samefont" }, typeof money === 'number' ? numeralFormat_1.numeralWrapper.formatMoney(money) : money);
}
exports.Money = Money;
/***/ }),
/* 28 */,
/* 29 */
/*!******************************!*\
!*** ./utils/JSONReviver.js ***!
\******************************/
/*! exports provided: Reviver, Generic_toJSON, Generic_fromJSON */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reviver", function() { return Reviver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_toJSON", function() { return Generic_toJSON; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_fromJSON", function() { return Generic_fromJSON; });
/* Generic Reviver, toJSON, and fromJSON functions used for saving and loading objects */
// A generic "smart reviver" function.
// Looks for object values with a `ctor` property and
// a `data` property. If it finds them, and finds a matching
// constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value.
function Reviver(key, value) {
var ctor;
if (value == null) {
console.log("Reviver WRONGLY called with key: " + key + ", and value: " + value);
return 0;
}
if (typeof value === "object" &&
typeof value.ctor === "string" &&
typeof value.data !== "undefined") {
// Compatibility for version v0.43.1
// TODO Remove this eventually
if (value.ctor === "AllServersMap") {
console.log('Converting AllServersMap for v0.43.1');
return value.data;
}
ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
}
}
return value;
}
Reviver.constructors = {}; // A list of constructors the smart reviver should know about
// A generic "toJSON" function that creates the data expected
// by Reviver.
// `ctorName` The name of the constructor to use to revive it
// `obj` The object being serialized
// `keys` (Optional) Array of the properties to serialize,
// if not given then all of the objects "own" properties
// that don't have function values will be serialized.
// (Note: If you list a property in `keys`, it will be serialized
// regardless of whether it's an "own" property.)
// Returns: The structure (which will then be turned into a string
// as part of the JSON.stringify algorithm)
function Generic_toJSON(ctorName, obj, keys) {
var data, key;
if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included
}
data = {};
for (let index = 0; index < keys.length; ++index) {
key = keys[index];
data[key] = obj[key];
}
return {ctor: ctorName, data: data};
}
// A generic "fromJSON" function for use with Reviver: Just calls the
// constructor function with no arguments, then applies all of the
// key/value pairs from the raw data to the instance. Only useful for
// constructors that can be reasonably called without arguments!
// `ctor` The constructor to call
// `data` The data to apply
// Returns: The object
function Generic_fromJSON(ctor, data) {
var obj, name;
obj = new ctor();
for (name in data) {
obj[name] = data[name];
}
return obj;
}
/***/ }),
/* 30 */
/*!**********************************!*\
!*** ./src/Programs/Programs.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Programs = void 0;
const Program_1 = __webpack_require__(/*! ./Program */ 1082);
const ProgramsMetadata_1 = __webpack_require__(/*! ./data/ProgramsMetadata */ 1081);
exports.Programs = {};
for (const params of ProgramsMetadata_1.programsMetadata) {
exports.Programs[params.key] = new Program_1.Program(params.name, params.create);
}
/***/ }),
/* 31 */
/*!**********************************!*\
!*** ./src/ui/MainMenu/Links.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeMainMenuLinks = exports.MainMenuLinks = void 0;
// Get references to the Main Menu link DOM elements
// Does NOT include collapsible headers for the links
const clearEventListeners_1 = __webpack_require__(/*! ../../../utils/uiHelpers/clearEventListeners */ 49);
const emptyElement = (() => {
const elem = document.createElement('div');
if (elem === null)
throw new Error("unable to create empty div element");
return elem;
})();
exports.MainMenuLinks = {
Terminal: emptyElement,
ScriptEditor: emptyElement,
ActiveScripts: emptyElement,
CreateProgram: emptyElement,
Stats: emptyElement,
Factions: emptyElement,
Augmentations: emptyElement,
HacknetNodes: emptyElement,
Sleeves: emptyElement,
City: emptyElement,
Travel: emptyElement,
Job: emptyElement,
StockMarket: emptyElement,
Bladeburner: emptyElement,
Corporation: emptyElement,
Gang: emptyElement,
Milestones: emptyElement,
Tutorial: emptyElement,
Options: emptyElement,
DevMenu: emptyElement,
};
function initializeMainMenuLinks() {
try {
function safeGetLink(id) {
const elem = clearEventListeners_1.clearEventListeners(id);
if (elem == null) {
throw new Error(`clearEventListeners() failed for element with id: ${id}`);
}
return elem;
}
exports.MainMenuLinks.Terminal = safeGetLink("terminal-menu-link");
exports.MainMenuLinks.ScriptEditor = safeGetLink("create-script-menu-link");
exports.MainMenuLinks.ActiveScripts = safeGetLink("active-scripts-menu-link");
exports.MainMenuLinks.CreateProgram = safeGetLink("create-program-menu-link");
exports.MainMenuLinks.Stats = safeGetLink("stats-menu-link");
exports.MainMenuLinks.Factions = safeGetLink("factions-menu-link");
exports.MainMenuLinks.Augmentations = safeGetLink("augmentations-menu-link");
exports.MainMenuLinks.HacknetNodes = safeGetLink("hacknet-nodes-menu-link");
exports.MainMenuLinks.Sleeves = safeGetLink("sleeves-menu-link");
exports.MainMenuLinks.City = safeGetLink("city-menu-link");
exports.MainMenuLinks.Travel = safeGetLink("travel-menu-link");
exports.MainMenuLinks.Job = safeGetLink("job-menu-link");
exports.MainMenuLinks.StockMarket = safeGetLink("stock-market-menu-link");
exports.MainMenuLinks.Bladeburner = safeGetLink("bladeburner-menu-link");
exports.MainMenuLinks.Corporation = safeGetLink("corporation-menu-link");
exports.MainMenuLinks.Gang = safeGetLink("gang-menu-link");
exports.MainMenuLinks.Milestones = safeGetLink("milestones-menu-link");
exports.MainMenuLinks.Tutorial = safeGetLink("tutorial-menu-link");
const op = document.getElementById("options-menu-link");
if (op === null)
throw new Error(`Could not find element with id: "options-menu-link"`);
exports.MainMenuLinks.Options = op; // This click listener is already set, so don't clear it
exports.MainMenuLinks.DevMenu = safeGetLink("dev-menu-link");
return true;
}
catch (e) {
console.error(`Failed to initialize Main Menu Links: ${e}`);
return false;
}
}
exports.initializeMainMenuLinks = initializeMainMenuLinks;
/***/ }),
/* 32 */,
/* 33 */
/*!**********************************!*\
!*** ./src/Company/Companies.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.companyExists = exports.loadCompanies = exports.initCompanies = exports.Companies = void 0;
// Constructs all CompanyPosition objects using the metadata in data/companypositions.ts
const CompaniesMetadata_1 = __webpack_require__(/*! ./data/CompaniesMetadata */ 1083);
const Company_1 = __webpack_require__(/*! ./Company */ 138);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
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;
/***/ }),
/* 34 */
/*!***************************************!*\
!*** ./src/Hacknet/data/Constants.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HacknetServerConstants = exports.HacknetNodeConstants = void 0;
exports.HacknetNodeConstants = {
MoneyGainPerLevel: 1.6,
BaseCost: 1000,
LevelBaseCost: 1,
RamBaseCost: 30e3,
CoreBaseCost: 500e3,
PurchaseNextMult: 1.85,
UpgradeLevelMult: 1.04,
UpgradeRamMult: 1.28,
UpgradeCoreMult: 1.48,
MaxLevel: 200,
MaxRam: 64,
MaxCores: 16,
};
exports.HacknetServerConstants = {
HashesPerLevel: 0.001,
BaseCost: 50e3,
RamBaseCost: 200e3,
CoreBaseCost: 1e6,
CacheBaseCost: 10e6,
PurchaseMult: 3.20,
UpgradeLevelMult: 1.10,
UpgradeRamMult: 1.40,
UpgradeCoreMult: 1.55,
UpgradeCacheMult: 1.85,
MaxServers: 20,
MaxLevel: 300,
MaxRam: 8192,
MaxCores: 128,
MaxCache: 15,
};
/***/ }),
/* 35 */,
/* 36 */,
/* 37 */
/*!*******************************************!*\
!*** ./src/SourceFile/SourceFileFlags.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Contains an array containing information about the player's source files
// Array[n] returns what level the player has of Source-File N.
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateSourceFileFlags = exports.SourceFileFlags = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
exports.SourceFileFlags = Array(Constants_1.CONSTANTS.TotalNumBitNodes + 1); // Skip index 0
function updateSourceFileFlags(p) {
for (let i = 0; i < exports.SourceFileFlags.length; ++i) {
exports.SourceFileFlags[i] = 0;
}
for (let i = 0; i < p.sourceFiles.length; ++i) {
const sf = p.sourceFiles[i];
exports.SourceFileFlags[sf.n] = sf.lvl;
}
}
exports.updateSourceFileFlags = updateSourceFileFlags;
/***/ }),
/* 38 */
/*!****************************************!*\
!*** ./src/Server/SpecialServerIps.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSpecialServerIps = exports.loadSpecialServerIps = exports.prestigeSpecialServerIps = exports.SpecialServerIps = exports.SpecialServerIpsMap = exports.SpecialServerNames = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
/* Holds IP of Special Servers */
exports.SpecialServerNames = {
FulcrumSecretTechnologies: "Fulcrum Secret Technologies Server",
CyberSecServer: "CyberSec Server",
NiteSecServer: "NiteSec Server",
TheBlackHandServer: "The Black Hand Server",
BitRunnersServer: "BitRunners Server",
TheDarkArmyServer: "The Dark Army Server",
DaedalusServer: "Daedalus Server",
WorldDaemon: "w0r1d_d43m0n",
};
class SpecialServerIpsMap {
addIp(name, ip) {
this[name] = ip;
}
getIp(name) {
return this[name];
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("SpecialServerIpsMap", this);
}
// Initializes a SpecialServerIpsMap Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(SpecialServerIpsMap, value.data);
}
}
exports.SpecialServerIpsMap = SpecialServerIpsMap;
JSONReviver_1.Reviver.constructors.SpecialServerIpsMap = SpecialServerIpsMap;
exports.SpecialServerIps = new SpecialServerIpsMap();
function prestigeSpecialServerIps() {
for (const member in exports.SpecialServerIps) {
delete exports.SpecialServerIps[member];
}
exports.SpecialServerIps = new SpecialServerIpsMap();
}
exports.prestigeSpecialServerIps = prestigeSpecialServerIps;
function loadSpecialServerIps(saveString) {
exports.SpecialServerIps = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadSpecialServerIps = loadSpecialServerIps;
function initSpecialServerIps() {
exports.SpecialServerIps = new SpecialServerIpsMap();
}
exports.initSpecialServerIps = initSpecialServerIps;
/***/ }),
/* 39 */
/*!************************************!*\
!*** ./src/Fconf/FconfSettings.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FconfSettings = void 0;
exports.FconfSettings = {
ENABLE_BASH_HOTKEYS: false,
ENABLE_TIMESTAMPS: false,
MAIN_MENU_STYLE: "default",
THEME_BACKGROUND_COLOR: "#000000",
THEME_FONT_COLOR: "#66ff33",
THEME_HIGHLIGHT_COLOR: "#ffffff",
THEME_PROMPT_COLOR: "#f92672",
WRAP_INPUT: false,
};
/***/ }),
/* 40 */
/*!*********************************************!*\
!*** ./src/Locations/data/LocationNames.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocationName = void 0;
/**
* Names of all locations
*/
var LocationName;
(function (LocationName) {
// Cities
LocationName["Aevum"] = "Aevum";
LocationName["Chongqing"] = "Chongqing";
LocationName["Ishima"] = "Ishima";
LocationName["NewTokyo"] = "New Tokyo";
LocationName["Sector12"] = "Sector-12";
LocationName["Volhaven"] = "Volhaven";
// Aevum Locations
LocationName["AevumAeroCorp"] = "AeroCorp";
LocationName["AevumBachmanAndAssociates"] = "Bachman & Associates";
LocationName["AevumClarkeIncorporated"] = "Clarke Incorporated";
LocationName["AevumCrushFitnessGym"] = "Crush Fitness Gym";
LocationName["AevumECorp"] = "ECorp";
LocationName["AevumFulcrumTechnologies"] = "Fulcrum Technologies";
LocationName["AevumGalacticCybersystems"] = "Galactic Cybersystems";
LocationName["AevumNetLinkTechnologies"] = "NetLink Technologies";
LocationName["AevumPolice"] = "Aevum Police Headquarters";
LocationName["AevumRhoConstruction"] = "Rho Construction";
LocationName["AevumSnapFitnessGym"] = "Snap Fitness Gym";
LocationName["AevumSummitUniversity"] = "Summit University";
LocationName["AevumWatchdogSecurity"] = "Watchdog Security";
LocationName["AevumCasino"] = "Iker Molina Casino";
// Chongqing locations
LocationName["ChongqingKuaiGongInternational"] = "KuaiGong International";
LocationName["ChongqingSolarisSpaceSystems"] = "Solaris Space Systems";
// Sector 12
LocationName["Sector12AlphaEnterprises"] = "Alpha Enterprises";
LocationName["Sector12BladeIndustries"] = "Blade Industries";
LocationName["Sector12CIA"] = "Central Intelligence Agency";
LocationName["Sector12CarmichaelSecurity"] = "Carmichael Security";
LocationName["Sector12CityHall"] = "Sector-12 City Hall";
LocationName["Sector12DeltaOne"] = "DeltaOne";
LocationName["Sector12FoodNStuff"] = "FoodNStuff";
LocationName["Sector12FourSigma"] = "Four Sigma";
LocationName["Sector12IcarusMicrosystems"] = "Icarus Microsystems";
LocationName["Sector12IronGym"] = "Iron Gym";
LocationName["Sector12JoesGuns"] = "Joe's Guns";
LocationName["Sector12MegaCorp"] = "MegaCorp";
LocationName["Sector12NSA"] = "National Security Agency";
LocationName["Sector12PowerhouseGym"] = "Powerhouse Gym";
LocationName["Sector12RothmanUniversity"] = "Rothman University";
LocationName["Sector12UniversalEnergy"] = "Universal Energy";
// New Tokyo
LocationName["NewTokyoDefComm"] = "DefComm";
LocationName["NewTokyoGlobalPharmaceuticals"] = "Global Pharmaceuticals";
LocationName["NewTokyoNoodleBar"] = "Noodle Bar";
LocationName["NewTokyoVitaLife"] = "VitaLife";
// Ishima
LocationName["IshimaNovaMedical"] = "Nova Medical";
LocationName["IshimaOmegaSoftware"] = "Omega Software";
LocationName["IshimaStormTechnologies"] = "Storm Technologies";
// Volhaven
LocationName["VolhavenCompuTek"] = "CompuTek";
LocationName["VolhavenHeliosLabs"] = "Helios Labs";
LocationName["VolhavenLexoCorp"] = "LexoCorp";
LocationName["VolhavenMilleniumFitnessGym"] = "Millenium Fitness Gym";
LocationName["VolhavenNWO"] = "NWO";
LocationName["VolhavenOmniTekIncorporated"] = "OmniTek Incorporated";
LocationName["VolhavenOmniaCybersystems"] = "Omnia Cybersystems";
LocationName["VolhavenSysCoreSecurities"] = "SysCore Securities";
LocationName["VolhavenZBInstituteOfTechnology"] = "ZB Institute of Technology";
// Generic locations
LocationName["Hospital"] = "Hospital";
LocationName["Slums"] = "The Slums";
LocationName["TravelAgency"] = "Travel Agency";
LocationName["WorldStockExchange"] = "World Stock Exchange";
// Default name for Location objects
LocationName["Void"] = "The Void";
})(LocationName = exports.LocationName || (exports.LocationName = {}));
/***/ }),
/* 41 */
/*!**************************************!*\
!*** ./src/ui/React/createPopup.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.removePopup = exports.createPopup = void 0;
/**
* Create a pop-up dialog box using React.
*
* Calling this function with the same ID and React Root Component will trigger a re-render
*
* @param id The (hopefully) unique identifier for the popup container
* @param rootComponent Root React Component for the content (NOT the popup containers themselves)
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ 21));
const Popup_1 = __webpack_require__(/*! ./Popup */ 1136);
const createElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createElement */ 51);
const removeElementById_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElementById */ 90);
let gameContainer;
(function () {
function getGameContainer() {
const container = document.getElementById("entire-game-container");
if (container == null) {
throw new Error(`Failed to find game container DOM element`);
}
gameContainer = container;
document.removeEventListener("DOMContentLoaded", getGameContainer);
}
document.addEventListener("DOMContentLoaded", getGameContainer);
})();
// This variable is used to avoid setting the semi-transparent background
// several times on top of one another. Sometimes there's several popup at once.
let deepestPopupId = "";
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function createPopup(id, rootComponent, props) {
let container = document.getElementById(id);
if (container == null) {
function onClick(event) {
if (!event.srcElement)
return;
if (!(event.srcElement instanceof HTMLElement))
return;
const clickedId = event.srcElement.id;
if (clickedId !== id)
return;
removePopup(id);
}
const backgroundColor = deepestPopupId === "" ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0)';
container = createElement_1.createElement("div", {
class: "popup-box-container",
display: "flex",
id: id,
backgroundColor: backgroundColor,
clickListener: onClick,
});
gameContainer.appendChild(container);
}
if (deepestPopupId === "")
deepestPopupId = id;
ReactDOM.render(React.createElement(Popup_1.Popup, { content: rootComponent, id: id, props: props, removePopup: removePopup }), container);
return container;
}
exports.createPopup = createPopup;
/**
* Closes a popup created with the createPopup() function above
*/
function removePopup(id) {
const content = document.getElementById(`${id}`);
if (content == null)
return;
ReactDOM.unmountComponentAtNode(content);
removeElementById_1.removeElementById(id);
removeElementById_1.removeElementById(`${id}-close`);
if (id === deepestPopupId)
deepestPopupId = "";
}
exports.removePopup = removePopup;
/***/ }),
/* 42 */
/*!*****************************************!*\
!*** ./src/Locations/data/CityNames.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CityName = void 0;
/**
* All possible Cities in the game. Names only, not actual "City" object
* Implemented as an enum for typing purposes
*/
var CityName;
(function (CityName) {
CityName["Aevum"] = "Aevum";
CityName["Chongqing"] = "Chongqing";
CityName["Ishima"] = "Ishima";
CityName["NewTokyo"] = "New Tokyo";
CityName["Sector12"] = "Sector-12";
CityName["Volhaven"] = "Volhaven";
})(CityName = exports.CityName || (exports.CityName = {}));
/***/ }),
/* 43 */
/*!************************************!*\
!*** ./src/InteractiveTutorial.js ***!
\************************************/
/*! exports provided: iTutorialSteps, iTutorialEnd, iTutorialStart, iTutorialNextStep, ITutorial */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialSteps", function() { return iTutorialSteps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialEnd", function() { return iTutorialEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialStart", function() { return iTutorialStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialNextStep", function() { return iTutorialNextStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ITutorial", function() { return ITutorial; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ui/MainMenu/Links */ 31);
/* harmony import */ var _ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Literature/data/LiteratureNames */ 144);
/* harmony import */ var _Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 91);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 49);
/* 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_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 51);
/* 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_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 129);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 90);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_9__);
// 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 n00dles
"TerminalAnalyze", // Analyzing n00dles
"TerminalNuke", // NUKE n00dles
"TerminalManualHack", // Hack n00dles
"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;
}
const 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;
ITutorial.currStep = 0;
ITutorial.isRunning = true;
document.getElementById("interactive-tutorial-container").style.display = "block";
// Exit tutorial button
const exitButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("interactive-tutorial-exit");
exitButton.addEventListener("click", function() {
iTutorialEnd();
return false;
});
// Back button
const backButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("interactive-tutorial-back");
backButton.addEventListener("click", function() {
iTutorialPrevStep();
return false;
});
// Next button
const nextButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("interactive-tutorial-next");
nextButton.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
iTutorialEvaluateStep();
}
function iTutorialEvaluateStep() {
if (!ITutorial.isRunning) {return;}
// Disable and clear main menu
const terminalMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("terminal-menu-link");
const statsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("stats-menu-link");
const activeScriptsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("active-scripts-menu-link");
const hacknetMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("hacknet-nodes-menu-link");
const cityMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("city-menu-link");
const tutorialMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_6__["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
const nextBtn = document.getElementById("interactive-tutorial-next");
switch(ITutorial.currStep) {
case iTutorialSteps.Start:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " +
"The game takes place in a dark, dystopian future... The year is 2077...
" +
"This tutorial will show you the basics of the game. " +
"You may skip the tutorial at any time.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.GoToCharacterPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Let's start by heading to the Stats page. Click the Stats tab on " +
"the main navigation menu (left-hand side of the screen)");
nextBtn.style.display = "none";
// Flash 'Stats' menu and set its tutorial click handler
statsMainMenu.setAttribute("class", "flashing-button");
statsMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialNextStep(); //Opening the character page will go to the next step
return false;
});
break;
case iTutorialSteps.CharacterPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialSetText("The Stats page shows a lot of important information about your progress, " +
"such as your skills, money, and bonuses. ")
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.CharacterGoToTerminalPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialSetText("Let's head to your computer's terminal by clicking the Terminal tab on the " +
"main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Terminal' menu and set its tutorial click handler
terminalMainMenu.setAttribute("class", "flashing-button");
terminalMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TerminalIntro:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The Terminal is used to interface with your home computer as well as " +
"all of the other machines around the world.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.TerminalHelp:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Let's try it out. Start by entering the help command into the Terminal " +
"(Don't forget to press Enter after typing the command)");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalLs:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The help command displays a list of all available Terminal commands, how to use them, " +
"and a description of what they do.
Let's try another command. Enter the ls command.");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScan:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText(" ls is a basic command that shows files " +
"on the computer. Right now, it shows that you have a program called NUKE.exe on your computer. " +
"We'll get to what this does later.
Using your home computer's terminal, you can connect " +
"to other machines throughout the world. Let's do that now by first entering " +
"the scan command.");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze1:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The scan command shows all available network connections. In other words, " +
"it displays a list of all servers that can be connected to from your " +
"current machine. A server is identified by its hostname.
" +
"That's great and all, but there's so many servers. Which one should you go to? " +
"The scan-analyze command gives some more detailed information about servers on the " +
"network. Try it now!");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze2:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You just ran scan-analyze with a depth of one. This command shows more detailed " +
"information about each server that you can connect to (servers that are a distance of " +
"one node away).
It is also possible to run scan-analyze with " +
"a higher depth. Let's try a depth of two with the following command: scan-analyze 2.")
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalConnect:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " +
"as figure out how to navigate to those servers through the network. You can only connect to " +
"a server that is one node away. To connect to a machine, use the connect [hostname] command.
" +
"From the results of the scan-analyze command, we can see that the n00dles server is " +
"only one node away. Let's connect so it now using: connect n00dles");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalAnalyze:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!
In the year 2077, currency has " +
"become digital and decentralized. People and corporations store their money " +
"on servers and computers. Using your hacking abilities, you can hack servers " +
"to steal money and gain experience.
" +
"Before you try to hack a server, you should run diagnostics using the analyze command.");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalNuke:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("When the analyze command finishes running it will show useful information " +
"about hacking the server.
For this server, the required hacking skill is only 1, " +
"which means you can hack it right now. However, in order to hack a server " +
"you must first gain root access. The NUKE.exe program that we saw earlier on your " +
"home computer is a virus that will grant you root access to a machine if there are enough " +
"open ports.
The analyze results shows that there do not need to be any open ports " +
"on this machine for the NUKE virus to work, so go ahead and run the virus using the " +
"run NUKE.exe command.");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalManualHack:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You now have root access! You can hack the server using the hack command. " +
"Try doing that now.");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalHackingMechanics:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("You are now attempting to hack the server. Performing a hack takes time and " +
"only has a certain percentage chance " +
"of success. This time and success chance is determined by a variety of factors, including " +
"your hacking skill and the server's security level.
" +
"If your attempt to hack the server is successful, you will steal a certain percentage " +
"of the server's total money. This percentage is affected by your hacking skill and " +
"the server's security level.
The amount of money on a server is not limitless. So, if " +
"you constantly hack a server and deplete its money, then you will encounter " +
"diminishing returns in your hacking.");
nextBtn.style.display = "inline-block";
break;
case iTutorialSteps.TerminalCreateScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " +
"you don't want to be hacking manually the entire time. You can automate your hacking " +
"by writing scripts!
To create a new script or edit an existing one, you can use the nano " +
"command. Scripts must end with the .script extension. Let's make a script now by " +
"entering nano n00dles.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("n00dles.script", "");
iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " +
"written in a simplified version of javascript. Copy and paste the following code into the script editor:
" +
"For anyone with basic programming experience, this code should be straightforward. " +
"This script will continuously hack the n00dles server.
" +
"To save and close the script editor, press the button in the bottom left, or press ctrl + b.");
nextBtn.style.display = "none"; // next step triggered in saveAndCloseScriptEditor() (Script.js)
break;
case iTutorialSteps.TerminalFree:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " +
"run on any machine which you have root access to. Different servers have different " +
"amounts of RAM. You can also purchase more RAM for your home server.
To check how much " +
"RAM is available on this machine, enter the free command.");
nextBtn.style.display = "none"; // next step triggered by terminal commmand
break;
case iTutorialSteps.TerminalRunScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("We have 4GB of free RAM on this machine, which is enough to run our " +
"script. Let's run our script using run n00dles.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! " +
"It will continuously run in the background and will automatically stop if " +
"the code ever completes (the n00dles.script will never complete because it " +
"runs an infinite loop).
These scripts can passively earn you income and hacking experience. " +
"Your scripts will also earn money and experience while you are offline, although at a " +
"slightly slower rate.
" +
"Let's check out some statistics for our running scripts by clicking the " +
"Active Scripts link in the main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Active Scripts' menu and set its tutorial click handler
activeScriptsMainMenu.setAttribute("class", "flashing-button");
activeScriptsMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.ActiveScriptsPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
iTutorialSetText("This page displays information about all of your scripts that are " +
"running across every server. You can use this to gauge how well " +
"your scripts are doing. Let's go back to the Terminal");
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 n00dles.script");
nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalTailScript:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " +
"just started running...but check back again in a few minutes!
" +
"This covers the basics of hacking. To learn more about writing " +
"scripts, select the Tutorial link in the " +
"main navigation menu to look at the documentation. " +
"If you are an experienced JavaScript " +
"developer, I would highly suggest you check out the section on " +
"NetscriptJS/Netscript 2.0, it's faster and more powerful.
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 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("here you can purchase new Hacknet Nodes and upgrade your " +
"existing ones. Let's purchase a new one now.");
nextBtn.style.display = "none"; // Next step triggered by purchaseHacknet() (HacknetNode.js)
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent();
iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " +
"earn you money over time, both online and offline. When you get enough " +
" money, you can upgrade " +
"your newly-purchased Hacknet Node below.
" +
"Let's go to the City page through the main navigation menu.");
nextBtn.style.display = "none";
// Flash 'City' menu and set its tutorial click handler
cityMainMenu.setAttribute("class", "flashing-button");
cityMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadLocationContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.WorldDescription:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadLocationContent();
iTutorialSetText("This page lists all of the different locations you can currently " +
"travel to. Each location has something that you can do. " +
"There's a lot of content out in the world, make sure " +
"you explore and discover!
" +
"Lastly, click on the Tutorial link in the main navigation menu.");
nextBtn.style.display = "none";
// Flash 'Tutorial' menu and set its tutorial click handler
tutorialMainMenu.setAttribute("class", "flashing-button");
tutorialMainMenu.addEventListener("click", function() {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TutorialPageInfo:
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
iTutorialSetText("This page contains a lot of different documentation about the game's " +
"content and mechanics. I know it's a lot, but I highly suggest you read " +
"(or at least skim) through this before you start playing. That's the end of the tutorial. " +
"Hope you enjoy the game!");
nextBtn.style.display = "inline-block";
nextBtn.innerHTML = "Finish Tutorial";
break;
case iTutorialSteps.End:
iTutorialEnd();
break;
default:
throw new Error("Invalid tutorial step");
}
if (ITutorial.stepIsDone[ITutorial.currStep] === true) {
nextBtn.style.display = "inline-block";
}
}
// Go to the next step and evaluate it
function iTutorialNextStep() {
// Special behavior for certain steps
if (ITutorial.currStep === iTutorialSteps.GoToCharacterPage) {
document.getElementById("stats-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.CharacterGoToTerminalPage) {
document.getElementById("terminal-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.TerminalGoToActiveScriptsPage) {
document.getElementById("active-scripts-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.ActiveScriptsPage) {
document.getElementById("terminal-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.GoToHacknetNodesPage) {
document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.HacknetNodesGoToWorldPage) {
document.getElementById("city-menu-link").removeAttribute("class");
}
if (ITutorial.currStep === iTutorialSteps.WorldDescription) {
document.getElementById("tutorial-menu-link").removeAttribute("class");
}
ITutorial.stepIsDone[ITutorial.currStep] = true;
if (ITutorial.currStep < iTutorialSteps.End) {
ITutorial.currStep += 1;
}
iTutorialEvaluateStep();
}
// Go to previous step and evaluate
function iTutorialPrevStep() {
if (ITutorial.currStep > iTutorialSteps.Start) {
ITutorial.currStep -= 1;
}
iTutorialEvaluateStep();
}
function iTutorialEnd() {
// Re-enable auto save
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval === 0) {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity;
} else {
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = _Settings_Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval * 5;
}
// Initialize references to main menu links
// We have to call initializeMainMenuLinks() again because the Interactive Tutorial
// re-creates Main menu links with clearEventListeners()
if (!Object(_ui_MainMenu_Links__WEBPACK_IMPORTED_MODULE_3__["initializeMainMenuLinks"])()) {
const errorMsg = "Failed to initialize Main Menu Links. Please try refreshing the page. " +
"If that doesn't work, report the issue to the developer";
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_5__["exceptionAlert"])(new Error(errorMsg));
console.error(errorMsg);
return;
}
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].init();
ITutorial.currStep = iTutorialSteps.End;
ITutorial.isRunning = false;
document.getElementById("interactive-tutorial-container").style.display = "none";
// Create a popup with final introductory stuff
const popupId = "interactive-tutorial-ending-popup";
const txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("p", {
innerHTML:
"If you are new to the game, the following links may be useful for you!
" +
"The Beginner's Guide to Hacking was added to your home computer! It contains some tips/pointers for starting out with the game. " +
"To read it, go to Terminal and enter
cat " + _Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_4__["LiteratureNames"].HackersStartingHandbook,
});
const gotitBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_7__["createElement"])("a", {
class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_9__["removeElementById"])(popupId);
},
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, [txt, gotitBtn]);
_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().messages.push(_Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_4__["LiteratureNames"].HackersStartingHandbook);
}
let textBox = null;
(function() {
function set() {
textBox = document.getElementById("interactive-tutorial-text");
document.removeEventListener("DOMContentLoaded", set);
}
document.addEventListener("DOMContentLoaded", set);
})();
function iTutorialSetText(txt) {
textBox.innerHTML = txt;
textBox.parentElement.scrollTop = 0; // this resets scroll position
}
/***/ }),
/* 44 */
/*!***********************************!*\
!*** ./utils/helpers/keyCodes.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KEY = void 0;
/**
* Keyboard key codes
*/
exports.KEY = {
CTRL: 17,
DOWNARROW: 40,
ENTER: 13,
ESC: 27,
TAB: 9,
UPARROW: 38,
"0": 48,
"1": 49,
"2": 50,
"3": 51,
"4": 52,
"5": 53,
"6": 54,
"7": 55,
"8": 56,
"9": 57,
A: 65,
B: 66,
C: 67,
D: 68,
E: 69,
F: 70,
G: 71,
H: 72,
I: 73,
J: 74,
K: 75,
L: 76,
M: 77,
N: 78,
O: 79,
P: 80,
Q: 81,
R: 82,
S: 83,
T: 84,
U: 85,
V: 86,
W: 87,
X: 88,
Y: 89,
Z: 90,
};
/***/ }),
/* 45 */
/*!***************************************!*\
!*** ./utils/helpers/getRandomInt.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRandomInt = void 0;
/**
* 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;
/***/ }),
/* 46 */,
/* 47 */
/*!*****************************************!*\
!*** ./src/StockMarket/StockMarket.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.displayStockMarketContent = exports.processStockPrices = exports.stockMarketCycle = exports.initSymbolToStockMap = exports.initStockMarket = exports.deleteStockMarket = exports.loadStockMarket = exports.cancelOrder = exports.placeOrder = exports.SymbolToStockMap = exports.StockMarket = void 0;
const BuyingAndSelling_1 = __webpack_require__(/*! ./BuyingAndSelling */ 174);
const Order_1 = __webpack_require__(/*! ./Order */ 996);
const OrderProcessing_1 = __webpack_require__(/*! ./OrderProcessing */ 995);
const Stock_1 = __webpack_require__(/*! ./Stock */ 191);
const StockMarketConstants_1 = __webpack_require__(/*! ./StockMarketConstants */ 994);
const InitStockMetadata_1 = __webpack_require__(/*! ./data/InitStockMetadata */ 993);
const OrderTypes_1 = __webpack_require__(/*! ./data/OrderTypes */ 111);
const PositionTypes_1 = __webpack_require__(/*! ./data/PositionTypes */ 98);
const StockSymbols_1 = __webpack_require__(/*! ./data/StockSymbols */ 284);
const Root_1 = __webpack_require__(/*! ./ui/Root */ 992);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const EventEmitter_1 = __webpack_require__(/*! ../utils/EventEmitter */ 487);
const navigationTracking_1 = __webpack_require__(/*! .././ui/navigationTracking */ 18);
const numeralFormat_1 = __webpack_require__(/*! .././ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const React = __importStar(__webpack_require__(/*! react */ 0));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ 21));
exports.StockMarket = {}; // Maps full stock name -> Stock object
exports.SymbolToStockMap = {}; // Maps symbol -> Stock object
function placeOrder(stock, shares, price, type, position, workerScript = null) {
if (!(stock instanceof Stock_1.Stock)) {
if (workerScript) {
workerScript.log("placeOrder", `Invalid stock: '${stock}'`);
}
else {
DialogBox_1.dialogBoxCreate(`ERROR: Invalid stock passed to placeOrder() function`);
}
return false;
}
if (typeof shares !== "number" || typeof price !== "number") {
if (workerScript) {
workerScript.log("placeOrder", `Invalid arguments: shares='${shares}' price='${price}'`);
}
else {
DialogBox_1.dialogBoxCreate("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
}
return false;
}
const order = new Order_1.Order(stock.symbol, shares, price, type, position);
if (exports.StockMarket["Orders"] == null) {
const orders = {};
for (const name in exports.StockMarket) {
const stk = exports.StockMarket[name];
if (!(stk instanceof Stock_1.Stock)) {
continue;
}
orders[stk.symbol] = [];
}
exports.StockMarket["Orders"] = orders;
}
exports.StockMarket["Orders"][stock.symbol].push(order);
// Process to see if it should be executed immediately
const processOrderRefs = {
rerenderFn: displayStockMarketContent,
stockMarket: exports.StockMarket,
symbolToStockMap: exports.SymbolToStockMap,
};
OrderProcessing_1.processOrders(stock, order.type, order.pos, processOrderRefs);
displayStockMarketContent();
return true;
}
exports.placeOrder = placeOrder;
function cancelOrder(params, workerScript = null) {
if (exports.StockMarket["Orders"] == null) {
return false;
}
if (params.order && params.order instanceof Order_1.Order) {
const order = params.order;
// An 'Order' object is passed in
const stockOrders = exports.StockMarket["Orders"][order.stockSymbol];
for (let i = 0; i < stockOrders.length; ++i) {
if (order == stockOrders[i]) {
stockOrders.splice(i, 1);
displayStockMarketContent();
return true;
}
}
return false;
}
else if (params.stock && params.shares && params.price && params.type &&
params.pos && params.stock instanceof Stock_1.Stock) {
// Order properties are passed in. Need to look for the order
const stockOrders = exports.StockMarket["Orders"][params.stock.symbol];
const orderTxt = params.stock.symbol + " - " + params.shares + " @ " +
numeralFormat_1.numeralWrapper.formatMoney(params.price);
for (let i = 0; i < stockOrders.length; ++i) {
const order = stockOrders[i];
if (params.shares === order.shares &&
params.price === order.price &&
params.type === order.type &&
params.pos === order.pos) {
stockOrders.splice(i, 1);
displayStockMarketContent();
if (workerScript) {
workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt);
}
return true;
}
}
if (workerScript) {
workerScript.scriptRef.log("Failed to cancel order: " + orderTxt);
}
return false;
}
return false;
}
exports.cancelOrder = cancelOrder;
function loadStockMarket(saveString) {
if (saveString === "") {
exports.StockMarket = {};
}
else {
exports.StockMarket = JSON.parse(saveString, JSONReviver_1.Reviver);
}
}
exports.loadStockMarket = loadStockMarket;
function deleteStockMarket() {
exports.StockMarket = {};
}
exports.deleteStockMarket = deleteStockMarket;
function initStockMarket() {
for (const stk in exports.StockMarket) {
if (exports.StockMarket.hasOwnProperty(stk)) {
delete exports.StockMarket[stk];
}
}
for (const metadata of InitStockMetadata_1.InitStockMetadata) {
const name = metadata.name;
exports.StockMarket[name] = new Stock_1.Stock(metadata);
}
const orders = {};
for (const name in exports.StockMarket) {
const stock = exports.StockMarket[name];
if (!(stock instanceof Stock_1.Stock)) {
continue;
}
orders[stock.symbol] = [];
}
exports.StockMarket["Orders"] = orders;
exports.StockMarket.storedCycles = 0;
exports.StockMarket.lastUpdate = 0;
exports.StockMarket.ticksUntilCycle = StockMarketConstants_1.TicksPerCycle;
}
exports.initStockMarket = initStockMarket;
function initSymbolToStockMap() {
for (const name in StockSymbols_1.StockSymbols) {
if (StockSymbols_1.StockSymbols.hasOwnProperty(name)) {
const stock = exports.StockMarket[name];
if (stock == null) {
console.error(`Could not find Stock for ${name}`);
continue;
}
const symbol = StockSymbols_1.StockSymbols[name];
exports.SymbolToStockMap[symbol] = stock;
}
}
}
exports.initSymbolToStockMap = initSymbolToStockMap;
function stockMarketCycle() {
for (const name in exports.StockMarket) {
const stock = exports.StockMarket[name];
if (!(stock instanceof Stock_1.Stock)) {
continue;
}
const roll = Math.random();
if (roll < 0.45) {
stock.b = !stock.b;
stock.flipForecastForecast();
}
exports.StockMarket.ticksUntilCycle = StockMarketConstants_1.TicksPerCycle;
}
}
exports.stockMarketCycle = stockMarketCycle;
// Stock prices updated every 6 seconds
const msPerStockUpdate = 6e3;
const cyclesPerStockUpdate = msPerStockUpdate / Constants_1.CONSTANTS.MilliPerCycle;
function processStockPrices(numCycles = 1) {
if (exports.StockMarket.storedCycles == null || isNaN(exports.StockMarket.storedCycles)) {
exports.StockMarket.storedCycles = 0;
}
exports.StockMarket.storedCycles += numCycles;
if (exports.StockMarket.storedCycles < cyclesPerStockUpdate) {
return;
}
// We can process the update every 4 seconds as long as there are enough
// stored cycles. This lets us account for offline time
const timeNow = new Date().getTime();
if (timeNow - exports.StockMarket.lastUpdate < 4e3) {
return;
}
exports.StockMarket.lastUpdate = timeNow;
exports.StockMarket.storedCycles -= cyclesPerStockUpdate;
// Cycle
if (exports.StockMarket.ticksUntilCycle == null || typeof exports.StockMarket.ticksUntilCycle !== "number") {
exports.StockMarket.ticksUntilCycle = StockMarketConstants_1.TicksPerCycle;
}
--exports.StockMarket.ticksUntilCycle;
if (exports.StockMarket.ticksUntilCycle <= 0) {
stockMarketCycle();
}
const v = Math.random();
for (const name in exports.StockMarket) {
const stock = exports.StockMarket[name];
if (!(stock instanceof Stock_1.Stock)) {
continue;
}
let av = (v * stock.mv) / 100;
if (isNaN(av)) {
av = .02;
}
let chc = 50;
if (stock.b) {
chc = (chc + stock.otlkMag) / 100;
}
else {
chc = (chc - stock.otlkMag) / 100;
}
if (stock.price >= stock.cap) {
chc = 0.1; // "Soft Limit" on stock price. It could still go up but its unlikely
stock.b = false;
}
if (isNaN(chc)) {
chc = 0.5;
}
const c = Math.random();
const processOrderRefs = {
rerenderFn: displayStockMarketContent,
stockMarket: exports.StockMarket,
symbolToStockMap: exports.SymbolToStockMap,
};
if (c < chc) {
stock.changePrice(stock.price * (1 + av));
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.LimitBuy, PositionTypes_1.PositionTypes.Short, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.LimitSell, PositionTypes_1.PositionTypes.Long, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.StopBuy, PositionTypes_1.PositionTypes.Long, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.StopSell, PositionTypes_1.PositionTypes.Short, processOrderRefs);
}
else {
stock.changePrice(stock.price / (1 + av));
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.LimitBuy, PositionTypes_1.PositionTypes.Long, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.LimitSell, PositionTypes_1.PositionTypes.Short, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.StopBuy, PositionTypes_1.PositionTypes.Short, processOrderRefs);
OrderProcessing_1.processOrders(stock, OrderTypes_1.OrderTypes.StopSell, PositionTypes_1.PositionTypes.Long, processOrderRefs);
}
let otlkMagChange = stock.otlkMag * av;
if (stock.otlkMag < 5) {
if (stock.otlkMag <= 1) {
otlkMagChange = 1;
}
else {
otlkMagChange *= 10;
}
}
stock.cycleForecast(otlkMagChange);
stock.cycleForecastForecast(otlkMagChange / 2);
// Shares required for price movement gradually approaches max over time
stock.shareTxUntilMovement = Math.min(stock.shareTxUntilMovement + 10, stock.shareTxForMovement);
}
displayStockMarketContent();
}
exports.processStockPrices = processStockPrices;
let stockMarketContainer = null;
function setStockMarketContainer() {
stockMarketContainer = document.getElementById("stock-market-container");
document.removeEventListener("DOMContentLoaded", setStockMarketContainer);
}
document.addEventListener("DOMContentLoaded", setStockMarketContainer);
function initStockMarketFnForReact() {
initStockMarket();
initSymbolToStockMap();
}
const eventEmitterForUiReset = new EventEmitter_1.EventEmitter();
function displayStockMarketContent() {
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.StockMarket)) {
return;
}
eventEmitterForUiReset.emitEvent();
if (stockMarketContainer instanceof HTMLElement) {
const castedStockMarket = exports.StockMarket;
ReactDOM.render(React.createElement(Root_1.StockMarketRoot, { buyStockLong: BuyingAndSelling_1.buyStock, buyStockShort: BuyingAndSelling_1.shortStock, cancelOrder: cancelOrder, eventEmitterForReset: eventEmitterForUiReset, initStockMarket: initStockMarketFnForReact, p: Player_1.Player, placeOrder: placeOrder, sellStockLong: BuyingAndSelling_1.sellStock, sellStockShort: BuyingAndSelling_1.sellShort, stockMarket: castedStockMarket }), stockMarketContainer);
}
}
exports.displayStockMarketContent = displayStockMarketContent;
/***/ }),
/* 48 */,
/* 49 */
/*!************************************************!*\
!*** ./utils/uiHelpers/clearEventListeners.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearEventListeners = void 0;
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 190);
/**
* Given an element by its ID, removes all event listeners from that element by cloning and
* replacing. Then returns the new cloned element.
* @param elemId The HTML ID to retrieve the element by.
*/
function clearEventListeners(elemId) {
try {
let elem;
if (typeof elemId === "string") {
elem = getElementById_1.getElementById(elemId);
}
else {
elem = elemId;
}
const newElem = elem.cloneNode(true);
if (elem.parentNode !== null) {
elem.parentNode.replaceChild(newElem, elem);
}
return newElem;
}
catch (e) {
// tslint:disable-next-line:no-console
console.error(e);
return null;
}
}
exports.clearEventListeners = clearEventListeners;
/***/ }),
/* 50 */
/*!************************!*\
!*** ./src/Hacking.ts ***!
\************************/
/*! no static exports found */
/*! exports used: calculateGrowTime, calculateHackingChance, calculateHackingExpGain, calculateHackingTime, calculatePercentMoneyHacked, calculateWeakenTime */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateWeakenTime = exports.calculateGrowTime = exports.calculateHackingTime = exports.calculatePercentMoneyHacked = exports.calculateHackingExpGain = exports.calculateHackingChance = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 19);
const intelligence_1 = __webpack_require__(/*! ./PersonObjects/formulas/intelligence */ 411);
/**
* Returns the chance the player has to successfully hack a server
*/
function calculateHackingChance(server, player) {
const hackFactor = 1.75;
const difficultyMult = (100 - server.hackDifficulty) / 100;
const skillMult = hackFactor * player.hacking_skill;
const skillChance = (skillMult - server.requiredHackingSkill) / skillMult;
const chance = skillChance * difficultyMult * player.hacking_chance_mult * intelligence_1.calculateIntelligenceBonus(player.intelligence, 1);
if (chance > 1) {
return 1;
}
if (chance < 0) {
return 0;
}
return chance;
}
exports.calculateHackingChance = calculateHackingChance;
/**
* Returns the amount of hacking experience the player will gain upon
* successfully hacking a server
*/
function calculateHackingExpGain(server, player) {
const baseExpGain = 3;
const diffFactor = 0.3;
if (server.baseDifficulty == null) {
server.baseDifficulty = server.hackDifficulty;
}
let expGain = baseExpGain;
expGain += (server.baseDifficulty * player.hacking_exp_mult * diffFactor);
return expGain * BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain;
}
exports.calculateHackingExpGain = calculateHackingExpGain;
/**
* 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, player) {
// 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.hacking_skill - (server.requiredHackingSkill - 1)) / player.hacking_skill;
const percentMoneyHacked = difficultyMult * skillMult * player.hacking_money_mult / balanceFactor;
if (percentMoneyHacked < 0) {
return 0;
}
if (percentMoneyHacked > 1) {
return 1;
}
return percentMoneyHacked * BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney;
}
exports.calculatePercentMoneyHacked = calculatePercentMoneyHacked;
/**
* Returns time it takes to complete a hack on a server, in seconds
*/
function calculateHackingTime(server, player) {
const difficultyMult = server.requiredHackingSkill * server.hackDifficulty;
const baseDiff = 500;
const baseSkill = 50;
const diffFactor = 2.5;
let skillFactor = (diffFactor * difficultyMult + baseDiff);
// tslint:disable-next-line
skillFactor /= (player.hacking_skill + baseSkill);
const hackTimeMultiplier = 5;
const hackingTime = hackTimeMultiplier * skillFactor / (player.hacking_speed_mult * intelligence_1.calculateIntelligenceBonus(player.intelligence, 1));
return hackingTime;
}
exports.calculateHackingTime = calculateHackingTime;
/**
* Returns time it takes to complete a grow operation on a server, in seconds
*/
function calculateGrowTime(server, player) {
const growTimeMultiplier = 3.2; // Relative to hacking time. 16/5 = 3.2
return growTimeMultiplier * calculateHackingTime(server, player);
}
exports.calculateGrowTime = calculateGrowTime;
/**
* Returns time it takes to complete a weaken operation on a server, in seconds
*/
function calculateWeakenTime(server, player) {
const weakenTimeMultiplier = 4; // Relative to hacking time
return weakenTimeMultiplier * calculateHackingTime(server, player);
}
exports.calculateWeakenTime = calculateWeakenTime;
/***/ }),
/* 51 */
/*!******************************************!*\
!*** ./utils/uiHelpers/createElement.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createElement = void 0;
function setElementAnchor(el, params) {
if (params.text !== undefined) {
el.text = params.text;
}
if (params.href !== undefined) {
el.href = params.href;
}
if (params.target !== undefined) {
el.target = params.target;
}
}
function setElementInput(el, params) {
if (params.name !== undefined) {
el.name = params.name;
}
if (params.value !== undefined) {
el.value = params.value;
}
if (params.type !== undefined) {
el.type = params.type;
}
if (params.checked !== undefined) {
el.checked = params.checked;
}
if (params.pattern !== undefined) {
el.pattern = params.pattern;
}
if (params.maxLength !== undefined) {
el.maxLength = params.maxLength;
}
if (params.placeholder !== undefined) {
el.placeholder = params.placeholder;
}
if (params.max !== undefined) {
el.max = params.max;
}
if (params.min !== undefined) {
el.min = params.min;
}
if (params.step !== undefined) {
el.step = params.step;
}
}
function setElementLabel(el, params) {
if (params.for !== undefined) {
el.htmlFor = params.for;
}
}
function setElementListeners(el, params) {
// tslint:disable:no-unbound-method
if (params.clickListener !== undefined) {
el.addEventListener("click", params.clickListener);
}
if (params.inputListener !== undefined) {
el.addEventListener("input", params.inputListener);
}
if (params.changeListener !== undefined) {
el.addEventListener("change", params.changeListener);
}
if (params.onkeyup !== undefined) {
el.addEventListener("keyup", params.onkeyup);
}
if (params.onkeydown !== undefined) {
el.addEventListener("keydown", params.onkeydown);
}
if (params.onfocus !== undefined) {
el.addEventListener("focus", params.onfocus);
}
// tslint:enable:no-unbound-method
}
function setElementStyle(el, params) {
if (params.display !== undefined) {
el.style.display = params.display;
}
if (params.visibility !== undefined) {
el.style.visibility = params.visibility;
}
if (params.margin !== undefined) {
el.style.margin = params.margin;
}
if (params.marginLeft !== undefined) {
el.style.marginLeft = params.marginLeft;
}
if (params.marginTop !== undefined) {
el.style.marginTop = params.marginTop;
}
if (params.padding !== undefined) {
el.style.padding = params.padding;
}
if (params.color !== undefined) {
el.style.color = params.color;
}
if (params.border !== undefined) {
el.style.border = params.border;
}
if (params.float !== undefined) {
el.style.cssFloat = params.float;
}
if (params.fontSize !== undefined) {
el.style.fontSize = params.fontSize;
}
if (params.whiteSpace !== undefined) {
el.style.whiteSpace = params.whiteSpace;
}
if (params.width !== undefined) {
el.style.width = params.width;
}
if (params.height !== undefined) {
el.style.height = params.height;
}
if (params.top !== undefined) {
el.style.top = params.top;
}
if (params.left !== undefined) {
el.style.left = params.left;
}
if (params.backgroundColor !== undefined) {
el.style.backgroundColor = params.backgroundColor;
}
if (params.position !== undefined) {
el.style.position = params.position;
}
if (params.overflow !== undefined) {
el.style.overflow = params.overflow;
}
}
function setElementTooltip(el, params) {
if (params.tooltip !== undefined && params.tooltip !== "") {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptext",
innerHTML: params.tooltip,
}));
}
else if (params.tooltipleft !== undefined) {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptextleft",
innerHTML: params.tooltipleft,
}));
}
else if (params.tooltipsmall !== undefined) {
el.className += " tooltip";
el.appendChild(createElement("span", {
class: "tooltiptext smallfont",
innerHTML: params.tooltipsmall,
}));
}
else if (params.tooltiplow !== undefined) {
el.className += "tooltip";
el.appendChild(createElement("span", {
class: "tooltiptextlow",
innerHTML: params.tooltiplow,
}));
}
}
/**
* An all-in-one-call way of creating an element to be added to the DOM at some point.
* @param tagName The HTML tag/element name
* @param params Additional parameters to set on the element
*/
function createElement(tagName, params = {}) {
const el = document.createElement(tagName);
if (params.id !== undefined) {
el.id = params.id;
}
if (params.class !== undefined) {
el.className = params.class;
}
if (params.innerHTML !== undefined) {
el.innerHTML = params.innerHTML;
}
if (params.innerText !== undefined) {
el.innerText = params.innerText;
}
if (params.tabIndex !== undefined) {
el.tabIndex = params.tabIndex;
}
setElementAnchor(el, params);
setElementInput(el, params);
setElementLabel(el, params);
setElementListeners(el, params);
setElementStyle(el, params);
setElementTooltip(el, params);
return el;
}
exports.createElement = createElement;
/***/ }),
/* 52 */
/*!*****************************************!*\
!*** ./src/Company/CompanyPositions.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompanyPositions = void 0;
// Constructs all CompanyPosition objects using the metadata in data/companypositions.ts
const CompanyPositionsMetadata_1 = __webpack_require__(/*! ./data/CompanyPositionsMetadata */ 1069);
const CompanyPosition_1 = __webpack_require__(/*! ./CompanyPosition */ 286);
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);
});
/***/ }),
/* 53 */,
/* 54 */,
/* 55 */,
/* 56 */
/*!************************************!*\
!*** ./src/ui/React/StdButton.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StdButton = void 0;
/**
* Basic stateless button
* Uses the 'std-button' css class
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
function StdButton(props) {
const hasTooltip = props.tooltip != null && props.tooltip !== "";
let className = props.disabled ? "std-button-disabled" : "std-button";
if (hasTooltip) {
className += " tooltip";
}
if (typeof props.addClasses === "string") {
className += ` ${props.addClasses}`;
}
// Tooltip will be set using inner HTML
let tooltip;
if (hasTooltip) {
if (typeof props.tooltip === 'string') {
const tooltipMarkup = {
__html: props.tooltip,
};
tooltip = React.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: tooltipMarkup });
}
else {
tooltip = React.createElement("span", { className: "tooltiptext" }, props.tooltip);
}
}
return (React.createElement("button", { className: className, id: props.id, onClick: props.onClick, style: props.style },
props.text,
hasTooltip &&
tooltip));
}
exports.StdButton = StdButton;
/***/ }),
/* 57 */,
/* 58 */
/*!**************************************************!*\
!*** ./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.PartTimeCompanyPositions = exports.BusinessConsultantCompanyPositions = exports.SoftwareConsultantCompanyPositions = exports.MiscCompanyPositions = exports.AgentCompanyPositions = exports.SecurityCompanyPositions = exports.BusinessCompanyPositions = exports.NetworkEngineerCompanyPositions = exports.SecurityEngineerCompanyPositions = exports.ITCompanyPositions = exports.SoftwareCompanyPositions = void 0;
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",
];
/***/ }),
/* 59 */
/*!*************************************!*\
!*** ./src/ui/React/Reputation.tsx ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Reputation = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function Reputation(reputation) {
return React.createElement("span", { className: "reputation samefont" }, typeof reputation === 'number' ? numeralFormat_1.numeralWrapper.formatReputation(reputation) : reputation);
}
exports.Reputation = Reputation;
/***/ }),
/* 60 */,
/* 61 */
/*!***************************!*\
!*** ./utils/YesNoBox.ts ***!
\***************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.yesNoTxtInpBoxCreate = exports.yesNoTxtInpBoxGetInput = exports.yesNoTxtInpBoxGetNoButton = exports.yesNoTxtInpBoxGetYesButton = exports.yesNoTxtInpBoxClose = exports.yesNoTxtInpBoxHotkeyHandler = exports.yesNoBoxCreate = exports.yesNoBoxGetNoButton = exports.yesNoBoxGetYesButton = exports.yesNoBoxClose = exports.yesNoBoxOpen = void 0;
/**
* Generic Yes-No Pop-up box
* Used to create pop-up boxes that require a yes/no response from player
*
* There are two types of pop ups:
* 1. Just a Yes/No response from player
* 2. Popup also includes a text input field in addition to the Yes/No response
*/
const clearEventListeners_1 = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 49);
const keyCodes_1 = __webpack_require__(/*! ./helpers/keyCodes */ 44);
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ 21));
exports.yesNoBoxOpen = false;
const yesNoBoxContainer = document.getElementById("yes-no-box-container");
const yesNoBoxTextElement = document.getElementById("yes-no-box-text");
function yesNoBoxHotkeyHandler(e) {
if (e.keyCode === keyCodes_1.KEY.ESC) {
yesNoBoxClose();
}
else if (e.keyCode === keyCodes_1.KEY.ENTER) {
const yesBtn = document.getElementById("yes-no-box-yes");
if (yesBtn) {
yesBtn.click();
}
else {
console.error(`Could not find YesNoBox Yes button DOM element`);
}
}
}
function yesNoBoxClose() {
if (yesNoBoxContainer) {
yesNoBoxContainer.style.display = "none";
}
else {
console.error("Container not found for YesNoBox");
}
exports.yesNoBoxOpen = false;
// Remove hotkey handler
document.removeEventListener("keydown", yesNoBoxHotkeyHandler);
return false; //So that 'return yesNoBoxClose()' is return false in event listeners
}
exports.yesNoBoxClose = yesNoBoxClose;
function yesNoBoxGetYesButton() {
return clearEventListeners_1.clearEventListeners("yes-no-box-yes");
}
exports.yesNoBoxGetYesButton = yesNoBoxGetYesButton;
function yesNoBoxGetNoButton() {
return clearEventListeners_1.clearEventListeners("yes-no-box-no");
}
exports.yesNoBoxGetNoButton = yesNoBoxGetNoButton;
function yesNoBoxCreate(txt) {
if (exports.yesNoBoxOpen) {
return false;
} //Already open
exports.yesNoBoxOpen = true;
if (yesNoBoxTextElement) {
ReactDOM.unmountComponentAtNode(yesNoBoxTextElement);
yesNoBoxTextElement.innerHTML = '';
if (typeof txt === 'string') {
yesNoBoxTextElement.innerHTML = txt;
}
else {
ReactDOM.render(txt, yesNoBoxTextElement);
}
}
else {
console.error(`Text element not found for YesNoBox`);
}
if (yesNoBoxContainer) {
yesNoBoxContainer.style.display = "flex";
}
else {
console.error("Container not found for YesNoBox");
}
// Add event listener for Esc and Enter hotkeys
document.addEventListener("keydown", yesNoBoxHotkeyHandler);
return true;
}
exports.yesNoBoxCreate = yesNoBoxCreate;
/**
* Yes-No pop up box with text input field
*/
const yesNoTextInputBoxContainer = document.getElementById("yes-no-text-input-box-container");
const yesNoTextInputBoxInput = document.getElementById("yes-no-text-input-box-input");
const yesNoTextInputBoxTextElement = document.getElementById("yes-no-text-input-box-text");
function yesNoTxtInpBoxHotkeyHandler(e) {
if (e.keyCode === keyCodes_1.KEY.ESC) {
yesNoTxtInpBoxClose();
}
else if (e.keyCode === keyCodes_1.KEY.ENTER) {
const yesBtn = document.getElementById("yes-no-text-input-box-yes");
if (yesBtn) {
yesBtn.click();
}
else {
console.error(`Could not find YesNoTxtInputBox Yes button DOM element`);
}
}
}
exports.yesNoTxtInpBoxHotkeyHandler = yesNoTxtInpBoxHotkeyHandler;
function yesNoTxtInpBoxClose() {
if (yesNoTextInputBoxContainer != null) {
yesNoTextInputBoxContainer.style.display = "none";
}
else {
console.error("Container not found for YesNoTextInputBox");
return false;
}
if (!yesNoTextInputBoxInput)
throw new Error("yesNoTextInputBoxInput was not set");
exports.yesNoBoxOpen = false;
yesNoTextInputBoxInput.value = "";
// Remove hotkey handler
document.removeEventListener("keydown", yesNoTxtInpBoxHotkeyHandler);
return false;
}
exports.yesNoTxtInpBoxClose = yesNoTxtInpBoxClose;
function yesNoTxtInpBoxGetYesButton() {
const elem = clearEventListeners_1.clearEventListeners("yes-no-text-input-box-yes");
if (elem === null)
throw new Error("Could not find element with id: 'yes-no-text-input-box-yes'");
return elem;
}
exports.yesNoTxtInpBoxGetYesButton = yesNoTxtInpBoxGetYesButton;
function yesNoTxtInpBoxGetNoButton() {
const elem = clearEventListeners_1.clearEventListeners("yes-no-text-input-box-no");
if (elem === null)
throw new Error("Could not find element with id: 'yes-no-text-input-box-no'");
return elem;
}
exports.yesNoTxtInpBoxGetNoButton = yesNoTxtInpBoxGetNoButton;
function yesNoTxtInpBoxGetInput() {
if (!yesNoTextInputBoxInput) {
console.error("Could not find YesNoTextInputBox input element");
return "";
}
let val = yesNoTextInputBoxInput.value;
val = val.replace(/\s+/g, '');
return val;
}
exports.yesNoTxtInpBoxGetInput = yesNoTxtInpBoxGetInput;
function yesNoTxtInpBoxCreate(txt) {
exports.yesNoBoxOpen = true;
if (yesNoTextInputBoxTextElement) {
ReactDOM.unmountComponentAtNode(yesNoTextInputBoxTextElement);
yesNoTextInputBoxTextElement.innerHTML = '';
if (typeof txt === 'string') {
yesNoTextInputBoxTextElement.innerHTML = txt;
}
else {
ReactDOM.render(txt, yesNoTextInputBoxTextElement);
}
}
if (yesNoTextInputBoxContainer) {
yesNoTextInputBoxContainer.style.display = "flex";
}
else {
console.error("Container not found for YesNoTextInputBox");
}
// Add event listener for Esc and Enter hotkeys
document.addEventListener("keydown", yesNoTxtInpBoxHotkeyHandler);
if (!yesNoTextInputBoxInput)
throw new Error("yesNoTextInputBoxInput was not set");
yesNoTextInputBoxInput.focus();
}
exports.yesNoTxtInpBoxCreate = yesNoTxtInpBoxCreate;
/***/ }),
/* 62 */,
/* 63 */,
/* 64 */,
/* 65 */,
/* 66 */
/*!***************************************!*\
!*** ./src/Script/ScriptHelpersTS.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isScriptFilename = void 0;
// Script helper functions
function isScriptFilename(f) {
return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns");
}
exports.isScriptFilename = isScriptFilename;
/***/ }),
/* 67 */
/*!**********************!*\
!*** ./src/Alias.ts ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.substituteAliases = exports.removeAlias = exports.parseAliasDeclaration = exports.printAliases = exports.loadGlobalAliases = exports.loadAliases = exports.GlobalAliases = exports.Aliases = void 0;
const postToTerminal_1 = __webpack_require__(/*! ./ui/postToTerminal */ 8);
exports.Aliases = {};
exports.GlobalAliases = {};
function loadAliases(saveString) {
if (saveString === "") {
exports.Aliases = {};
}
else {
exports.Aliases = JSON.parse(saveString);
}
}
exports.loadAliases = loadAliases;
function loadGlobalAliases(saveString) {
if (saveString === "") {
exports.GlobalAliases = {};
}
else {
exports.GlobalAliases = JSON.parse(saveString);
}
}
exports.loadGlobalAliases = loadGlobalAliases;
// Prints all aliases to terminal
function printAliases() {
for (const name in exports.Aliases) {
if (exports.Aliases.hasOwnProperty(name)) {
postToTerminal_1.post("alias " + name + "=" + exports.Aliases[name]);
}
}
for (const name in exports.GlobalAliases) {
if (exports.GlobalAliases.hasOwnProperty(name)) {
postToTerminal_1.post("global alias " + name + "=" + exports.GlobalAliases[name]);
}
}
}
exports.printAliases = printAliases;
// Returns true if successful, false otherwise
function parseAliasDeclaration(dec, global = false) {
const re = /^([_|\w|!|%|,|@]+)="(.+)"$/;
const matches = dec.match(re);
if (matches == null || matches.length != 3) {
return false;
}
if (global) {
addGlobalAlias(matches[1], matches[2]);
}
else {
addAlias(matches[1], matches[2]);
}
return true;
}
exports.parseAliasDeclaration = parseAliasDeclaration;
function addAlias(name, value) {
if (name in exports.GlobalAliases) {
delete exports.GlobalAliases[name];
}
exports.Aliases[name] = value.trim();
}
function addGlobalAlias(name, value) {
if (name in exports.Aliases) {
delete exports.Aliases[name];
}
exports.GlobalAliases[name] = value.trim();
}
function getAlias(name) {
if (exports.Aliases.hasOwnProperty(name)) {
return exports.Aliases[name];
}
return null;
}
function getGlobalAlias(name) {
if (exports.GlobalAliases.hasOwnProperty(name)) {
return exports.GlobalAliases[name];
}
return null;
}
function removeAlias(name) {
if (exports.Aliases.hasOwnProperty(name)) {
delete exports.Aliases[name];
return true;
}
if (exports.GlobalAliases.hasOwnProperty(name)) {
delete exports.GlobalAliases[name];
return true;
}
return false;
}
exports.removeAlias = removeAlias;
/**
* Returns the original string with any aliases substituted in.
* Aliases are only applied to "whole words", one level deep
*/
function substituteAliases(origCommand) {
var _a, _b;
const commandArray = origCommand.split(" ");
if (commandArray.length > 0) {
// For the alias and unalias commands, dont substite
if (commandArray[0] === "unalias" || commandArray[0] === "alias") {
return commandArray.join(" ");
}
let somethingSubstituted = true;
let depth = 0;
while (somethingSubstituted && depth < 10) {
depth++;
somethingSubstituted = false;
const alias = (_a = getAlias(commandArray[0])) === null || _a === void 0 ? void 0 : _a.split(" ");
if (alias != null) {
somethingSubstituted = true;
commandArray.splice(0, 1, ...alias);
//commandArray[0] = alias;
}
for (let i = 0; i < commandArray.length; ++i) {
const alias = (_b = getGlobalAlias(commandArray[i])) === null || _b === void 0 ? void 0 : _b.split(" ");
if (alias != null) {
somethingSubstituted = true;
commandArray.splice(i, 1, ...alias);
i += alias.length - 1;
//commandArray[i] = alias;
}
}
}
}
return commandArray.join(" ");
}
exports.substituteAliases = substituteAliases;
/***/ }),
/* 68 */
/*!***********************************!*\
!*** ./src/NetscriptEvaluator.js ***!
\***********************************/
/*! exports provided: netscriptDelay, makeRuntimeRejectMsg, resolveNetscriptRequestedThreads, getErrorLineNumber, isScriptErrorMessage */
/*! exports used: isScriptErrorMessage, makeRuntimeRejectMsg, netscriptDelay, resolveNetscriptRequestedThreads */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return netscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return makeRuntimeRejectMsg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return resolveNetscriptRequestedThreads; });
/* unused harmony export getErrorLineNumber */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isScriptErrorMessage; });
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/helpers/isString */ 72);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_2__);
function netscriptDelay(time, workerScript) {
return new Promise(function(resolve) {
workerScript.delay = Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_0__["setTimeoutRef"])(() => {
workerScript.delay = null;
resolve();
}, time);
workerScript.delayResolve = resolve;
});
}
function makeRuntimeRejectMsg(workerScript, msg, exp=null) {
var lineNum = "";
if (exp != null) {
var num = getErrorLineNumber(exp, workerScript);
lineNum = " (Line " + num + ")"
}
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_2__["AllServers"][workerScript.serverIp];
if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${this.serverIp}`);
}
return "|"+server.hostname+"|"+workerScript.name+"|" + msg + lineNum;
}
function resolveNetscriptRequestedThreads(workerScript, functionName, requestedThreads) {
const threads = workerScript.scriptRef.threads;
if (!requestedThreads) {
return (isNaN(threads) || threads < 1) ? 1 : threads;
}
const requestedThreadsAsInt = requestedThreads|0;
if (isNaN(requestedThreads) || requestedThreadsAsInt < 1) {
throw makeRuntimeRejectMsg(workerScript, `Invalid thread count passed to ${functionName}: ${requestedThreads}. Threads must be a positive number.`);
}
if (requestedThreads > threads) {
throw makeRuntimeRejectMsg(workerScript, `Too many threads requested by ${functionName}. Requested: ${requestedThreads}. Has: ${threads}.`);
}
return requestedThreadsAsInt;
}
function getErrorLineNumber(exp, workerScript) {
var code = workerScript.scriptRef.codeCode();
//Split code up to the start of the node
try {
code = code.substring(0, exp.start);
return (code.match(/\n/g) || []).length + 1;
} catch(e) {
return -1;
}
}
function isScriptErrorMessage(msg) {
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_1__["isString"])(msg)) {return false;}
let splitMsg = msg.split("|");
if (splitMsg.length != 4){
return false;
}
return true;
}
/***/ }),
/* 69 */,
/* 70 */
/*!*******************************************!*\
!*** ./src/Netscript/killWorkerScript.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.killWorkerScript = void 0;
/**
* Stops an actively-running script (represented by a WorkerScript object)
* and removes it from the global pool of active scripts.
*/
const WorkerScript_1 = __webpack_require__(/*! ./WorkerScript */ 247);
const WorkerScripts_1 = __webpack_require__(/*! ./WorkerScripts */ 112);
const WorkerScriptStartStopEventEmitter_1 = __webpack_require__(/*! ./WorkerScriptStartStopEventEmitter */ 147);
const RunningScript_1 = __webpack_require__(/*! ../Script/RunningScript */ 194);
const AllServers_1 = __webpack_require__(/*! ../Server/AllServers */ 20);
const compareArrays_1 = __webpack_require__(/*! ../../utils/helpers/compareArrays */ 195);
const roundToTwo_1 = __webpack_require__(/*! ../../utils/helpers/roundToTwo */ 290);
function killWorkerScript(script, serverIp, rerenderUi) {
if (rerenderUi == null || typeof rerenderUi !== "boolean") {
rerenderUi = true;
}
if (script instanceof WorkerScript_1.WorkerScript) {
stopAndCleanUpWorkerScript(script);
return true;
}
else if (script instanceof RunningScript_1.RunningScript && typeof serverIp === "string") {
// Try to kill by PID
const res = killWorkerScriptByPid(script.pid, rerenderUi);
if (res) {
return res;
}
// If for some reason that doesn't work, we'll try the old way
for (const ws of WorkerScripts_1.workerScripts.values()) {
if (ws.name == script.filename && ws.serverIp == serverIp &&
compareArrays_1.compareArrays(ws.args, script.args)) {
stopAndCleanUpWorkerScript(ws, rerenderUi);
return true;
}
}
return false;
}
else if (typeof script === "number") {
return killWorkerScriptByPid(script, rerenderUi);
}
else {
console.error(`killWorkerScript() called with invalid argument:`);
console.error(script);
return false;
}
}
exports.killWorkerScript = killWorkerScript;
function killWorkerScriptByPid(pid, rerenderUi = true) {
const ws = WorkerScripts_1.workerScripts.get(pid);
if (ws instanceof WorkerScript_1.WorkerScript) {
stopAndCleanUpWorkerScript(ws, rerenderUi);
return true;
}
return false;
}
function stopAndCleanUpWorkerScript(workerScript, rerenderUi = true) {
workerScript.env.stopFlag = true;
killNetscriptDelay(workerScript);
removeWorkerScript(workerScript, rerenderUi);
}
/**
* Helper function that removes the script being killed from the global pool.
* Also handles other cleanup-time operations
*
* @param {WorkerScript | number} - Identifier for WorkerScript. Either the object itself, or
* its index in the global workerScripts array
*/
function removeWorkerScript(workerScript, rerenderUi = true) {
if (workerScript instanceof WorkerScript_1.WorkerScript) {
const ip = workerScript.serverIp;
const name = workerScript.name;
// Get the server on which the script runs
const server = AllServers_1.AllServers[ip];
if (server == null) {
console.error(`Could not find server on which this script is running: ${ip}`);
return;
}
// Recalculate ram used on that server
server.ramUsed = roundToTwo_1.roundToTwo(server.ramUsed - workerScript.ramUsage);
if (server.ramUsed < 0) {
console.warn(`Server (${server.hostname}) RAM usage went negative (if it's due to floating pt imprecision, it's okay): ${server.ramUsed}`);
server.ramUsed = 0;
}
// Delete the RunningScript object from that server
for (let i = 0; i < server.runningScripts.length; ++i) {
const runningScript = server.runningScripts[i];
if (runningScript.filename === name && compareArrays_1.compareArrays(runningScript.args, workerScript.args)) {
server.runningScripts.splice(i, 1);
break;
}
}
// Delete script from global pool (workerScripts)
const res = WorkerScripts_1.workerScripts.delete(workerScript.pid);
if (!res) {
console.warn(`removeWorkerScript() called with WorkerScript that wasn't in the global map:`);
console.warn(workerScript);
}
if (rerenderUi) {
WorkerScriptStartStopEventEmitter_1.WorkerScriptStartStopEventEmitter.emitEvent();
}
}
else {
console.error(`Invalid argument passed into removeWorkerScript():`);
console.error(workerScript);
return;
}
}
/**
* Helper function that interrupts a script's delay if it is in the middle of a
* timed, blocked operation (like hack(), sleep(), etc.). This allows scripts to
* be killed immediately even if they're in the middle of one of those long operations
*/
function killNetscriptDelay(workerScript) {
if (workerScript instanceof WorkerScript_1.WorkerScript) {
if (workerScript.delay) {
clearTimeout(workerScript.delay);
if (workerScript.delayResolve) {
workerScript.delayResolve();
}
}
}
}
/***/ }),
/* 71 */
/*!****************************************!*\
!*** ./src/Faction/FactionHelpers.jsx ***!
\****************************************/
/*! exports provided: inviteToFaction, joinFaction, startHackingMission, displayFactionContent, purchaseAugmentationBoxCreate, hasAugmentationPrereqs, purchaseAugmentation, getNextNeurofluxLevel, processPassiveFactionRepGain */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inviteToFaction", function() { return inviteToFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinFaction", function() { return joinFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startHackingMission", function() { return startHackingMission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayFactionContent", function() { return displayFactionContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentationBoxCreate", function() { return purchaseAugmentationBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAugmentationPrereqs", function() { return hasAugmentationPrereqs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentation", function() { return purchaseAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextNeurofluxLevel", function() { return getNextNeurofluxLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processPassiveFactionRepGain", function() { return processPassiveFactionRepGain; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ui/Root */ 791);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_ui_Root__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Augmentation/AugmentationHelpers */ 79);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Augmentation/PlayerOwnedAugmentation */ 196);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../engine */ 15);
/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Faction */ 125);
/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Faction__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Factions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Factions */ 17);
/* harmony import */ var _Factions__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Factions__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Missions */ 81);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../PersonObjects/formulas/reputation */ 109);
/* harmony import */ var _PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../utils/FactionInvitationBox */ 790);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../utils/YesNoBox */ 61);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__);
function inviteToFaction(faction) {
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].SuppressFactionInvites) {
faction.alreadyInvited = true;
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factionInvitations.push(faction.name);
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_17__["Page"].Factions)) {
_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].loadFactionsContent();
}
} else {
Object(_utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_19__[/* factionInvitationBoxCreate */ "a"])(faction);
}
}
function joinFaction(faction) {
if (faction.isMember) return;
faction.isMember = true;
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factions.push(faction.name);
const factionInfo = faction.getInfo(); //Determine what factions you are banned from now that you have joined this faction
for (const i in factionInfo.enemies) {
const enemy = factionInfo.enemies[i];
if (_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][enemy] instanceof _Faction__WEBPACK_IMPORTED_MODULE_10__["Faction"]) {
_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][enemy].isBanned = true;
}
}
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factionInvitations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factionInvitations[i] == faction.name || _Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factionInvitations[i]].isBanned) {
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].factionInvitations.splice(i, 1);
i--;
}
}
}
function startHackingMission(faction) {
const mission = new _Missions__WEBPACK_IMPORTED_MODULE_12__[/* HackingMission */ "a"](faction.playerReputation, faction);
Object(_Missions__WEBPACK_IMPORTED_MODULE_12__[/* setInMission */ "d"])(true, mission); //Sets inMission flag to true
mission.init();
} //Displays the HTML content for a specific faction
function displayFactionContent(factionName, initiallyOnAugmentationsPage = false) {
const faction = _Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][factionName];
if (faction == null) {
throw new Error(`Invalid factionName passed into displayFactionContent(): ${factionName}`);
}
if (!faction.isMember) {
throw new Error(`Not a member of this faction. Cannot display faction information`);
}
react_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_2__["FactionRoot"], {
engine: _engine__WEBPACK_IMPORTED_MODULE_9__["Engine"],
initiallyOnAugmentationsPage: initiallyOnAugmentationsPage,
faction: faction,
p: _Player__WEBPACK_IMPORTED_MODULE_13__["Player"],
startHackingMissionFn: startHackingMission
}), _engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].Display.factionContent);
}
function purchaseAugmentationBoxCreate(aug, fac) {
const factionInfo = fac.getInfo();
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__["yesNoBoxGetYesButton"])();
yesBtn.innerHTML = "Purchase";
yesBtn.addEventListener("click", function () {
if (!Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_4__[/* isRepeatableAug */ "f"])(aug) && _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasAugmentation(aug)) {
return;
}
purchaseAugmentation(aug, fac);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__["yesNoBoxClose"])();
});
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__["yesNoBoxGetNoButton"])();
noBtn.innerHTML = "Cancel";
noBtn.addEventListener("click", function () {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__["yesNoBoxClose"])();
});
let content = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
dangerouslySetInnerHTML: {
__html: aug.info
}
});
if (typeof aug.info !== 'string') {
content = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, aug.info);
}
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_21__["yesNoBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", null, aug.name), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), content, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), "Would you like to purchase the ", aug.name, " Augmentation for\xA0", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_20__["Money"])(aug.baseCost * factionInfo.augmentationPriceMult), "?"));
} //Returns a boolean indicating whether the player has the prerequisites for the
//specified Augmentation
function hasAugmentationPrereqs(aug) {
let hasPrereqs = true;
if (aug.prereqs && aug.prereqs.length > 0) {
for (let i = 0; i < aug.prereqs.length; ++i) {
const prereqAug = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"][aug.prereqs[i]];
if (prereqAug == null) {
console.error(`Invalid prereq Augmentation ${aug.prereqs[i]}`);
continue;
}
if (prereqAug.owned === false) {
hasPrereqs = false; // Check if the aug is purchased
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations[j].name === prereqAug.name) {
hasPrereqs = true;
break;
}
}
}
}
}
return hasPrereqs;
}
function purchaseAugmentation(aug, fac, sing = false) {
const factionInfo = fac.getInfo();
var hasPrereqs = hasAugmentationPrereqs(aug);
if (!hasPrereqs) {
var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + "purchase this one.";
if (sing) {
return txt;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])(txt);
}
} else if (aug.baseCost !== 0 && _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].money.lt(aug.baseCost * factionInfo.augmentationPriceMult)) {
let txt = "You don't have enough money to purchase " + aug.name;
if (sing) {
return txt;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["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_18__["dialogBoxCreate"])(txt);
} else if (aug.baseCost === 0 || _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].firstAugPurchased === false) {
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].firstAugPurchased = true;
document.getElementById("augmentations-tab").style.display = "list-item";
document.getElementById("character-menu-header").click();
document.getElementById("character-menu-header").click();
}
var queuedAugmentation = new _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_5__["PlayerOwnedAugmentation"](aug.name);
if (aug.name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__["AugmentationNames"].NeuroFluxGovernor) {
queuedAugmentation.level = getNextNeurofluxLevel();
}
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations.push(queuedAugmentation);
_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].loseMoney(aug.baseCost * factionInfo.augmentationPriceMult); // If you just purchased Neuroflux Governor, recalculate the cost
if (aug.name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__["AugmentationNames"].NeuroFluxGovernor) {
var nextLevel = getNextNeurofluxLevel();
--nextLevel;
var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
aug.baseRepRequirement = 500 * mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7__["BitNodeMultipliers"].AugmentationRepCost;
aug.baseCost = 750e3 * mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7__["BitNodeMultipliers"].AugmentationMoneyCost;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations.length - 1; ++i) {
aug.baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_16__["SourceFileFlags"][11]];
}
}
for (var name in _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"]) {
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"].hasOwnProperty(name)) {
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_3__["Augmentations"][name].baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_16__["SourceFileFlags"][11]];
}
}
if (sing) {
return "You purchased " + aug.name;
} else {
if (!_Settings_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].SuppressBuyAugmentationConfirmation) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("You purchased " + aug.name + ". It's enhancements will not take " + "effect until they are installed. To install your augmentations, go to the " + "'Augmentations' tab on the left-hand navigation menu. Purchasing additional " + "augmentations will now be more expensive.");
}
} // Force a rerender of the Augmentations page
displayFactionContent(fac.name, true);
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["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.");
}
}
function getNextNeurofluxLevel() {
// Get current Neuroflux level based on Player's augmentations
let currLevel = 0;
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].augmentations[i].name === _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__["AugmentationNames"].NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].augmentations[i].level;
}
} // Account for purchased but uninstalled Augmentations
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].queuedAugmentations[i].name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_6__["AugmentationNames"].NeuroFluxGovernor) {
++currLevel;
}
}
return currLevel + 1;
}
function processPassiveFactionRepGain(numCycles) {
for (const name in _Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"]) {
if (name === _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].currentWorkFactionName) continue;
if (!_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"].hasOwnProperty(name)) continue;
const faction = _Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][name];
if (!faction.isMember) continue; // No passive rep for special factions
const info = faction.getInfo();
if (!info.offersWork()) continue; // No passive rep for gangs.
if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getGangName() === name) continue; // 0 favor = 1%/s
// 50 favor = 6%/s
// 100 favor = 11%/s
const favorMult = Math.min(0.1, faction.favor / 1000 + 0.01); // Find the best of all possible favor gain, minimum 1 rep / 2 minute.
const hRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15__["getHackingWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"], faction);
const sRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15__["getFactionSecurityWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"], faction);
const fRep = Object(_PersonObjects_formulas_reputation__WEBPACK_IMPORTED_MODULE_15__["getFactionFieldWorkRepGain"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"], faction);
const rate = Math.max(hRep * favorMult, sRep * favorMult, fRep * favorMult, 1 / 120);
faction.playerReputation += rate * numCycles * _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].faction_rep_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_7__["BitNodeMultipliers"].FactionPassiveRepGain;
}
}
/***/ }),
/* 72 */
/*!***********************************!*\
!*** ./utils/helpers/isString.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isString = void 0;
/**
* Checks whether the value passed in can be considered a string.
* @param value The value to check if it is a string.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function isString(value) {
return (typeof value === "string" || value instanceof String);
}
exports.isString = isString;
/***/ }),
/* 73 */
/*!********************************!*\
!*** ./src/Message/Message.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Message = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class Message {
constructor(filename = "", msg = "") {
// Name of Message file
this.filename = "";
// The text contains in the Message
this.msg = "";
// Flag indicating whether this Message has been received by the player
this.recvd = false;
this.filename = filename;
this.msg = msg;
this.recvd = false;
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("Message", this);
}
// Initializes a Message Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Message, value.data);
}
}
exports.Message = Message;
JSONReviver_1.Reviver.constructors.Message = Message;
/***/ }),
/* 74 */
/*!**************************!*\
!*** ./src/Terminal.jsx ***!
\**************************/
/*! exports provided: postNetburnerText, Terminal */
/*! exports used: Terminal, postNetburnerText */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return postNetburnerText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Terminal; });
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Terminal/DirectoryHelpers */ 86);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Terminal/determineAllPossibilitiesForTabCompletion */ 782);
/* harmony import */ var _Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Terminal/HelpText */ 458);
/* harmony import */ var _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Terminal/tabCompletion */ 781);
/* harmony import */ var _Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Fconf_Fconf__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Fconf/Fconf */ 193);
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Alias */ 67);
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Alias__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CodingContracts */ 93);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./DarkWeb/DarkWeb */ 533);
/* harmony import */ var _DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Fconf/FconfSettings */ 39);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Hacking */ 50);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Hacking__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Hacknet/HacknetServer */ 78);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./InteractiveTutorial */ 43);
/* harmony import */ var _Literature_LiteratureHelpers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Literature/LiteratureHelpers */ 523);
/* harmony import */ var _Literature_LiteratureHelpers__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_Literature_LiteratureHelpers__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Message/Message */ 73);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Message_Message__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Message/MessageHelpers */ 87);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./NetscriptWorker */ 80);
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Netscript/killWorkerScript */ 70);
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Netscript/WorkerScriptStartStopEventEmitter */ 147);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./RedPill */ 103);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Script/RunningScript */ 194);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 195);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Script/RunningScriptHelpers */ 444);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 120);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Script/ScriptHelpersTS */ 66);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./ui/numeralFormat */ 7);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 44);
/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 113);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 409);
/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ../utils/LogBox */ 151);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ../utils/YesNoBox */ 61);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./ui/postToTerminal */ 8);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! autosize */ 780);
/* harmony import */ var autosize__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(autosize__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! jszip */ 779);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! file-saver */ 778);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var arg__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! arg */ 445);
/* harmony import */ var arg__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(arg__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_48__);
function postNetburnerText() {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bitburner v" + _Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].Version);
} // Helper function that checks if an argument (which is a string) is a valid number
function isNumber(str) {
if (typeof str != "string") {
return false;
} // Only process strings
return !isNaN(str) && !isNaN(parseFloat(str));
}
function getTerminalInput() {
return document.getElementById("terminal-input-text-box").value;
} // Defines key commands in terminal
$(document).keydown(function (event) {
// Terminal
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["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_35__["KEY"].ENTER) {
event.preventDefault(); // Prevent newline from being entered in Script Editor
const command = getTerminalInput();
const dir = Terminal.currDir;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("[" + (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_TIMESTAMPS ? Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_37__["getTimestamp"])() + " " : "") + _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().hostname + ` ~${dir}]> ${command}`);
if (command.length > 0) {
Terminal.resetTerminalInput(); // Clear input first
Terminal.executeCommands(command);
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].C && event.ctrlKey) {
if (_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"]._actionInProgress) {
// Cancel action
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Cancelling...");
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"]._actionInProgress = false;
Terminal.finishAction(true);
} else if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
// Dont prevent default so it still copies
Terminal.resetTerminalInput(); // Clear Terminal
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["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_35__["KEY"].UPARROW || _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].P && event.ctrlKey) {
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
event.preventDefault();
} // Cycle through past commands
if (terminalInput == null) {
return;
}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {
return;
}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
}
if (i != 0) {
--Terminal.commandHistoryIndex;
}
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_32__["setTimeoutRef"])(function () {
terminalInput.selectionStart = terminalInput.selectionEnd = 10000;
}, 10);
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].DOWNARROW || _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].M && event.ctrlKey) {
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
event.preventDefault();
} // Cycle through past commands
if (terminalInput == null) {
return;
}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {
return;
}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
} // Latest command, put nothing
if (i == len || i == len - 1) {
Terminal.commandHistoryIndex = len;
terminalInput.value = "";
} else {
++Terminal.commandHistoryIndex;
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
}
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].TAB) {
event.preventDefault(); // Autocomplete
if (terminalInput == null) {
return;
}
let input = terminalInput.value;
if (input == "") {
return;
}
const semiColonIndex = input.lastIndexOf(";");
if (semiColonIndex !== -1) {
input = input.slice(semiColonIndex + 1);
}
input = input.trim();
input = input.replace(/\s\s+/g, ' ');
const commandArray = input.split(" ");
let index = commandArray.length - 2;
if (index < -1) {
index = 0;
}
const allPos = Object(_Terminal_determineAllPossibilitiesForTabCompletion__WEBPACK_IMPORTED_MODULE_1__["determineAllPossibilitiesForTabCompletion"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"], input, index, Terminal.currDir);
if (allPos.length == 0) {
return;
}
let arg = "";
let command = "";
if (commandArray.length == 0) {
return;
}
if (commandArray.length == 1) {
command = commandArray[0];
} else if (commandArray.length == 2) {
command = commandArray[0];
arg = commandArray[1];
} else if (commandArray.length == 3) {
command = commandArray[0] + " " + commandArray[1];
arg = commandArray[2];
} else {
arg = commandArray.pop();
command = commandArray.join(" ");
}
Object(_Terminal_tabCompletion__WEBPACK_IMPORTED_MODULE_3__["tabCompletion"])(command, arg, allPos);
terminalInput.focus();
} // Extra Bash Emulation Hotkeys, must be enabled through .fconf
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].A && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("home");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].E && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("end");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].B && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("prevchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].B && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("prevword");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].F && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("nextchar");
}
if (event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].F && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("nextword");
}
if ((event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].H || event.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["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_33__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["Page"].Terminal)) {
$('.terminal-input').focus();
}
});
$(document).keydown(function (e) {
if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["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_33__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_33__["Page"].Terminal)) {
if (e.which == _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_35__["KEY"].CTRL) {
terminalCtrlPressed = false;
}
if (e.shiftKey) {
shiftKeyPressed = false;
}
}
});
let Terminal = {
// Flags to determine whether the player is currently running a hack or an analyze
hackFlag: false,
backdoorFlag: false,
analyzeFlag: false,
actionStarted: false,
actionTime: 0,
commandHistory: [],
commandHistoryIndex: 0,
// True if a Coding Contract prompt is opened
contractOpen: false,
// Full Path of current directory
// Excludes the trailing forward slash
currDir: "/",
resetTerminalInput: function (keepInput = false) {
let input = "";
if (keepInput) {
input = getTerminalInput();
}
const dir = Terminal.currDir;
if (_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].WRAP_INPUT) {
document.getElementById("terminal-input-td").innerHTML = `
` + ``; // Auto re-size the line element as it wraps
autosize__WEBPACK_IMPORTED_MODULE_43___default()(document.getElementById("terminal-input-text-box"));
} else {
document.getElementById("terminal-input-td").innerHTML = `
` + ``;
}
const hdr = document.getElementById("terminal-input-header");
hdr.style.display = "inline";
const terminalInput = document.getElementById("terminal-input-text-box");
if (typeof terminalInput.selectionStart == "number") {
terminalInput.selectionStart = terminalInput.selectionEnd = terminalInput.value.length;
} else if (typeof terminalInput.createTextRange != "undefined") {
terminalInput.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
},
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 inputText = terminalInput.value;
switch (mod.toLowerCase()) {
case "backspace":
if (start > 0 && start <= inputLength + 1) {
terminalInput.value = inputText.substr(0, start - 1) + inputText.substr(start);
}
break;
case "deletewordbefore":
// Delete rest of word before the cursor
for (var delStart = start - 1; delStart > 0; --delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, delStart) + inputText.substr(start);
return;
}
}
break;
case "deletewordafter":
// Delete rest of word after the cursor
for (var delStart = start + 1; delStart <= text.length + 1; ++delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, start) + inputText.substr(delStart);
return;
}
}
break;
case "clearafter":
// Deletes everything after cursor
break;
case "clearbefore:":
// Deleetes everything before cursor
break;
}
} catch (e) {
console.error("Exception in Terminal.modifyInput: " + e);
}
},
moveTextCursor: function (loc) {
try {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput == null) {
return;
}
terminalInput.focus();
var inputLength = terminalInput.value.length;
var start = terminalInput.selectionStart;
switch (loc.toLowerCase()) {
case "home":
terminalInput.setSelectionRange(0, 0);
break;
case "end":
terminalInput.setSelectionRange(inputLength, inputLength);
break;
case "prevchar":
if (start > 0) {
terminalInput.setSelectionRange(start - 1, start - 1);
}
break;
case "prevword":
for (var i = start - 2; i >= 0; --i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i + 1, i + 1);
return;
}
}
terminalInput.setSelectionRange(0, 0);
break;
case "nextchar":
terminalInput.setSelectionRange(start + 1, start + 1);
break;
case "nextword":
for (var i = start + 1; i <= inputLength; ++i) {
if (terminalInput.value.charAt(i) === " ") {
terminalInput.setSelectionRange(i, i);
return;
}
}
terminalInput.setSelectionRange(inputLength, inputLength);
break;
default:
console.warn("Invalid loc argument in Terminal.moveTextCursor()");
break;
}
} catch (e) {
console.error("Exception in Terminal.moveTextCursor: " + e);
}
},
startHack: function () {
Terminal.hackFlag = true; // Hacking through Terminal should be faster than hacking through a script
Terminal.actionTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingTime"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer(), _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) / 4;
Terminal.startAction();
},
startBackdoor: function () {
Terminal.backdoorFlag = true; // Backdoor should take the same amount of time as hack
Terminal.actionTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingTime"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer(), _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) / 4;
Terminal.startAction();
},
startAnalyze: function () {
Terminal.analyzeFlag = true;
Terminal.actionTime = 1;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Analyzing system...");
Terminal.startAction();
},
startAction: function () {
Terminal.actionStarted = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["hackProgressPost"])("Time left:");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["hackProgressBarPost"])("["); // Disable terminal
document.getElementById("terminal-input-td").innerHTML = '';
$('input[class=terminal-input]').prop('disabled', true);
},
finishAction: function (cancelled = false) {
if (Terminal.hackFlag) {
Terminal.finishHack(cancelled);
} else if (Terminal.backdoorFlag) {
Terminal.finishBackdoor(cancelled);
} else if (Terminal.analyzeFlag) {
Terminal.finishAnalyze(cancelled);
} // 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);
},
// Complete the hack/analyze command
finishHack: function (cancelled = false) {
if (!cancelled) {
var server = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer(); // Calculate whether hack was successful
var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingChance"])(server, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]);
var rand = Math.random();
var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingExpGain"])(server, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]);
var expGainedOnFailure = expGainedOnSuccess / 4;
if (rand < hackChance) {
// Success!
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] && _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] == server.ip) {
if (_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN == null) {
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN = 1;
}
Object(_RedPill__WEBPACK_IMPORTED_MODULE_23__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN);
Terminal.hackFlag = false;
return;
}
server.backdoorInstalled = true;
var moneyGained = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculatePercentMoneyHacked"])(server, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]);
moneyGained = Math.floor(server.moneyAvailable * moneyGained);
if (moneyGained <= 0) {
moneyGained = 0;
} // Safety check
server.moneyAvailable -= moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].gainMoney(moneyGained);
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].recordMoneySource(moneyGained, "hacking");
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].gainHackingExp(expGainedOnSuccess);
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].gainIntelligenceExp(expGainedOnSuccess / _Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].IntelligenceTerminalHackBaseExpGain);
server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_8__["CONSTANTS"].ServerFortifyAmount);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postElement"])(react__WEBPACK_IMPORTED_MODULE_47___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_47___default.a.Fragment, null, "Hack successful! Gained ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_42__["Money"])(moneyGained), " and ", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatExp(expGainedOnSuccess), " hacking exp"));
} else {
// Failure
// Player only gains 25% exp for failure? TODO Can change this later to balance
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].gainHackingExp(expGainedOnFailure);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Failed to hack ${server.hostname}. Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatExp(expGainedOnFailure)} hacking exp`);
}
}
Terminal.hackFlag = false;
},
finishBackdoor: function (cancelled = false) {
if (!cancelled) {
const server = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] && _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerNames"].WorldDaemon] == server.ip) {
if (_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN == null) {
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN = 1;
}
Object(_RedPill__WEBPACK_IMPORTED_MODULE_23__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN);
Terminal.backdoorFlag = false;
return;
}
server.backdoorInstalled = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postElement"])(react__WEBPACK_IMPORTED_MODULE_47___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_47___default.a.Fragment, null, "Backdoor successful!"));
}
Terminal.backdoorFlag = false;
},
finishAnalyze: function (cancelled = false) {
if (!cancelled) {
let currServ = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const isHacknet = currServ instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__["HacknetServer"];
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(currServ.hostname + ": ");
const org = currServ.organizationName;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Organization name: " + (!isHacknet ? org : "Player"));
let hasAdminRights = !isHacknet && currServ.hasAdminRights || isHacknet;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Root Access: " + (hasAdminRights ? "YES" : "NO"));
const hackingSkill = currServ.requiredHackingSkill;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Required hacking skill: " + (!isHacknet ? hackingSkill : "N/A"));
const security = currServ.hackDifficulty;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Server security level: " + (!isHacknet ? _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatServerSecurity(security) : "N/A"));
const hackingChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingChance"])(currServ, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Chance to hack: " + (!isHacknet ? _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatPercentage(hackingChance) : "N/A"));
const hackingTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingTime"])(currServ, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) * 1000;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Time to hack: " + (!isHacknet ? Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["convertTimeMsToTimeElapsedString"])(hackingTime, true) : "N/A"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postElement"])(react__WEBPACK_IMPORTED_MODULE_47___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_47___default.a.Fragment, null, "Total money available on server: ", !isHacknet ? Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_42__["Money"])(currServ.moneyAvailable) : "N/A"));
const numPort = currServ.numOpenPortsRequired;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Required number of open ports for NUKE: " + (!isHacknet ? numPort : "N/A"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SSH port: " + (currServ.sshPortOpen ? "Open" : "Closed"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("FTP port: " + (currServ.ftpPortOpen ? "Open" : "Closed"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SMTP port: " + (currServ.smtpPortOpen ? "Open" : "Closed"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("HTTP port: " + (currServ.httpPortOpen ? "Open" : "Closed"));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SQL port: " + (currServ.sqlPortOpen ? "Open" : "Closed"));
}
Terminal.analyzeFlag = false;
},
executeCommands: function (commands) {
// Sanitize input
commands = commands.trim();
commands = commands.replace(/\s\s+/g, ' '); // Replace all extra whitespace in command with a single space
// Handle Terminal History - multiple commands should be saved as one
if (Terminal.commandHistory[Terminal.commandHistory.length - 1] != commands) {
Terminal.commandHistory.push(commands);
if (Terminal.commandHistory.length > 50) {
Terminal.commandHistory.splice(0, 1);
}
}
Terminal.commandHistoryIndex = Terminal.commandHistory.length; // Split commands and execute sequentially
commands = commands.match(/(?:'[^']*'|"[^"]*"|[^;"])*/g).map(_Alias__WEBPACK_IMPORTED_MODULE_5__["substituteAliases"]).map(c => c.match(/(?:'[^']*'|"[^"]*"|[^;"])*/g)).flat();
for (let i = 0; i < commands.length; i++) {
if (commands[i].match(/^\s*$/)) {
continue;
} // Don't run commands that only have whitespace
Terminal.executeCommand(commands[i].trim());
}
},
parseCommandArguments: function (command) {
// This will be used to keep track of whether we're in a quote. This is for situations
// like the alias command:
// alias run="run NUKE.exe"
// We want the run="run NUKE.exe" to be parsed as a single command, so this flag
// will keep track of whether we have a quote in
let inQuote = ``; // Returns an array with the command and its arguments in each index
// Properly handles quotation marks (e.g. `run foo.script "the sun"` will return [run, foo.script, the sun])
const args = [];
let start = 0,
i = 0;
let prevChar = ''; // Previous character
while (i < command.length) {
let escaped = false; // Check for escaped quotation marks
if (i >= 1) {
prevChar = command.charAt(i - 1);
if (prevChar === "\\") {
escaped = true;
}
}
const c = command.charAt(i);
if (c === '"') {
// Double quotes
if (!escaped && prevChar === " ") {
const endQuote = command.indexOf('"', i + 1);
if (endQuote !== -1 && (endQuote === command.length - 1 || command.charAt(endQuote + 1) === " ")) {
args.push(command.substr(i + 1, endQuote - i - 1));
if (endQuote === command.length - 1) {
start = i = endQuote + 1;
} else {
start = i = endQuote + 2; // Skip the space
}
continue;
}
} else {
if (inQuote === ``) {
inQuote = `"`;
} else if (inQuote === `"`) {
inQuote = ``;
}
}
} else if (c === "'") {
// Single quotes, same thing as above
if (!escaped && prevChar === " ") {
const endQuote = command.indexOf("'", i + 1);
if (endQuote !== -1 && (endQuote === command.length - 1 || command.charAt(endQuote + 1) === " ")) {
args.push(command.substr(i + 1, endQuote - i - 1));
if (endQuote === command.length - 1) {
start = i = endQuote + 1;
} else {
start = i = endQuote + 2; // Skip the space
}
continue;
}
} else {
if (inQuote === ``) {
inQuote = `'`;
} else if (inQuote === `'`) {
inQuote = ``;
}
}
} else if (c === " " && inQuote === ``) {
let arg = command.substr(start, i - start); // If this is a number, convert it from a string to number
if (isNumber(arg)) {
args.push(parseFloat(arg));
} else {
args.push(arg);
}
start = i + 1;
}
++i;
} // Add the last argument
if (start !== i) {
let arg = command.substr(start, i - start); // If this is a number, convert it from string to number
if (isNumber(arg)) {
args.push(parseFloat(arg));
} else {
args.push(arg);
}
}
return args;
},
executeCommand: function (command) {
if (Terminal.hackFlag || Terminal.backdoorFlag || Terminal.analyzeFlag) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Cannot execute command (${command}) while an action is in progress`);
return;
} // Allow usage of ./
if (command.startsWith("./")) {
command = "run " + command.slice(2);
} // Only split the first space
var commandArray = Terminal.parseCommandArguments(command);
if (commandArray.length == 0) {
return;
}
/****************** Interactive Tutorial Terminal Commands ******************/
if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["ITutorial"].isRunning) {
var n00dlesServ = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["GetServerByHostname"])("n00dles");
if (n00dlesServ == null) {
throw new Error("Could not get n00dles server");
return;
}
switch (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["ITutorial"].currStep) {
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalHelp:
if (commandArray.length === 1 && commandArray[0] == "help") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["TerminalHelpText"]);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalLs:
if (commandArray.length === 1 && commandArray[0] == "ls") {
Terminal.executeListCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalScan:
if (commandArray.length === 1 && commandArray[0] == "scan") {
Terminal.executeScanCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalScanAnalyze1:
if (commandArray.length == 1 && commandArray[0] == "scan-analyze") {
Terminal.executeScanAnalyzeCommand(1);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalScanAnalyze2:
if (commandArray.length == 2 && commandArray[0] == "scan-analyze" && commandArray[1] === 2) {
Terminal.executeScanAnalyzeCommand(2);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalConnect:
if (commandArray.length == 2) {
if (commandArray[0] == "connect" && (commandArray[1] == "n00dles" || commandArray[1] == n00dlesServ.ip)) {
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].currentServer = n00dlesServ.ip;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Connected to n00dles");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Wrong command! Try again!");
return;
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalAnalyze:
if (commandArray.length === 1 && commandArray[0] === "analyze") {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Incorrect usage of analyze command. Usage: analyze");
return;
}
Terminal.startAnalyze();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalNuke:
if (commandArray.length == 2 && commandArray[0] == "run" && commandArray[1] == "NUKE.exe") {
n00dlesServ.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("NUKE successful! Gained root access to n00dles");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalManualHack:
if (commandArray.length == 1 && commandArray[0] == "hack") {
Terminal.startHack();
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalCreateScript:
if (commandArray.length == 2 && commandArray[0] == "nano" && commandArray[1] == "n00dles.script") {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent("n00dles.script", "");
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalFree:
if (commandArray.length == 1 && commandArray[0] == "free") {
Terminal.executeFreeCommand(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].TerminalRunScript:
if (commandArray.length == 2 && commandArray[0] == "run" && commandArray[1] == "n00dles.script") {
Terminal.runScript(commandArray);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialSteps"].ActiveScriptsToTerminal:
if (commandArray.length == 2 && commandArray[0] == "tail" && commandArray[1] == "n00dles.script") {
// Check that the script exists on this machine
var runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_27__[/* findRunningScript */ "a"])("n00dles.script", [], _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer());
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Error: No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__["logBoxCreate"])(runningScript);
Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_15__["iTutorialNextStep"])();
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Bad command. Please follow the tutorial");
}
break;
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["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_22__["Player"].getCurrentServer();
switch (commandArray[0].toLowerCase()) {
case "alias":
if (commandArray.length === 1) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_5__["printAliases"])();
return;
}
if (commandArray.length === 2) {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_5__["parseAliasDeclaration"])(commandArray[1])) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Set alias ${commandArray[1]}`);
return;
}
}
if (commandArray.length === 3) {
if (commandArray[1] === "-g") {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_5__["parseAliasDeclaration"])(commandArray[2], true)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Set global alias ${commandArray[2]}`);
return;
}
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]');
break;
case "analyze":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Incorrect usage of analyze command. Usage: analyze");
return;
}
Terminal.startAnalyze();
break;
case "backdoor":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Incorrect usage of backdoor command. Usage: backdoor");
return;
}
if (s.purchasedByPlayer) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Cannot use backdoor on your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (!s.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You do not have admin rights for this machine! Cannot backdoor");
} else if (s.requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hacking_skill) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Your hacking skill is not high enough to use backdoor on this machine. Try analyzing the machine to determine the required hacking skill");
} else if (s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__["HacknetServer"]) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Cannot use backdoor on this type of Server");
} else {
Terminal.startBackdoor();
}
break;
case "buy":
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_31__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) {
Object(_DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_10__["executeDarkwebTerminalCommand"])(commandArray);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You need to be able to connect to the Dark Web to use the buy command. (Maybe there's a TOR router you can buy somewhere)");
}
break;
case "cat":
{
try {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of cat command. Usage: cat [file]");
return;
}
const filename = Terminal.getFilepath(commandArray[1]);
if (!filename.endsWith(".msg") && !filename.endsWith(".lit") && !filename.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Only .msg, .txt, and .lit files are viewable with cat (filename must end with .msg, .txt, or .lit)");
return;
}
if (filename.endsWith(".msg") || filename.endsWith(".lit")) {
for (let i = 0; i < s.messages.length; ++i) {
if (filename.endsWith(".lit") && s.messages[i] === filename) {
Object(_Literature_LiteratureHelpers__WEBPACK_IMPORTED_MODULE_16__["showLiterature"])(s.messages[i]);
return;
} else if (filename.endsWith(".msg") && s.messages[i].filename === filename) {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_18__[/* showMessage */ "e"])(s.messages[i]);
return;
}
}
} else if (filename.endsWith(".txt")) {
const txt = Terminal.getTextFile(filename);
if (txt != null) {
txt.show();
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`No such file ${filename}`);
} catch (e) {
Terminal.postThrownError(e);
}
break;
}
case "cd":
{
if (commandArray.length > 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: cd [dir]");
} else {
let dir = commandArray.length === 2 ? commandArray[1] : "/";
let evaledDir;
if (dir === "/") {
evaledDir = "/";
} else {
// Ignore trailing slashes
dir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["removeTrailingSlash"])(dir);
evaledDir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateDirectoryPath"])(dir, Terminal.currDir);
if (evaledDir == null || evaledDir === "") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid path. Failed to change directories");
return;
}
const server = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
if (!server.scripts.some(script => script.filename.startsWith(evaledDir)) && !server.textFiles.some(file => file.fn.startsWith(evaledDir))) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid path. Failed to change directories");
return;
}
}
Terminal.currDir = evaledDir; // Reset input to update current directory on UI
Terminal.resetTerminalInput();
}
break;
}
case "check":
{
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...");
} else {
const scriptName = Terminal.getFilepath(commandArray[1]); // Can only tail script files
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(scriptName)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("tail can only be called on .script files (filename must end with .script)");
return;
} // Get args
let args = [];
for (var i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
} // Check that the script exists on this machine
var runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_27__[/* findRunningScript */ "a"])(scriptName, args, s);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such script exists");
return;
}
runningScript.displayLog();
}
} catch (e) {
Terminal.postThrownError(e);
}
break;
}
case "clear":
case "cls":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of clear/cls command. Usage: clear/cls");
return;
}
$("#terminal tr:not(:last)").remove();
postNetburnerText();
break;
case "connect":
{
// Disconnect from current server in terminal and connect to new one
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of connect command. Usage: connect [ip/hostname]");
return;
}
let ip = commandArray[1];
for (let i = 0; i < s.serversOnNetwork.length; i++) {
if (Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServerOnNetwork"])(s, i).ip == ip || Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServerOnNetwork"])(s, i).hostname == ip) {
Terminal.connectToServer(ip);
return;
}
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Host not found");
break;
}
case "download":
{
try {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of download command. Usage: download [script/text file]");
return;
}
const fn = commandArray[1];
if (fn === "*" || fn === "*.script" || fn === "*.txt") {
// Download all scripts as a zip
var zip = new jszip__WEBPACK_IMPORTED_MODULE_44__();
if (fn === "*" || fn === "*.script") {
for (var i = 0; i < s.scripts.length; ++i) {
var file = new Blob([s.scripts[i].code], {
type: "text/plain"
});
zip.file(s.scripts[i].filename + ".js", file);
}
}
if (fn === "*" || fn === "*.txt") {
for (var i = 0; i < s.textFiles.length; ++i) {
var file = new Blob([s.textFiles[i].text], {
type: "text/plain"
});
zip.file(s.textFiles[i].fn, file);
}
}
let zipFn;
switch (fn) {
case "*.script":
zipFn = "bitburnerScripts.zip";
break;
case "*.txt":
zipFn = "bitburnerTexts.zip";
break;
default:
zipFn = "bitburnerFiles.zip";
break;
}
zip.generateAsync({
type: "blob"
}).then(function (content) {
file_saver__WEBPACK_IMPORTED_MODULE_45__["saveAs"](content, zipFn);
});
return;
} else if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(fn)) {
// Download a single script
const script = Terminal.getScript(fn);
if (script != null) {
return script.download();
}
} else if (fn.endsWith(".txt")) {
// Download a single text file
const txt = Terminal.getTextFile(fn);
if (txt != null) {
return txt.download();
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Cannot download this filetype`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`${fn} does not exist`);
} catch (e) {
Terminal.postThrownError(e);
}
break;
}
case "expr":
{
if (commandArray.length <= 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of expr command. Usage: expr [math expression]");
return;
}
let expr = commandArray.slice(1).join(""); // Sanitize the math expression
let sanitizedExpr = expr.replace(/s+/g, '').replace(/[^-()\d/*+.]/g, '');
let result;
try {
result = eval(sanitizedExpr);
} catch (e) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Could not evaluate expression: ${sanitizedExpr}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(result);
break;
}
case "free":
Terminal.executeFreeCommand(commandArray);
break;
case "hack":
{
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of hack command. Usage: hack");
return;
} // Hack the current PC (usually for money)
// You can't hack your home pc or servers you purchased
if (s.purchasedByPlayer) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (s.hasAdminRights == false) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You do not have admin rights for this machine! Cannot hack");
} else if (s.requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hacking_skill) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else if (s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__["HacknetServer"]) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Cannot hack this type of Server");
} else {
Terminal.startHack();
}
break;
}
case "help":
if (commandArray.length !== 1 && commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of help command. Usage: help");
return;
}
if (commandArray.length === 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(_Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["TerminalHelpText"]);
} else {
var cmd = commandArray[1];
var txt = _Terminal_HelpText__WEBPACK_IMPORTED_MODULE_2__["HelpTexts"][cmd];
if (txt == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No help topics match '" + cmd + "'");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(txt);
}
break;
case "home":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of home command. Usage: home");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].currentServer = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getHomeComputer().ip;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Connected to home");
Terminal.currDir = "/";
Terminal.resetTerminalInput();
break;
case "hostname":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of hostname command. Usage: hostname");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().hostname);
break;
case "ifconfig":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of ifconfig command. Usage: ifconfig");
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().ip);
break;
case "kill":
{
Terminal.executeKillCommand(commandArray);
break;
}
case "killall":
{
for (let i = s.runningScripts.length - 1; i >= 0; --i) {
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20__["killWorkerScript"])(s.runningScripts[i], s.ip, false);
}
_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_21__["WorkerScriptStartStopEventEmitter"].emitEvent();
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Killing all running scripts");
break;
}
case "ls":
{
Terminal.executeListCommand(commandArray);
break;
}
case "lscpu":
{
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().cpuCores + " Core(s)");
break;
}
case "mem":
{
Terminal.executeMemCommand(commandArray);
break;
}
case "mv":
{
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Incorrect number of arguments. Usage: mv [src] [dest]`);
return;
}
try {
const source = commandArray[1];
const dest = commandArray[2];
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(source) && !source.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`'mv' can only be used on scripts and text files (.txt)`);
return;
}
const srcFile = Terminal.getFile(source);
if (srcFile == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Source file ${source} does not exist`);
return;
}
const sourcePath = Terminal.getFilepath(source);
const destPath = Terminal.getFilepath(dest);
const destFile = Terminal.getFile(dest); // 'mv' command only works on scripts and txt files.
// Also, you can't convert between different file types
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(source)) {
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(dest)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Source and destination files must have the same type`);
return;
} // Command doesnt work if script is running
if (s.isRunning(sourcePath)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Cannot use 'mv' on a script that is running`);
return;
}
if (destFile != null) {
// Already exists, will be overwritten, so we'll delete it
const status = s.removeFile(destPath);
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Something went wrong...please contact game dev (probably a bug)`);
return;
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Warning: The destination file was overwritten");
}
}
srcFile.filename = destPath;
} else if (source.endsWith(".txt")) {
if (!dest.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Source and destination files must have the same type`);
return;
}
if (destFile != null) {
// Already exists, will be overwritten, so we'll delete it
const status = s.removeFile(destPath);
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Something went wrong...please contact game dev (probably a bug)`);
return;
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Warning: The destination file was overwritten");
}
}
srcFile.fn = destPath;
}
} catch (e) {
Terminal.postThrownError(e);
}
break;
}
case "nano":
Terminal.executeNanoCommand(commandArray);
break;
case "ps":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of ps command. Usage: ps");
return;
}
for (let i = 0; i < s.runningScripts.length; i++) {
let rsObj = s.runningScripts[i];
let res = `(PID - ${rsObj.pid}) ${rsObj.filename}`;
for (let j = 0; j < rsObj.args.length; ++j) {
res += " " + rsObj.args[j].toString();
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(res);
}
break;
case "rm":
{
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: rm [program/script]");
return;
} // Check programs
let delTarget, status;
try {
delTarget = Terminal.getFilepath(commandArray[1]);
status = s.removeFile(delTarget);
} catch (err) {
status = {
res: false,
msg: 'No such file exists'
};
}
if (!status.res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(status.msg);
}
break;
}
case "run":
// Run a program or a script
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]...");
} else {
var executableName = commandArray[1]; // Secret Music player!
if (executableName === "musicplayer") {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])('', false);
return;
} // Check if its a script or just a program/executable
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(executableName)) {
Terminal.runScript(commandArray);
} else if (executableName.endsWith(".cct")) {
Terminal.runContract(executableName);
} else {
Terminal.runProgram(commandArray);
}
}
break;
case "scan":
Terminal.executeScanCommand(commandArray);
break;
case "scan-analyze":
if (commandArray.length === 1) {
Terminal.executeScanAnalyzeCommand(1);
} else {
// # of args must be 2 or 3
if (commandArray.length > 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]");
return;
}
let all = false;
if (commandArray.length === 3 && commandArray[2] === "-a") {
all = true;
}
let depth = parseInt(commandArray[1]);
if (isNaN(depth) || depth < 0) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of scan-analyze command. depth argument must be positive numeric");
return;
}
if (depth > 3 && !_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].DeepscanV1.name) && !_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 3");
return;
} else if (depth > 5 && !_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].DeepscanV2.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 5");
return;
} else if (depth > 10) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("You cannot scan-analyze with that high of a depth. Maximum depth is 10");
return;
}
Terminal.executeScanAnalyzeCommand(depth, all);
}
break;
/* eslint-disable no-case-declarations */
case "scp":
Terminal.executeScpCommand(commandArray);
break;
/* eslint-enable no-case-declarations */
case "sudov":
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: sudov");
return;
}
if (s.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("You have ROOT access to this machine");
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("You do NOT have root access to this machine");
}
break;
case "tail":
{
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]...");
} else if (typeof commandArray[1] === 'string') {
const scriptName = Terminal.getFilepath(commandArray[1]);
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(scriptName)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("tail can only be called on .script, .ns, .js files, or by pid");
return;
} // Get script arguments
const args = [];
for (let i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
} // go over all the running scripts. If there's a perfect
// match, use it!
for (var i = 0; i < s.runningScripts.length; ++i) {
if (s.runningScripts[i].filename === scriptName && Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_25__["compareArrays"])(s.runningScripts[i].args, args)) {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__["logBoxCreate"])(s.runningScripts[i]);
return;
}
} // Find all scripts that are potential candidates.
const candidates = [];
for (var i = 0; i < s.runningScripts.length; ++i) {
// only scripts that have more arguments (equal arguments is already caught)
if (s.runningScripts[i].args.length < args.length) continue; // make a smaller copy of the args.
const args2 = s.runningScripts[i].args.slice(0, args.length);
if (s.runningScripts[i].filename === scriptName && Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_25__["compareArrays"])(args2, args)) {
candidates.push(s.runningScripts[i]);
}
} // If there's only 1 possible choice, use that.
if (candidates.length === 1) {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__["logBoxCreate"])(candidates[0]);
return;
} // otherwise lists all possible conflicting choices.
if (candidates.length > 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Found several potential candidates:");
for (const candidate of candidates) Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`${candidate.filename} ${candidate.args.join(' ')}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Script arguments need to be specified.");
return;
} // if there's no candidate then we just don't know.
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such script exists.");
} else {
const runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_27__[/* findRunningScriptByPid */ "b"])(commandArray[1], _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer());
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such script exists");
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__["logBoxCreate"])(runningScript);
}
} catch (e) {
Terminal.postThrownError(e);
}
break;
}
case "theme":
{
let args = commandArray.slice(1);
if (args.length !== 1 && args.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect number of arguments.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Usage: theme [default|muted|solarized] | #[background color hex] #[text color hex] #[highlight color hex]");
} else if (args.length === 1) {
var themeName = args[0];
if (themeName == "default") {
document.body.style.setProperty('--my-highlight-color', "#ffffff");
document.body.style.setProperty('--my-font-color', "#66ff33");
document.body.style.setProperty('--my-background-color', "#000000");
document.body.style.setProperty('--my-prompt-color', "#f92672");
} else if (themeName == "muted") {
document.body.style.setProperty('--my-highlight-color', "#ffffff");
document.body.style.setProperty('--my-font-color', "#66ff33");
document.body.style.setProperty('--my-background-color', "#252527");
} else if (themeName == "solarized") {
document.body.style.setProperty('--my-highlight-color', "#6c71c4");
document.body.style.setProperty('--my-font-color', "#839496");
document.body.style.setProperty('--my-background-color', "#002b36");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Theme not found");
}
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_PROMPT_COLOR = document.body.style.getPropertyValue("--my-prompt-color");
} else {
var inputBackgroundHex = args[0];
var inputTextHex = args[1];
var inputHighlightHex = args[2];
if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputBackgroundHex) && /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputTextHex) && /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputHighlightHex)) {
document.body.style.setProperty('--my-highlight-color', inputHighlightHex);
document.body.style.setProperty('--my-font-color', inputTextHex);
document.body.style.setProperty('--my-background-color', inputBackgroundHex);
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_HIGHLIGHT_COLOR = document.body.style.getPropertyValue("--my-highlight-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_FONT_COLOR = document.body.style.getPropertyValue("--my-font-color");
_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_12__["FconfSettings"].THEME_BACKGROUND_COLOR = document.body.style.getPropertyValue("--my-background-color");
} else {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid Hex Input for theme");
}
}
break;
}
case "top":
{
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of top command. Usage: top");
return;
} // Headers
const scriptWidth = 40;
const pidWidth = 10;
const threadsWidth = 16;
const scriptTxt = "Script";
const pidTxt = "PID";
const threadsTxt = "Threads";
const ramTxt = "RAM Usage";
const spacesAfterScriptTxt = " ".repeat(scriptWidth - scriptTxt.length);
const spacesAfterPidTxt = " ".repeat(pidWidth - pidTxt.length);
const spacesAfterThreadsTxt = " ".repeat(threadsWidth - threadsTxt.length);
const headers = `${scriptTxt}${spacesAfterScriptTxt}${pidTxt}${spacesAfterPidTxt}${threadsTxt}${spacesAfterThreadsTxt}${ramTxt}`;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(headers);
let currRunningScripts = s.runningScripts; // Iterate through scripts on current server
for (let i = 0; i < currRunningScripts.length; i++) {
let script = currRunningScripts[i]; // Calculate name padding
const numSpacesScript = Math.max(0, scriptWidth - script.filename.length);
const spacesScript = " ".repeat(numSpacesScript); // Calculate PID padding
const numSpacesPid = Math.max(0, pidWidth - (script.pid + "").length);
const spacesPid = " ".repeat(numSpacesPid); // Calculate thread padding
const numSpacesThread = Math.max(0, threadsWidth - (script.threads + "").length);
const spacesThread = " ".repeat(numSpacesThread); // Calculate and transform RAM usage
const ramUsage = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(Object(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_26__["getRamUsageFromRunningScript"])(script) * script.threads);
const entry = [script.filename, spacesScript, script.pid, spacesPid, script.threads, spacesThread, ramUsage].join("");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(entry);
}
break;
}
case "unalias":
{
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])('Incorrect usage of unalias name. Usage: unalias [alias]');
return;
} else {
if (Object(_Alias__WEBPACK_IMPORTED_MODULE_5__["removeAlias"])(commandArray[1])) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Removed alias ${commandArray[1]}`);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`No such alias exists: ${commandArray[1]}`);
}
}
break;
}
case "wget":
{
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of wget command. Usage: wget [url] [target file]");
return;
}
let url = commandArray[1];
let target = Terminal.getFilepath(commandArray[2]);
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(target) && !target.endsWith(".txt")) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`wget failed: Invalid target file. Target file must be script or text file`);
}
$.get(url, function (data) {
let res;
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(target)) {
res = s.writeToScriptFile(target, data);
} else {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("wget failed");
}
if (res.overwritten) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`wget successfully retrieved content and overwrote ${target}`);
}
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`wget successfully retrieved content to new file ${target}`);
}, 'text').fail(function (e) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("wget failed: " + JSON.stringify(e));
});
break;
}
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Command ${commandArray[0]} not found`);
}
},
connectToServer: function (ip) {
var serv = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServer"])(ip);
if (serv == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Invalid server. Connection failed.");
return;
}
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].currentServer = serv.ip;
_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().isConnectedTo = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Connected to " + serv.hostname);
Terminal.currDir = "/";
if (_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().hostname == "darkweb") {
Object(_DarkWeb_DarkWeb__WEBPACK_IMPORTED_MODULE_10__["checkIfConnectedToDarkweb"])(); // Posts a 'help' message if connecting to dark web
}
Terminal.resetTerminalInput();
},
executeFreeCommand: function (commandArray) {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of free command. Usage: free");
return;
}
const ram = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().maxRam);
const used = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().ramUsed);
const avail = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().maxRam - _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().ramUsed);
const maxLength = Math.max(ram.length, Math.max(used.length, avail.length));
const usedPercent = _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatPercentage(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().ramUsed / _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().maxRam);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Total: ${" ".repeat(maxLength - ram.length)}${ram}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Used: ${" ".repeat(maxLength - used.length)}${used} (${usedPercent})`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Available: ${" ".repeat(maxLength - avail.length)}${avail}`);
},
executeKillCommand: function (commandArray) {
try {
if (commandArray.length < 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]...");
return;
} // Kill by PID
if (typeof commandArray[1] === "number") {
const pid = commandArray[1];
const res = Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20__["killWorkerScript"])(pid);
if (res) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Killing script with PID ${pid}`);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Failed to kill script with PID ${pid}. No such script exists`);
}
return;
}
const s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const scriptName = Terminal.getFilepath(commandArray[1]);
const args = [];
for (let i = 2; i < commandArray.length; ++i) {
args.push(commandArray[i]);
}
const runningScript = s.getRunningScript(scriptName, args);
if (runningScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such script is running. Nothing to kill");
return;
}
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_20__["killWorkerScript"])(runningScript, s.ip);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Killing ${scriptName}`);
} catch (e) {
Terminal.postThrownError(e);
}
},
executeListCommand: function (commandArray) {
const numArgs = commandArray.length;
function incorrectUsage() {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of ls command. Usage: ls [dir] [| grep pattern]");
}
if (numArgs <= 0 || numArgs > 5 || numArgs === 3) {
return incorrectUsage();
} // Grep
let filter = null; // Grep
// Directory path
let prefix = Terminal.currDir;
if (!prefix.endsWith("/")) {
prefix += "/";
} // If there are 4+ arguments, then the last 3 must be for grep
if (numArgs >= 4) {
if (commandArray[numArgs - 2] !== "grep" || commandArray[numArgs - 3] !== "|") {
return incorrectUsage();
}
filter = commandArray[numArgs - 1];
} // If the second argument is not a pipe, then it must be for listing a directory
if (numArgs >= 2 && commandArray[1] !== "|") {
prefix = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateDirectoryPath"])(commandArray[1], Terminal.currDir);
if (prefix != null) {
if (!prefix.endsWith("/")) {
prefix += "/";
}
if (!Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["isValidDirectoryPath"])(prefix)) {
return incorrectUsage();
}
}
} // Root directory, which is the same as no 'prefix' at all
if (prefix === "/") {
prefix = null;
} // Display all programs and scripts
const allPrograms = [];
const allScripts = [];
const allTextFiles = [];
const allContracts = [];
const allMessages = [];
const folders = [];
function handleFn(fn, dest) {
let parsedFn = fn;
if (prefix) {
if (!fn.startsWith(prefix)) {
return;
} else {
parsedFn = fn.slice(prefix.length, fn.length);
}
}
if (filter && !parsedFn.includes(filter)) {
return;
} // If the fn includes a forward slash, it must be in a subdirectory.
// Therefore, we only list the "first" directory in its path
if (parsedFn.includes("/")) {
const firstParentDir = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["getFirstParentDirectory"])(parsedFn);
if (filter && !firstParentDir.includes(filter)) {
return;
}
if (!folders.includes(firstParentDir)) {
folders.push(firstParentDir);
}
return;
}
dest.push(parsedFn);
} // Get all of the programs and scripts on the machine into one temporary array
const s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
for (const program of s.programs) handleFn(program, allPrograms);
for (const script of s.scripts) handleFn(script.filename, allScripts);
for (const txt of s.textFiles) handleFn(txt.fn, allTextFiles);
for (const contract of s.contracts) handleFn(contract.fn, allContracts);
for (const msgOrLit of s.messages) msgOrLit instanceof _Message_Message__WEBPACK_IMPORTED_MODULE_17__["Message"] ? handleFn(msgOrLit.filename, allMessages) : handleFn(msgOrLit, allMessages); // Sort the files/folders alphabetically then print each
allPrograms.sort();
allScripts.sort();
allTextFiles.sort();
allContracts.sort();
allMessages.sort();
folders.sort();
function postSegments(segments, config) {
const maxLength = Math.max(...segments.map(s => s.length)) + 1;
const filesPerRow = Math.floor(80 / maxLength);
for (let i = 0; i < segments.length; i++) {
let row = '';
for (let col = 0; col < filesPerRow; col++) {
if (!(i < segments.length)) break;
row += segments[i];
row += " ".repeat(maxLength * (col + 1) - row.length);
i++;
}
i--;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postContent"])(row, config);
}
}
const config = {
color: "#0000FF"
};
const groups = [{
segments: folders,
config: config
}, {
segments: allMessages
}, {
segments: allTextFiles
}, {
segments: allPrograms
}, {
segments: allContracts
}, {
segments: allScripts
}].filter(g => g.segments.length > 0);
for (let i = 0; i < groups.length; i++) {
if (i !== 0) Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postElement"])(react__WEBPACK_IMPORTED_MODULE_47___default.a.createElement("br", null));
postSegments(groups[i].segments, groups[i].config);
}
},
executeMemCommand: function (commandArray) {
try {
if (commandArray.length !== 2 && commandArray.length !== 4) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]");
return;
}
const scriptName = commandArray[1];
let numThreads = 1;
if (commandArray.length === 4 && commandArray[2] === "-t") {
numThreads = Math.round(parseInt(commandArray[3]));
if (isNaN(numThreads) || numThreads < 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid number of threads specified. Number of threads must be greater than 1");
return;
}
}
const script = Terminal.getScript(scriptName);
if (script == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such script exists!");
return;
}
const ramUsage = script.ramUsage * numThreads;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`This script requires ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(ramUsage)} of RAM to run for ${numThreads} thread(s)`);
} catch (e) {
Terminal.postThrownError(e);
}
},
executeNanoCommand: function (commandArray) {
if (commandArray.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of nano command. Usage: nano [scriptname]");
return;
}
try {
const filename = commandArray[1];
if (filename === ".fconf") {
let text = Object(_Fconf_Fconf__WEBPACK_IMPORTED_MODULE_4__["createFconf"])();
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filename, text);
return;
} else if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(filename)) {
const filepath = Terminal.getFilepath(filename);
const script = Terminal.getScript(filename);
if (script == null) {
let code = "";
if (filename.endsWith(".ns") || filename.endsWith(".js")) {
code = `export async function main(ns) {
}`;
}
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath, code);
} else {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath, script.code);
}
} else if (filename.endsWith(".txt")) {
const filepath = Terminal.getFilepath(filename);
const txt = Terminal.getTextFile(filename);
if (txt == null) {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath);
} else {
_engine__WEBPACK_IMPORTED_MODULE_11__["Engine"].loadScriptEditorContent(filepath, txt.text);
}
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid file. Only scripts (.script, .ns, .js), text files (.txt), or .fconf can be edited with nano");
return;
}
} catch (e) {
Terminal.postThrownError(e);
}
},
executeScanCommand: function (commandArray) {
if (commandArray.length !== 1) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of netstat/scan command. Usage: netstat/scan");
return;
} // Displays available network connections using TCP
const currServ = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const servers = currServ.serversOnNetwork.map((_, i) => {
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServerOnNetwork"])(currServ, i);
return {
hostname: server.hostname,
ip: server.ip,
hasRoot: server.hasAdminRights ? "Y" : "N"
};
});
servers.unshift({
hostname: "Hostname",
ip: "IP",
hasRoot: "Root Access"
});
const maxHostname = Math.max(...servers.map(s => s.hostname.length));
const maxIP = Math.max(...servers.map(s => s.ip.length));
for (const server of servers) {
let entry = server.hostname;
entry += " ".repeat(maxHostname - server.hostname.length + 1);
entry += server.ip;
entry += " ".repeat(maxIP - server.ip.length + 1);
entry += server.hasRoot;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(entry);
}
},
executeScanAnalyzeCommand: function (depth = 1, all = false) {
// TODO Using array as stack for now, can make more efficient
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(" "); // Map of all servers to keep track of which have been visited
var visited = {};
for (const ip in _Server_AllServers__WEBPACK_IMPORTED_MODULE_29__["AllServers"]) {
visited[ip] = 0;
}
const stack = [];
const depthQueue = [0];
const currServ = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
stack.push(currServ);
while (stack.length != 0) {
const s = stack.pop();
const d = depthQueue.pop();
const isHacknet = s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__["HacknetServer"];
if (!all && s.purchasedByPlayer && s.hostname != "home") {
continue; // Purchased server
} else if (visited[s.ip] || d > depth) {
continue; // Already visited or out-of-depth
} else if (!all && isHacknet) {
continue; // Hacknet Server
} else {
visited[s.ip] = 1;
}
for (var i = s.serversOnNetwork.length - 1; i >= 0; --i) {
stack.push(Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServerOnNetwork"])(s, i));
depthQueue.push(d + 1);
}
if (d == 0) {
continue;
} // Don't print current server
var titleDashes = Array((d - 1) * 4 + 1).join("-");
if (_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].AutoLink.name)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("" + titleDashes + "> " + s.hostname + "", false);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("" + titleDashes + ">" + s.hostname + "");
}
var dashes = titleDashes + "--";
var c = "NO";
if (s.hasAdminRights) {
c = "YES";
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${dashes}Root Access: ${c}${!isHacknet ? ", Required hacking skill: " + s.requiredHackingSkill : ""}`);
if (!isHacknet) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(dashes + "Number of open ports required to NUKE: " + s.numOpenPortsRequired);
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(dashes + "RAM: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_34__["numeralWrapper"].formatRAM(s.maxRam));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(" ");
}
var links = document.getElementsByClassName("scan-analyze-link");
for (let i = 0; i < links.length; ++i) {
(function () {
var hostname = links[i].innerHTML.toString();
links[i].onclick = function () {
if (Terminal.analyzeFlag || Terminal.hackFlag || Terminal.backdoorFlag) {
return;
}
Terminal.connectToServer(hostname);
};
})(); // Immediate invocation
}
},
executeScpCommand(commandArray) {
try {
if (commandArray.length !== 3) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
const scriptname = Terminal.getFilepath(commandArray[1]);
if (!scriptname.endsWith(".lit") && !Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(scriptname) && !scriptname.endsWith(".txt")) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("scp only works for scripts, text files (.txt), and literature files (.lit)");
return;
}
const destServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServer"])(commandArray[2]);
if (destServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Invalid destination. ${commandArray[2]} not found`);
return;
}
const currServ = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer(); // Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message_Message__WEBPACK_IMPORTED_MODULE_17__["Message"]) && currServ.messages[i] == scriptname) {
found = true;
break;
}
}
if (!found) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("No such file exists!");
}
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(scriptname + " copied over to " + destServer.hostname);
return; // Already exists
}
}
destServer.messages.push(scriptname);
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["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_40__["postError"])("No such file exists!");
}
let tRes = destServer.writeToTextFile(txtFile.fn, txtFile.text);
if (!tRes.success) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("scp failed");
return;
}
if (tRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwriten`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
return;
} // Get the current script
let sourceScript = null;
for (let i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
sourceScript = currServ.scripts[i];
break;
}
}
if (sourceScript == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("scp() failed. No such script exists");
return;
}
let sRes = destServer.writeToScriptFile(scriptname, sourceScript.code);
if (!sRes.success) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`scp failed`);
return;
}
if (sRes.overwritten) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwritten`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${scriptname} overwritten on ${destServer.hostname}`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${scriptname} copied over to ${destServer.hostname}`);
} catch (e) {
Terminal.postThrownError(e);
}
},
// First called when the "run [program]" command is called. Checks to see if you
// have the executable and, if you do, calls the executeProgram() function
runProgram: function (commandArray) {
if (commandArray.length < 2) {
return;
} // Check if you have the program on your computer. If you do, execute it, otherwise
// display an error message
const programName = commandArray[1];
if (_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hasProgram(programName)) {
Terminal.executeProgram(commandArray);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)");
},
// Contains the implementations of all possible programs
executeProgram: function (commandArray) {
if (commandArray.length < 2) {
return;
}
var s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const programName = commandArray[1];
const splitArgs = commandArray.slice(1); // TODO: refactor this/these out of Terminal. This logic could reside closer to the Programs themselves.
/**
* @typedef {function (server=, args=)} ProgramHandler
* @param {Server} server The current server the program is being executed against
* @param {string[]} args The command line arguments passed in to the program
* @returns {void}
*/
/**
* @type {Object. {
if (server.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["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_22__["Player"].getCurrentServer().numOpenPortsRequired) {
server.hasAdminRights = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("NUKE successful! Gained root access to " + _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer().hostname); // TODO: Make this take time rather than be instant
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("NUKE unsuccessful. Not enough ports have been opened");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].BruteSSHProgram.name] = server => {
if (server.sshPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SSH Port (22) is already open!");
return;
}
server.sshPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Opened SSH Port(22)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].FTPCrackProgram.name] = server => {
if (server.ftpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("FTP Port (21) is already open!");
return;
}
server.ftpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Opened FTP Port (21)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].RelaySMTPProgram.name] = server => {
if (server.smtpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SMTP Port (25) is already open!");
return;
}
server.smtpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Opened SMTP Port (25)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].HTTPWormProgram.name] = server => {
if (server.httpPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("HTTP Port (80) is already open!");
return;
}
server.httpPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Opened HTTP Port (80)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].SQLInjectProgram.name] = server => {
if (server.sqlPortOpen) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("SQL Port (1433) is already open!");
return;
}
server.sqlPortOpen = true;
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Opened SQL Port (1433)!");
server.openPortCount++;
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].ServerProfiler.name] = (server, args) => {
if (args.length !== 2) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Must pass a server hostname or IP as an argument for ServerProfiler.exe");
return;
}
const targetServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_30__["getServer"])(args[1]);
if (targetServer == null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Invalid server IP/hostname");
return;
}
if (targetServer instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_14__["HacknetServer"]) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`${_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].ServerProfiler.name} cannot be run on a Hacknet Server.`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(targetServer.hostname + ":");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Server base security level: " + targetServer.baseDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Server current security level: " + targetServer.hackDifficulty);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Server growth rate: " + targetServer.serverGrowth);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Netscript hack() execution time: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["convertTimeMsToTimeElapsedString"])(Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateHackingTime"])(targetServer, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) * 1000, true)}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Netscript grow() execution time: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["convertTimeMsToTimeElapsedString"])(Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateGrowTime"])(targetServer, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) * 1000, true)}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Netscript weaken() execution time: ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_41__["convertTimeMsToTimeElapsedString"])(Object(_Hacking__WEBPACK_IMPORTED_MODULE_13__["calculateWeakenTime"])(targetServer, _Player__WEBPACK_IMPORTED_MODULE_22__["Player"]) * 1000, true)}`);
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].AutoLink.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("When using scan-analyze, click on a server's hostname to connect to it.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].DeepscanV1.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].DeepscanV2.name] = () => {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("This executable cannot be run.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10.");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].Flight.name] = () => {
const numAugReq = Math.round(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_6__["BitNodeMultipliers"].DaedalusAugsRequirement * 30);
const fulfilled = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].augmentations.length >= numAugReq && _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].money.gt(1e11) && _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hacking_skill >= 2500;
if (!fulfilled) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Augmentations: ${_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].augmentations.length} / ${numAugReq}`);
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postElement"])(react__WEBPACK_IMPORTED_MODULE_47___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_47___default.a.Fragment, null, "Money: ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_42__["Money"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].money.toNumber()), " / ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_42__["Money"])(1e11)));
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Hacking skill: ${_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].hacking_skill} / 2500`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("We will contact you.");
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("-- Daedalus --");
};
programHandlers[_Programs_Programs__WEBPACK_IMPORTED_MODULE_9__["Programs"].BitFlume.name] = () => {
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__["yesNoBoxGetYesButton"])();
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__["yesNoBoxGetNoButton"])();
yesBtn.innerHTML = "Travel to BitNode Nexus";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function () {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_23__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_22__["Player"].bitNodeN, true);
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__["yesNoBoxClose"])();
});
noBtn.addEventListener("click", function () {
return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__["yesNoBoxClose"])();
});
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_39__["yesNoBoxCreate"])("WARNING: USING THIS PROGRAM WILL CAUSE YOU TO LOSE ALL OF YOUR PROGRESS ON THE CURRENT BITNODE.
" + "Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " + "and select a new one.");
};
if (!programHandlers.hasOwnProperty(programName)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Invalid executable. Cannot be run");
return;
}
programHandlers[programName](s, splitArgs);
},
/**
* Given a filename, returns that file's full path. This takes into account
* the Terminal's current directory.
*/
getFilepath: function (filename) {
const path = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["evaluateFilePath"])(filename, Terminal.currDir);
if (path == null) {
throw new Error(`Invalid file path specified: ${filename}`);
}
if (Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["isInRootDirectory"])(path)) {
return Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_0__["removeLeadingSlash"])(path);
}
return path;
},
/**
* Given a filename, searches and returns that file. File-type agnostic
*/
getFile: function (filename) {
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_28__["isScriptFilename"])(filename)) {
return Terminal.getScript(filename);
}
if (filename.endsWith(".lit")) {
return Terminal.getLitFile(filename);
}
if (filename.endsWith(".txt")) {
return Terminal.getTextFile(filename);
}
return null;
},
/**
* Processes a file path referring to a literature file, taking into account the terminal's
* current directory + server. Returns the lit file if it exists, and null otherwise
*/
getLitFile: function (filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const lit of s.messages) {
if (typeof lit === "string" && filepath === lit) {
return lit;
}
}
return null;
},
/**
* Processes a file path referring to a script, taking into account the terminal's
* current directory + server. Returns the script if it exists, and null otherwise.
*/
getScript: function (filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const script of s.scripts) {
if (filepath === script.filename) {
return script;
}
}
return null;
},
/**
* Processes a file path referring to a text file, taking into account the terminal's
* current directory + server. Returns the text file if it exists, and null otherwise.
*/
getTextFile: function (filename) {
const s = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const filepath = Terminal.getFilepath(filename);
for (const txt of s.textFiles) {
if (filepath === txt.fn) {
return txt;
}
}
return null;
},
postThrownError: function (e) {
if (e instanceof Error) {
const errorLabel = "Error: ";
const errorString = e.toString();
if (errorString.startsWith(errorLabel)) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(errorString.slice(errorLabel.length));
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(errorString);
}
}
},
runScript: function (commandArray) {
if (commandArray.length < 2) {
dialogBoxCreate(`Bug encountered with Terminal.runScript(). Command array has a length of less than 2: ${commandArray}`);
return;
}
const server = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const scriptName = Terminal.getFilepath(commandArray[1]);
const runArgs = {
'--tail': Boolean,
'-t': Number
};
const flags = arg__WEBPACK_IMPORTED_MODULE_46__(runArgs, {
permissive: true,
argv: commandArray.slice(2)
});
const threadFlag = Math.round(parseFloat(flags['-t']));
const tailFlag = flags['--tail'] === true;
if (flags['-t'] !== undefined && (threadFlag < 0 || isNaN(threadFlag))) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])("Invalid number of threads specified. Number of threads must be greater than 0");
return;
}
const numThreads = !isNaN(threadFlag) && threadFlag > 0 ? threadFlag : 1;
const args = flags['_']; // Check if this script is already running
if (Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_27__[/* findRunningScript */ "a"])(scriptName, args, server) != null) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("ERROR: This script is already running. Cannot run multiple instances");
return;
} // Check if the script exists and if it does run it
for (let i = 0; i < server.scripts.length; i++) {
if (server.scripts[i].filename !== scriptName) {
continue;
} // Check for admin rights and that there is enough RAM availble to run
const script = server.scripts[i];
const ramUsage = script.ramUsage * numThreads;
const ramAvailable = server.maxRam - server.ramUsed;
if (!server.hasAdminRights) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Need root access to run script");
return;
}
if (ramUsage > ramAvailable) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("This machine does not have enough RAM to run this script with " + numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
return;
} // Able to run script
const runningScript = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_24__["RunningScript"](script, args);
runningScript.threads = numThreads;
const success = Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_19__[/* startWorkerScript */ "e"])(runningScript, server);
if (!success) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["postError"])(`Failed to start script`);
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Running script with ${numThreads} thread(s), pid ${runningScript.pid} and args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_36__["arrayToString"])(args)}.`);
if (tailFlag) {
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_38__["logBoxCreate"])(runningScript);
}
return;
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["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_40__["post"])("ERROR: There's already a Coding Contract in Progress");
}
const serv = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].getCurrentServer();
const contract = serv.getContract(contractName);
if (contract == null) {
return Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("ERROR: No such contract");
}
Terminal.contractOpen = true;
const res = await contract.prompt();
switch (res) {
case _CodingContracts__WEBPACK_IMPORTED_MODULE_7__["CodingContractResult"].Success:
var reward = _Player__WEBPACK_IMPORTED_MODULE_22__["Player"].gainCodingContractReward(contract.reward, contract.getDifficulty());
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Contract SUCCESS - ${reward}`);
serv.removeContract(contract);
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_7__["CodingContractResult"].Failure:
++contract.tries;
if (contract.tries >= contract.getMaxNumTries()) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Contract
FAILED
- Contract is now self-destructing");
serv.removeContract(contract);
} else {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])(`Contract
FAILED
- ${contract.getMaxNumTries() - contract.tries} tries remaining`);
}
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_7__["CodingContractResult"].Cancelled:
default:
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_40__["post"])("Contract cancelled");
break;
}
Terminal.contractOpen = false;
}
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 75 */,
/* 76 */
/*!************************************!*\
!*** ./src/utils/SetTimeoutRef.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setTimeoutRef = void 0;
// This is a reference to the native setTimeout() function
// setTimeout() is used in various places around the game's source code.
// This reference is used to make sure that if players alter window.setTimeout()
// through NetscriptJS, then the game will still function properly
exports.setTimeoutRef = window.setTimeout.bind(window);
/***/ }),
/* 77 */,
/* 78 */
/*!**************************************!*\
!*** ./src/Hacknet/HacknetServer.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HacknetServer = void 0;
/**
* Hacknet Servers - Reworked Hacknet Node mechanic for BitNode-9
*/
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const BaseServer_1 = __webpack_require__(/*! ../Server/BaseServer */ 680);
const Constants_2 = __webpack_require__(/*! ./data/Constants */ 34);
const HacknetServers_1 = __webpack_require__(/*! ./formulas/HacknetServers */ 139);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 399);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class HacknetServer extends BaseServer_1.BaseServer {
constructor(params = { hostname: "", ip: IPAddress_1.createRandomIp() }) {
super(params);
// Cache level. Affects hash Capacity
this.cache = 1;
// Number of cores. Improves hash production
this.cores = 1;
// Number of hashes that can be stored by this Hacknet Server
this.hashCapacity = 0;
// Hashes produced per second
this.hashRate = 0;
// Similar to Node level. Improves hash production
this.level = 1;
// How long this HacknetServer has existed, in seconds
this.onlineTimeSeconds = 0;
// Total number of hashes earned by this server
this.totalHashesGenerated = 0;
this.maxRam = 1;
this.updateHashCapacity();
}
calculateCacheUpgradeCost(levels) {
return HacknetServers_1.calculateCacheUpgradeCost(this.cache, levels);
}
calculateCoreUpgradeCost(levels, costMult) {
return HacknetServers_1.calculateCoreUpgradeCost(this.cores, levels, costMult);
}
calculateLevelUpgradeCost(levels, costMult) {
return HacknetServers_1.calculateLevelUpgradeCost(this.level, levels, costMult);
}
calculateRamUpgradeCost(levels, costMult) {
return HacknetServers_1.calculateRamUpgradeCost(this.maxRam, levels, costMult);
}
// Process this Hacknet Server in the game loop. Returns the number of hashes generated
process(numCycles = 1) {
const seconds = numCycles * Constants_1.CONSTANTS.MilliPerCycle / 1000;
return this.hashRate * seconds;
}
upgradeCache(levels) {
this.cache = Math.min(Constants_2.HacknetServerConstants.MaxCache, Math.round(this.cache + levels));
this.updateHashCapacity();
}
upgradeCore(levels, prodMult) {
this.cores = Math.min(Constants_2.HacknetServerConstants.MaxCores, Math.round(this.cores + levels));
this.updateHashRate(prodMult);
}
upgradeLevel(levels, prodMult) {
this.level = Math.min(Constants_2.HacknetServerConstants.MaxLevel, Math.round(this.level + levels));
this.updateHashRate(prodMult);
}
upgradeRam(levels, prodMult) {
for (let i = 0; i < levels; ++i) {
this.maxRam *= 2;
}
this.maxRam = Math.min(Constants_2.HacknetServerConstants.MaxRam, Math.round(this.maxRam));
this.updateHashRate(prodMult);
return true;
}
// Whenever a script is run, we must update this server's hash rate
runScript(script, prodMult) {
super.runScript(script);
if (prodMult != null && typeof prodMult === "number") {
this.updateHashRate(prodMult);
}
}
updateHashCapacity() {
this.hashCapacity = 32 * Math.pow(2, this.cache);
}
updateHashRate(prodMult) {
this.hashRate = HacknetServers_1.calculateHashGainRate(this.level, this.ramUsed, this.maxRam, this.cores, prodMult);
if (isNaN(this.hashRate)) {
this.hashRate = 0;
console.error(`Error calculating Hacknet Server hash production. This is a bug. Please report to game dev`, false);
}
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("HacknetServer", this);
}
// Initializes a HacknetServer Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(HacknetServer, value.data);
}
}
exports.HacknetServer = HacknetServer;
JSONReviver_1.Reviver.constructors.HacknetServer = HacknetServer;
/***/ }),
/* 79 */
/*!**************************************************!*\
!*** ./src/Augmentation/AugmentationHelpers.jsx ***!
\**************************************************/
/*! exports provided: displayAugmentationsContent, isRepeatableAug, installAugmentations, initAugmentations, applyAugmentation, augmentationExists */
/*! exports used: applyAugmentation, augmentationExists, displayAugmentationsContent, initAugmentations, installAugmentations, isRepeatableAug */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayAugmentationsContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isRepeatableAug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return installAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return augmentationExists; });
/* harmony import */ var _Augmentation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentation */ 16);
/* harmony import */ var _Augmentation__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations */ 12);
/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentations__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PlayerOwnedAugmentation */ 196);
/* harmony import */ var _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./data/AugmentationNames */ 4);
/* harmony import */ var _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ui/Root */ 795);
/* harmony import */ var _ui_Root__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_ui_Root__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Prestige */ 173);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../SaveObject */ 114);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _ExportBonus__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../ExportBonus */ 150);
/* harmony import */ var _ExportBonus__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_ExportBonus__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../utils/helpers/clearObject */ 768);
/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Casino_RNG__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Casino/RNG */ 283);
/* harmony import */ var _Casino_RNG__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Casino_RNG__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_19__);
function AddToAugmentations(aug) {
var name = aug.name;
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name] = aug;
}
function getRandomBonus() {
var bonuses = [{
bonuses: {
hacking_chance_mult: 1.25,
hacking_speed_mult: 1.10,
hacking_money_mult: 1.25,
hacking_grow_mult: 1.1
},
description: "Increases the player's hacking chance by 25%. " + "Increases the player's hacking speed by 10%. " + "Increases the amount of money the player's gains from hacking by 25%. " + "Improves grow() by 10%."
}, {
bonuses: {
hacking_mult: 1.15,
hacking_exp_mult: 2
},
description: "Increases the player's hacking skill by 15%. " + "Increases the player's hacking experience gain rate by 100%."
}, {
bonuses: {
strength_mult: 1.25,
strength_exp_mult: 2,
defense_mult: 1.25,
defense_exp_mult: 2,
dexterity_mult: 1.25,
dexterity_exp_mult: 2,
agility_mult: 1.25,
agility_exp_mult: 2
},
description: "Increases all of the player's combat stats by 25%. " + "Increases all of the player's combat stat experience gain rate by 100%."
}, {
bonuses: {
charisma_mult: 1.5,
charisma_exp_mult: 2
},
description: "This augmentation increases the player's charisma by 50%. " + "Increases the player's charisma experience gain rate by 100%."
}, {
bonuses: {
hacknet_node_money_mult: 1.2,
hacknet_node_purchase_cost_mult: 0.85,
hacknet_node_ram_cost_mult: 0.85,
hacknet_node_core_cost_mult: 0.85,
hacknet_node_level_cost_mult: 0.85
},
description: "Increases the amount of money produced by Hacknet Nodes by 20%. " + "Decreases all costs related to Hacknet Node by 15%."
}, {
bonuses: {
company_rep_mult: 1.25,
faction_rep_mult: 1.15,
work_money_mult: 1.7
},
description: "Increases the amount of money the player gains from working by 70%. " + "Increases the amount of reputation the player gains when working for a company by 25%. " + "Increases the amount of reputation the player gains for a faction by 15%."
}, {
bonuses: {
crime_success_mult: 2,
crime_money_mult: 2
},
description: "Increases the player's crime success rate by 100%. " + "Increases the amount of money the player gains from crimes by 100%."
}];
const randomNumber = new _Casino_RNG__WEBPACK_IMPORTED_MODULE_17__["WHRNG"](Math.floor(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].lastUpdate / 3600000));
for (let i = 0; i < 5; i++) randomNumber.step();
return bonuses[Math.floor(bonuses.length * randomNumber.random())];
}
function initAugmentations() {
for (var name in _Faction_Factions__WEBPACK_IMPORTED_MODULE_7__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_7__["Factions"].hasOwnProperty(name)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_7__["Factions"][name].augmentations = [];
}
} //Reset Augmentations
Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16__["clearObject"])(_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"]); //Time-Based Augment Test
const randomBonuses = getRandomBonus();
const UnstableCircadianModulatorParams = {
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].UnstableCircadianModulator,
moneyCost: 5e9,
repCost: 3.625e5,
info: "An experimental nanobot injection. Its unstable nature leads to " + "unpredictable results based on your circadian rhythm."
};
Object.keys(randomBonuses.bonuses).forEach(key => UnstableCircadianModulatorParams[key] = randomBonuses.bonuses[key]);
const UnstableCircadianModulator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"](UnstableCircadianModulatorParams);
UnstableCircadianModulator.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].UnstableCircadianModulator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].UnstableCircadianModulator];
}
AddToAugmentations(UnstableCircadianModulator); //Combat stat augmentations
const HemoRecirculator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator,
moneyCost: 4.5e7,
repCost: 1e4,
info: "A heart implant that greatly increases the body's ability to effectively use and pump " + "blood.",
strength_mult: 1.08,
defense_mult: 1.08,
agility_mult: 1.08,
dexterity_mult: 1.08
});
HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HemoRecirculator];
}
AddToAugmentations(HemoRecirculator);
const Targeting1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1,
moneyCost: 1.5e7,
repCost: 5e3,
info: "A cranial implant that is embedded within the inner ear structures and optic nerves. It regulates " + "and enhances balance and hand-eye coordination.",
dexterity_mult: 1.1
});
Targeting1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Ishima", "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1];
}
AddToAugmentations(Targeting1);
const Targeting2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2,
moneyCost: 4.25e7,
repCost: 8.75e3,
info: "This upgraded version of the 'Augmented Targeting' implant is capable of augmenting " + "reality by digitally displaying weaknesses and vital signs of threats.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting1],
dexterity_mult: 1.2
});
Targeting2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2];
}
AddToAugmentations(Targeting2);
const Targeting3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3,
moneyCost: 1.15e8,
repCost: 2.75e4,
info: "The latest version of the 'Augmented Targeting' implant adds the ability to " + "lock-on and track threats.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting2],
dexterity_mult: 1.3
});
Targeting3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated", "KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Targeting3];
}
AddToAugmentations(Targeting3);
const SyntheticHeart = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart,
moneyCost: 2.875e9,
repCost: 7.5e5,
info: "This advanced artificial heart, created from plasteel and graphene, is capable of pumping blood " + "more efficiently than an organic heart.",
agility_mult: 1.5,
strength_mult: 1.5
});
SyntheticHeart.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead", "NWO", "The Covenant", "Daedalus", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SyntheticHeart];
}
AddToAugmentations(SyntheticHeart);
const SynfibrilMuscle = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle,
repCost: 4.375e5,
moneyCost: 1.125e9,
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'.",
strength_mult: 1.3,
defense_mult: 1.3
});
SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead", "NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynfibrilMuscle];
}
AddToAugmentations(SynfibrilMuscle);
const CombatRib1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1,
repCost: 7.5e3,
moneyCost: 2.375e7,
info: "The rib cage is augmented to continuously release boosters into the bloodstream " + "which increase the oxygen-carrying capacity of blood.",
strength_mult: 1.1,
defense_mult: 1.1
});
CombatRib1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Volhaven", "Ishima", "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1];
}
AddToAugmentations(CombatRib1);
const CombatRib2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2,
repCost: 1.875e4,
moneyCost: 6.5e7,
info: "An upgraded version of the 'Combat Rib' augmentation that adds potent stimulants which " + "improve focus and endurance while decreasing reaction time and fatigue.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib1],
strength_mult: 1.14,
defense_mult: 1.14
});
CombatRib2.addToFactions(["The Dark Army", "The Syndicate", "Volhaven", "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2];
}
AddToAugmentations(CombatRib2);
const CombatRib3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3,
repCost: 3.5e4,
moneyCost: 1.2e8,
info: "The latest version of the 'Combat Rib' augmentation releases advanced anabolic steroids that " + "improve muscle mass and physical performance while being safe and free of side effects.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib2],
strength_mult: 1.18,
defense_mult: 1.18
});
CombatRib3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated", "KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CombatRib3];
}
AddToAugmentations(CombatRib3);
const NanofiberWeave = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave,
repCost: 3.75e4,
moneyCost: 1.25e8,
info: "Synthetic nanofibers are woven into the skin's extracellular matrix using electrospinning, " + "which improves its regenerative and extracellular homeostasis abilities.",
strength_mult: 1.2,
defense_mult: 1.2
});
NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead", "Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NanofiberWeave];
}
AddToAugmentations(NanofiberWeave);
const SubdermalArmor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor,
repCost: 8.75e5,
moneyCost: 3.25e9,
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 or electrical traumas.",
defense_mult: 2.2
});
SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SubdermalArmor];
}
AddToAugmentations(SubdermalArmor);
const WiredReflexes = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes,
repCost: 1.25e3,
moneyCost: 2.5e6,
info: "Synthetic nerve-enhancements are injected into all major parts of the somatic nervous system, " + "supercharging the spread of neural signals and increasing reflex speed.",
agility_mult: 1.05,
dexterity_mult: 1.05
});
WiredReflexes.addToFactions(["Tian Di Hui", "Slum Snakes", "Sector-12", "Volhaven", "Aevum", "Ishima", "The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].WiredReflexes];
}
AddToAugmentations(WiredReflexes);
const GrapheneBoneLacings = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings,
repCost: 1.125e6,
moneyCost: 4.25e9,
info: "Graphene is grafted and fused into the skeletal structure, " + "enhancing bone density and tensile strength.",
strength_mult: 1.7,
defense_mult: 1.7
});
GrapheneBoneLacings.addToFactions(["Fulcrum Secret Technologies", "The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBoneLacings];
}
AddToAugmentations(GrapheneBoneLacings);
const BionicSpine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine,
repCost: 4.5e4,
moneyCost: 1.25e8,
info: "The spine is reconstructed using plasteel and carbon fibers. " + "It is now capable of stimulating and regulating neural signals " + "passing through the spinal cord, improving senses and reaction speed. " + "The 'Bionic Spine' also interfaces with all other 'Bionic' implants.",
strength_mult: 1.15,
defense_mult: 1.15,
agility_mult: 1.15,
dexterity_mult: 1.15
});
BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International", "OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine];
}
AddToAugmentations(BionicSpine);
const GrapheneBionicSpine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine,
repCost: 1.625e6,
moneyCost: 6e9,
info: "An upgrade to the 'Bionic Spine' augmentation. The spine is fused with graphene " + "which enhances durability and supercharges all body functions.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicSpine],
strength_mult: 1.6,
defense_mult: 1.6,
agility_mult: 1.6,
dexterity_mult: 1.6
});
GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicSpine];
}
AddToAugmentations(GrapheneBionicSpine);
const BionicLegs = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs,
repCost: 1.5e5,
moneyCost: 3.75e8,
info: "Cybernetic legs, created from plasteel and carbon fibers, enhance running speed.",
agility_mult: 1.6
});
BionicLegs.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International", "OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs];
}
AddToAugmentations(BionicLegs);
const GrapheneBionicLegs = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs,
repCost: 7.5e5,
moneyCost: 4.5e9,
info: "An upgrade to the 'Bionic Legs' augmentation. The legs are fused " + "with graphene, greatly enhancing jumping ability.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicLegs],
agility_mult: 2.5
});
GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicLegs];
}
AddToAugmentations(GrapheneBionicLegs); // Work stat augmentations
const SpeechProcessor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor,
repCost: 7.5e3,
moneyCost: 5e7,
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.",
charisma_mult: 1.2
});
SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum", "Ishima", "Volhaven", "Silhouette"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechProcessor];
}
AddToAugmentations(SpeechProcessor);
const TITN41Injection = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection,
repCost: 2.5e4,
moneyCost: 1.9e8,
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.",
charisma_mult: 1.15,
charisma_exp_mult: 1.15
});
TITN41Injection.addToFactions(["Silhouette"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TITN41Injection];
}
AddToAugmentations(TITN41Injection);
const EnhancedSocialInteractionImplant = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant,
repCost: 3.75e5,
moneyCost: 1.375e9,
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 expressions, body " + "language, and the voice tone, and 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.",
charisma_mult: 1.6,
charisma_exp_mult: 1.6
});
EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated", "OmniTek Incorporated", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedSocialInteractionImplant];
}
AddToAugmentations(EnhancedSocialInteractionImplant); // Hacking augmentations
const BitWire = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire,
repCost: 3.75e3,
moneyCost: 1e7,
info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " + "capabilities.",
hacking_mult: 1.05
});
BitWire.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BitWire];
}
AddToAugmentations(BitWire);
const ArtificialBioNeuralNetwork = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork,
repCost: 2.75e5,
moneyCost: 3e9,
info: "A network consisting of millions of nanoprocessors is embedded into the brain. " + "The network is meant to mimic the way a biological brain solves a problem, with 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 the user to solve much more complex problems at a much faster rate.",
hacking_speed_mult: 1.03,
hacking_money_mult: 1.15,
hacking_mult: 1.12
});
ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialBioNeuralNetwork];
}
AddToAugmentations(ArtificialBioNeuralNetwork);
const ArtificialSynapticPotentiation = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation,
repCost: 6.25e3,
moneyCost: 8e7,
info: "The body is injected with a chemical that artificially induces synaptic potentiation, " + "otherwise known as the strengthening of synapses. This results in enhanced cognitive abilities.",
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.05,
hacking_exp_mult: 1.05
});
ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ArtificialSynapticPotentiation];
}
AddToAugmentations(ArtificialSynapticPotentiation);
const EnhancedMyelinSheathing = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing,
repCost: 1e5,
moneyCost: 1.375e9,
info: "Electrical signals are used to induce a new, artificial form of myelinogenesis 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.",
hacking_speed_mult: 1.03,
hacking_exp_mult: 1.1,
hacking_mult: 1.08
});
EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EnhancedMyelinSheathing];
}
AddToAugmentations(EnhancedMyelinSheathing);
const SynapticEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement,
repCost: 2e3,
moneyCost: 7.5e6,
info: "A small cranial implant that continuously uses weak electrical signals to stimulate the brain and " + "induce stronger synaptic activity. This improves the user's cognitive abilities.",
hacking_speed_mult: 1.03
});
SynapticEnhancement.addToFactions(["CyberSec", "Aevum"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SynapticEnhancement];
}
AddToAugmentations(SynapticEnhancement);
const NeuralRetentionEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement,
repCost: 2e4,
moneyCost: 2.5e8,
info: "Chemical injections are used to permanently alter and strengthen the brain's neuronal " + "circuits, strengthening the ability to retain information.",
hacking_exp_mult: 1.25
});
NeuralRetentionEnhancement.addToFactions(["NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralRetentionEnhancement];
}
AddToAugmentations(NeuralRetentionEnhancement);
const DataJack = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack,
repCost: 1.125e5,
moneyCost: 4.5e8,
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.",
hacking_money_mult: 1.25
});
DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DataJack];
}
AddToAugmentations(DataJack);
const ENM = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM,
repCost: 1.5e4,
moneyCost: 2.5e8,
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.",
hacking_mult: 1.08
});
ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM];
}
AddToAugmentations(ENM);
const ENMCore = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore,
repCost: 2.5e5,
moneyCost: 2.5e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_speed_mult: 1.03,
hacking_money_mult: 1.1,
hacking_chance_mult: 1.03,
hacking_exp_mult: 1.07,
hacking_mult: 1.07
});
ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore];
}
AddToAugmentations(ENMCore);
const ENMCoreV2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2,
repCost: 1e6,
moneyCost: 4.5e9,
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 information on " + "a network by re-routing traffic, spoofing IP addresses, and altering the data inside network " + "packets.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCore],
hacking_speed_mult: 1.05,
hacking_money_mult: 1.3,
hacking_chance_mult: 1.05,
hacking_exp_mult: 1.15,
hacking_mult: 1.08
});
ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Blade Industries", "OmniTek Incorporated", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2];
}
AddToAugmentations(ENMCoreV2);
const ENMCoreV3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3,
repCost: 1.75e6,
moneyCost: 7.5e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV2],
hacking_speed_mult: 1.05,
hacking_money_mult: 1.4,
hacking_chance_mult: 1.1,
hacking_exp_mult: 1.25,
hacking_mult: 1.1
});
ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMCoreV3];
}
AddToAugmentations(ENMCoreV3);
const ENMAnalyzeEngine = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine,
repCost: 6.25e5,
moneyCost: 6e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_speed_mult: 1.1
});
ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMAnalyzeEngine];
}
AddToAugmentations(ENMAnalyzeEngine);
const ENMDMA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA,
repCost: 1e6,
moneyCost: 7e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENM],
hacking_money_mult: 1.4,
hacking_chance_mult: 1.2
});
ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", "Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ENMDMA];
}
AddToAugmentations(ENMDMA);
const Neuralstimulator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator,
repCost: 5e4,
moneyCost: 3e9,
info: "A cranial implant that intelligently stimulates certain areas of the brain " + "in order to improve cognitive functions.",
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.1,
hacking_exp_mult: 1.12
});
Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", "Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuralstimulator];
}
AddToAugmentations(Neuralstimulator);
const NeuralAccelerator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator,
repCost: 2e5,
moneyCost: 1.75e9,
info: "A microprocessor that accelerates the processing " + "speed of biological neural networks. This is a cranial implant that is embedded inside the brain.",
hacking_mult: 1.1,
hacking_exp_mult: 1.15,
hacking_money_mult: 1.2
});
NeuralAccelerator.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuralAccelerator];
}
AddToAugmentations(NeuralAccelerator);
const CranialSignalProcessorsG1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1,
repCost: 1e4,
moneyCost: 7e7,
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.",
hacking_speed_mult: 1.01,
hacking_mult: 1.05
});
CranialSignalProcessorsG1.addToFactions(["CyberSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1];
}
AddToAugmentations(CranialSignalProcessorsG1);
const CranialSignalProcessorsG2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2,
repCost: 1.875e4,
moneyCost: 1.25e8,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG1],
hacking_speed_mult: 1.02,
hacking_chance_mult: 1.05,
hacking_mult: 1.07
});
CranialSignalProcessorsG2.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2];
}
AddToAugmentations(CranialSignalProcessorsG2);
const CranialSignalProcessorsG3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3,
repCost: 5e4,
moneyCost: 5.5e8,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG2],
hacking_speed_mult: 1.02,
hacking_money_mult: 1.15,
hacking_mult: 1.09
});
CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand", "BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3];
}
AddToAugmentations(CranialSignalProcessorsG3);
const CranialSignalProcessorsG4 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4,
repCost: 1.25e5,
moneyCost: 1.1e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG3],
hacking_speed_mult: 1.02,
hacking_money_mult: 1.2,
hacking_grow_mult: 1.25
});
CranialSignalProcessorsG4.addToFactions(["The Black Hand", "BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4];
}
AddToAugmentations(CranialSignalProcessorsG4);
const CranialSignalProcessorsG5 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5,
repCost: 2.5e5,
moneyCost: 2.25e9,
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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG4],
hacking_mult: 1.3,
hacking_money_mult: 1.25,
hacking_grow_mult: 1.75
});
CranialSignalProcessorsG5.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CranialSignalProcessorsG5];
}
AddToAugmentations(CranialSignalProcessorsG5);
const NeuronalDensification = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification,
repCost: 1.875e5,
moneyCost: 1.375e9,
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.",
hacking_mult: 1.15,
hacking_exp_mult: 1.1,
hacking_speed_mult: 1.03
});
NeuronalDensification.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuronalDensification];
}
AddToAugmentations(NeuronalDensification); // Work Augmentations
const NuoptimalInjectorImplant = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant,
repCost: 5e3,
moneyCost: 2e7,
info: "This torso implant automatically injects nootropic supplements into " + "the bloodstream to improve memory, increase focus, and provide other " + "cognitive enhancements.",
company_rep_mult: 1.2
});
NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NuoptimalInjectorImplant];
}
AddToAugmentations(NuoptimalInjectorImplant);
const SpeechEnhancement = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement,
repCost: 2.5e3,
moneyCost: 1.25e7,
info: "An advanced neural implant that improves your speaking abilities, making " + "you more convincing and likable in conversations and overall improving your " + "social interactions.",
company_rep_mult: 1.1,
charisma_mult: 1.1
});
SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International", "Clarke Incorporated", "Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SpeechEnhancement];
}
AddToAugmentations(SpeechEnhancement);
const FocusWire = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire,
repCost: 7.5e4,
moneyCost: 9e8,
info: "A cranial implant that stops procrastination by blocking specific neural pathways " + "in the brain.",
hacking_exp_mult: 1.05,
strength_exp_mult: 1.05,
defense_exp_mult: 1.05,
dexterity_exp_mult: 1.05,
agility_exp_mult: 1.05,
charisma_exp_mult: 1.05,
company_rep_mult: 1.1,
work_money_mult: 1.2
});
FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].FocusWire];
}
AddToAugmentations(FocusWire);
const PCDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI,
repCost: 3.75e5,
moneyCost: 3.75e9,
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.",
company_rep_mult: 1.3,
hacking_mult: 1.08
});
PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI];
}
AddToAugmentations(PCDNI);
const PCDNIOptimizer = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer,
repCost: 5e5,
moneyCost: 4.5e9,
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 a connected computer.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI],
company_rep_mult: 1.75,
hacking_mult: 1.1
});
PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNIOptimizer];
}
AddToAugmentations(PCDNIOptimizer);
const PCDNINeuralNetwork = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork,
repCost: 1.5e6,
moneyCost: 7.5e9,
info: "This is an additional installation that upgrades the functionality of the " + "PC Direct-Neural Interface augmentation. When connected to a computer, " + "The Neural Network upgrade allows the user to use their own brain's " + "processing power to aid the computer in computational tasks.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNI],
company_rep_mult: 2,
hacking_mult: 1.1,
hacking_speed_mult: 1.05
});
PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCDNINeuralNetwork];
}
AddToAugmentations(PCDNINeuralNetwork);
const ADRPheromone1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1,
repCost: 3.75e3,
moneyCost: 1.75e7,
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.",
company_rep_mult: 1.1,
faction_rep_mult: 1.1
});
ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone1];
}
AddToAugmentations(ADRPheromone1);
const ADRPheromone2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2,
repCost: 6.25e4,
moneyCost: 5.5e8,
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.",
company_rep_mult: 1.2,
faction_rep_mult: 1.2
});
ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ADRPheromone2];
}
AddToAugmentations(ADRPheromone2);
const ShadowsSimulacrum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum,
repCost: 3.75e4,
moneyCost: 4e8,
info: "A crude but functional matter phase-shifter module that is embedded " + "in the brainstem and cerebellum. This augmentation was developed by " + "criminal organizations and allows the user to project and control holographic " + "simulacrums within a large radius. These simulacrums are commonly used for " + "espionage and surveillance work.",
company_rep_mult: 1.15,
faction_rep_mult: 1.15
});
ShadowsSimulacrum.addToFactions(["The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].ShadowsSimulacrum];
}
AddToAugmentations(ShadowsSimulacrum); // HacknetNode Augmentations
const HacknetNodeCPUUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload,
repCost: 3.75e3,
moneyCost: 1.1e7,
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.",
hacknet_node_money_mult: 1.15,
hacknet_node_purchase_cost_mult: 0.85
});
HacknetNodeCPUUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCPUUpload];
}
AddToAugmentations(HacknetNodeCPUUpload);
const HacknetNodeCacheUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload,
repCost: 2.5e3,
moneyCost: 5.5e6,
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.",
hacknet_node_money_mult: 1.10,
hacknet_node_level_cost_mult: 0.85
});
HacknetNodeCacheUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCacheUpload];
}
AddToAugmentations(HacknetNodeCacheUpload);
const HacknetNodeNICUpload = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload,
repCost: 1.875e3,
moneyCost: 4.5e6,
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.",
hacknet_node_money_mult: 1.1,
hacknet_node_purchase_cost_mult: 0.9
});
HacknetNodeNICUpload.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeNICUpload];
}
AddToAugmentations(HacknetNodeNICUpload);
const HacknetNodeKernelDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI,
repCost: 7.5e3,
moneyCost: 4e7,
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 " + "electrochemical signals.",
hacknet_node_money_mult: 1.25
});
HacknetNodeKernelDNI.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeKernelDNI];
}
AddToAugmentations(HacknetNodeKernelDNI);
const HacknetNodeCoreDNI = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI,
repCost: 1.25e4,
moneyCost: 6e7,
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 " + "electrochemical signals.",
hacknet_node_money_mult: 1.45
});
HacknetNodeCoreDNI.addToFactions(["Netburners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HacknetNodeCoreDNI];
}
AddToAugmentations(HacknetNodeCoreDNI); //Misc/Hybrid augmentations
const NeuroFluxGovernor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor,
repCost: 1.25e3,
moneyCost: 3.75e6,
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.",
stats: react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_18___default.a.Fragment, null, "This special augmentation can be leveled up infinitely. Each level of this augmentation increases ALL multipliers by 1%, stacking multiplicatively."),
hacking_chance_mult: 1.01,
hacking_speed_mult: 1.01,
hacking_money_mult: 1.01,
hacking_grow_mult: 1.01,
hacking_mult: 1.01,
strength_mult: 1.01,
defense_mult: 1.01,
dexterity_mult: 1.01,
agility_mult: 1.01,
charisma_mult: 1.01,
hacking_exp_mult: 1.01,
strength_exp_mult: 1.01,
defense_exp_mult: 1.01,
dexterity_exp_mult: 1.01,
agility_exp_mult: 1.01,
charisma_exp_mult: 1.01,
company_rep_mult: 1.01,
faction_rep_mult: 1.01,
crime_money_mult: 1.01,
crime_success_mult: 1.01,
hacknet_node_money_mult: 1.01,
hacknet_node_purchase_cost_mult: 0.99,
hacknet_node_ram_cost_mult: 0.99,
hacknet_node_core_cost_mult: 0.99,
hacknet_node_level_cost_mult: 0.99,
work_money_mult: 1.01
}); // Set the Augmentation's level to the currently-installed level
let currLevel = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
currLevel = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].level;
}
}
NeuroFluxGovernor.level = currLevel; // To set the price/rep req of the NeuroFlux, we have to take into account NeuroFlux
// levels that are purchased but not yet installed
let nextLevel = currLevel;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
++nextLevel;
}
}
let mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel);
NeuroFluxGovernor.baseRepRequirement = 500 * mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__["BitNodeMultipliers"].AugmentationRepCost;
NeuroFluxGovernor.baseCost = 750e3 * mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_5__["BitNodeMultipliers"].AugmentationMoneyCost;
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor];
}
NeuroFluxGovernor.addToAllFactions();
AddToAugmentations(NeuroFluxGovernor);
const Neurotrainer1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1,
repCost: 1e3,
moneyCost: 4e6,
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.",
hacking_exp_mult: 1.1,
strength_exp_mult: 1.1,
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
agility_exp_mult: 1.1,
charisma_exp_mult: 1.1
});
Neurotrainer1.addToFactions(["CyberSec", "Aevum"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer1];
}
AddToAugmentations(Neurotrainer1);
const Neurotrainer2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2,
repCost: 1e4,
moneyCost: 4.5e7,
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.",
hacking_exp_mult: 1.15,
strength_exp_mult: 1.15,
defense_exp_mult: 1.15,
dexterity_exp_mult: 1.15,
agility_exp_mult: 1.15,
charisma_exp_mult: 1.15
});
Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer2];
}
AddToAugmentations(Neurotrainer2);
const Neurotrainer3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3,
repCost: 2.5e4,
moneyCost: 1.3e8,
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.",
hacking_exp_mult: 1.2,
strength_exp_mult: 1.2,
defense_exp_mult: 1.2,
dexterity_exp_mult: 1.2,
agility_exp_mult: 1.2,
charisma_exp_mult: 1.2
});
Neurotrainer3.addToFactions(["NWO", "Four Sigma"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurotrainer3];
}
AddToAugmentations(Neurotrainer3);
const Hypersight = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight,
repCost: 1.5e5,
moneyCost: 2.75e9,
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 walls, thus providing 'x-ray vision'-like capabilities.",
dexterity_mult: 1.4,
hacking_speed_mult: 1.03,
hacking_money_mult: 1.1
});
Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Hypersight];
}
AddToAugmentations(Hypersight);
const LuminCloaking1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1,
repCost: 1.5e3,
moneyCost: 5e6,
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 to the naked eye.",
agility_mult: 1.05,
crime_money_mult: 1.1
});
LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1];
}
AddToAugmentations(LuminCloaking1);
const LuminCloaking2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2,
repCost: 5e3,
moneyCost: 3e7,
info: "This is a more advanced version of the LuminCloaking-V1 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.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking1],
agility_mult: 1.1,
defense_mult: 1.1,
crime_money_mult: 1.25
});
LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].LuminCloaking2];
}
AddToAugmentations(LuminCloaking2);
const SmartSonar = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar,
repCost: 2.25e4,
moneyCost: 7.5e7,
info: "A cochlear implant that helps the player detect and locate enemies " + "using sound propagation.",
dexterity_mult: 1.1,
dexterity_exp_mult: 1.15,
crime_money_mult: 1.25
});
SmartSonar.addToFactions(["Slum Snakes"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartSonar];
}
AddToAugmentations(SmartSonar);
const PowerRecirculator = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator,
repCost: 2.5e4,
moneyCost: 1.8e8,
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.",
hacking_mult: 1.05,
strength_mult: 1.05,
defense_mult: 1.05,
dexterity_mult: 1.05,
agility_mult: 1.05,
charisma_mult: 1.05,
hacking_exp_mult: 1.1,
strength_exp_mult: 1.1,
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
agility_exp_mult: 1.1,
charisma_exp_mult: 1.1
});
PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PowerRecirculator];
}
AddToAugmentations(PowerRecirculator); // Unique AUGS (Each Faction gets one unique augmentation)
// Factions that already have unique augs up to this point:
// Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies,
// Silhouette
// Illuminati
const QLink = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink,
repCost: 1.875e6,
moneyCost: 2.5e13,
info: "A brain implant that wirelessly connects you to the Illuminati's " + "quantum supercomputer, allowing you to access and use its incredible " + "computing power.",
hacking_mult: 1.75,
hacking_speed_mult: 2,
hacking_chance_mult: 2.5,
hacking_money_mult: 4
});
QLink.addToFactions(["Illuminati"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].QLink];
}
AddToAugmentations(QLink); // Daedalus
const RedPill = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill,
repCost: 2.5e6,
moneyCost: 0e0,
info: "It's time to leave the cave.",
stats: react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_18___default.a.Fragment, null)
});
RedPill.addToFactions(["Daedalus"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheRedPill];
}
AddToAugmentations(RedPill); // Covenant
const SPTN97 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97,
repCost: 1.25e6,
moneyCost: 4.875e9,
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.",
strength_mult: 1.75,
defense_mult: 1.75,
dexterity_mult: 1.75,
agility_mult: 1.75,
hacking_mult: 1.15
});
SPTN97.addToFactions(["The Covenant"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SPTN97];
}
AddToAugmentations(SPTN97); // ECorp
const HiveMind = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind,
repCost: 1.5e6,
moneyCost: 5.5e9,
info: "A brain implant developed by ECorp. They do not reveal what " + "exactly the implant does, but they promise that it will greatly " + "enhance your abilities.",
hacking_grow_mult: 3,
stats: react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_18___default.a.Fragment, null)
});
HiveMind.addToFactions(["ECorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HiveMind];
}
AddToAugmentations(HiveMind); // MegaCorp
const CordiARCReactor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor,
repCost: 1.125e6,
moneyCost: 5e9,
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 amounts of clean " + "energy for the body.",
strength_mult: 1.35,
defense_mult: 1.35,
dexterity_mult: 1.35,
agility_mult: 1.35,
strength_exp_mult: 1.35,
defense_exp_mult: 1.35,
dexterity_exp_mult: 1.35,
agility_exp_mult: 1.35
});
CordiARCReactor.addToFactions(["MegaCorp"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CordiARCReactor];
}
AddToAugmentations(CordiARCReactor); // BachmanAndAssociates
const SmartJaw = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw,
repCost: 3.75e5,
moneyCost: 2.75e9,
info: "A bionic jaw that contains advanced hardware and software " + "capable of psychoanalyzing and profiling the personality of " + "others using optical imaging software.",
charisma_mult: 1.5,
charisma_exp_mult: 1.5,
company_rep_mult: 1.25,
faction_rep_mult: 1.25
});
SmartJaw.addToFactions(["Bachman & Associates"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SmartJaw];
}
AddToAugmentations(SmartJaw); // BladeIndustries
const Neotra = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra,
repCost: 5.625e5,
moneyCost: 2.875e9,
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.",
strength_mult: 1.55,
defense_mult: 1.55
});
Neotra.addToFactions(["Blade Industries"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neotra];
}
AddToAugmentations(Neotra); // NWO
const Xanipher = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher,
repCost: 8.75e5,
moneyCost: 4.25e9,
info: "A concoction of advanced nanobots that is orally ingested into the " + "body. These nanobots induce physiological changes and significantly " + "improve the body's functioning in all aspects.",
hacking_mult: 1.2,
strength_mult: 1.2,
defense_mult: 1.2,
dexterity_mult: 1.2,
agility_mult: 1.2,
charisma_mult: 1.2,
hacking_exp_mult: 1.15,
strength_exp_mult: 1.15,
defense_exp_mult: 1.15,
dexterity_exp_mult: 1.15,
agility_exp_mult: 1.15,
charisma_exp_mult: 1.15
});
Xanipher.addToFactions(["NWO"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Xanipher];
}
AddToAugmentations(Xanipher);
const HydroflameLeftArm = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HydroflameLeftArm,
repCost: 1.25e6,
moneyCost: 2.5e12,
info: "The left arm of a legendary BitRunner who ascended beyond this world. " + "It projects a light blue energy shield that protects the exposed inner parts. " + "Even though it contains no weapons, the advanced tungsten titanium " + "alloy increases the users strength to unbelievable levels. The augmentation " + "gets more powerful over time for seemingly no reason.",
strength_mult: 2.70
});
HydroflameLeftArm.addToFactions(["NWO"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HydroflameLeftArm)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HydroflameLeftArm];
}
AddToAugmentations(HydroflameLeftArm); // ClarkeIncorporated
const nextSENS = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS,
repCost: 4.375e5,
moneyCost: 1.925e9,
info: "The body is genetically re-engineered to maintain a state " + "of negligible senescence, preventing the body from " + "deteriorating with age.",
hacking_mult: 1.2,
strength_mult: 1.2,
defense_mult: 1.2,
dexterity_mult: 1.2,
agility_mult: 1.2,
charisma_mult: 1.2
});
nextSENS.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].nextSENS];
}
AddToAugmentations(nextSENS); // OmniTekIncorporated
const OmniTekInfoLoad = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad,
repCost: 6.25e5,
moneyCost: 2.875e9,
info: "OmniTek's data and information repository is uploaded " + "into your brain, enhancing your programming and " + "hacking abilities.",
hacking_mult: 1.2,
hacking_exp_mult: 1.25
});
OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OmniTekInfoLoad];
}
AddToAugmentations(OmniTekInfoLoad); // FourSigma
// TODO Later when Intelligence is added in . Some aug that greatly increases int
// KuaiGongInternational
const PhotosyntheticCells = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells,
repCost: 5.625e5,
moneyCost: 2.75e9,
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.",
strength_mult: 1.4,
defense_mult: 1.4,
agility_mult: 1.4
});
PhotosyntheticCells.addToFactions(["KuaiGong International"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PhotosyntheticCells];
}
AddToAugmentations(PhotosyntheticCells); // BitRunners
const Neurolink = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink,
repCost: 8.75e5,
moneyCost: 4.375e9,
info: "A brain implant that provides a high-bandwidth, direct neural link between your " + "mind and the BitRunners' data servers, which reportedly contain " + "the largest database of hacking tools and information in the world.",
hacking_mult: 1.15,
hacking_exp_mult: 1.2,
hacking_chance_mult: 1.1,
hacking_speed_mult: 1.05,
programs: [_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].FTPCrackProgram.name, _Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].RelaySMTPProgram.name]
});
Neurolink.addToFactions(["BitRunners"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neurolink];
}
AddToAugmentations(Neurolink); // BlackHand
const TheBlackHand = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand,
repCost: 1e5,
moneyCost: 5.5e8,
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 by just touching them.",
strength_mult: 1.15,
dexterity_mult: 1.15,
hacking_mult: 1.1,
hacking_speed_mult: 1.02,
hacking_money_mult: 1.1
});
TheBlackHand.addToFactions(["The Black Hand"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].TheBlackHand];
}
AddToAugmentations(TheBlackHand); // NiteSec
const CRTX42AA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA,
repCost: 4.5e4,
moneyCost: 2.25e8,
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.",
hacking_mult: 1.08,
hacking_exp_mult: 1.15
});
CRTX42AA.addToFactions(["NiteSec"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CRTX42AA];
}
AddToAugmentations(CRTX42AA); // Chongqing
const Neuregen = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen,
repCost: 3.75e4,
moneyCost: 3.75e8,
info: "A drug that genetically modifies the neurons in the brain " + "resulting in neurons never die, continuously " + "regenerate, and strengthen themselves.",
hacking_exp_mult: 1.4
});
Neuregen.addToFactions(["Chongqing"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].Neuregen];
}
AddToAugmentations(Neuregen); // Sector12
const CashRoot = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot,
repCost: 1.25e4,
moneyCost: 1.25e8,
info: react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_18___default.a.Fragment, null, "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."),
startingMoney: 1e6,
programs: [_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].BruteSSHProgram.name]
});
CashRoot.addToFactions(["Sector-12"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].CashRoot];
}
AddToAugmentations(CashRoot); // NewTokyo
const NutriGen = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen,
repCost: 6.25e3,
moneyCost: 2.5e6,
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.",
strength_exp_mult: 1.2,
defense_exp_mult: 1.2,
dexterity_exp_mult: 1.2,
agility_exp_mult: 1.2
});
NutriGen.addToFactions(["New Tokyo"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NutriGen];
}
AddToAugmentations(NutriGen); // Aevum
const PCMatrix = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCMatrix,
repCost: 100e3,
moneyCost: 2e9,
info: "A 'Probability Computation Matrix' is installed in the frontal cortex. This implant " + "uses advanced mathematical algorithims to rapidly identify and compute statistical " + "outcomes of nearly every situation.",
charisma_mult: 1.0777,
charisma_exp_mult: 1.0777,
work_money_mult: 1.777,
faction_rep_mult: 1.0777,
company_rep_mult: 1.0777,
crime_success_mult: 1.0777,
crime_money_mult: 1.0777,
programs: [_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].DeepscanV1.name, _Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].AutoLink.name]
});
PCMatrix.addToFactions(["Aevum"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCMatrix)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].PCMatrix];
}
AddToAugmentations(PCMatrix); // Ishima
const INFRARet = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet,
repCost: 7.5e3,
moneyCost: 3e7,
info: "A tiny chip that sits behind the retinae. This implant lets the" + "user visually detect infrared radiation.",
crime_success_mult: 1.25,
crime_money_mult: 1.1,
dexterity_mult: 1.1
});
INFRARet.addToFactions(["Ishima"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INFRARet];
}
AddToAugmentations(INFRARet); // Volhaven
const DermaForce = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce,
repCost: 1.5e4,
moneyCost: 5e7,
info: "Synthetic skin that is grafted onto the body. This skin consists of " + "millions of nanobots capable of projecting high-density muon beams, " + "creating an energy barrier around the user.",
defense_mult: 1.4
});
DermaForce.addToFactions(["Volhaven"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].DermaForce];
}
AddToAugmentations(DermaForce); // SpeakersForTheDead
const GrapheneBrachiBlades = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades,
repCost: 2.25e5,
moneyCost: 2.5e9,
info: "An upgrade to the BrachiBlades augmentation. It infuses " + "the retractable blades with an advanced graphene material " + "making them stronger and lighter.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades],
strength_mult: 1.4,
defense_mult: 1.4,
crime_success_mult: 1.1,
crime_money_mult: 1.3
});
GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBrachiBlades];
}
AddToAugmentations(GrapheneBrachiBlades); // DarkArmy
const GrapheneBionicArms = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms,
repCost: 5e5,
moneyCost: 3.75e9,
info: "An upgrade to the Bionic Arms augmentation. It infuses the " + "prosthetic arms with an advanced graphene material " + "to make them stronger and lighter.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms],
strength_mult: 1.85,
dexterity_mult: 1.85
});
GrapheneBionicArms.addToFactions(["The Dark Army"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GrapheneBionicArms];
}
AddToAugmentations(GrapheneBionicArms); // TheSyndicate
const BrachiBlades = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades,
repCost: 1.25e4,
moneyCost: 9e7,
info: "A set of retractable plasteel blades that are implanted in the arm, underneath the skin.",
strength_mult: 1.15,
defense_mult: 1.15,
crime_success_mult: 1.1,
crime_money_mult: 1.15
});
BrachiBlades.addToFactions(["The Syndicate"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BrachiBlades];
}
AddToAugmentations(BrachiBlades); // Tetrads
const BionicArms = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms,
repCost: 6.25e4,
moneyCost: 2.75e8,
info: "Cybernetic arms created from plasteel and carbon fibers that completely replace " + "the user's organic arms.",
strength_mult: 1.3,
dexterity_mult: 1.3
});
BionicArms.addToFactions(["Tetrads"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BionicArms];
}
AddToAugmentations(BionicArms); // TianDiHui
const SNA = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA,
repCost: 6.25e3,
moneyCost: 3e7,
info: "A cranial implant that affects the user's personality, making them better " + "at negotiation in social situations.",
work_money_mult: 1.1,
company_rep_mult: 1.15,
faction_rep_mult: 1.15
});
SNA.addToFactions(["Tian Di Hui"]);
if (augmentationExists(_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].SNA];
}
AddToAugmentations(SNA); // Special Bladeburner Augmentations
const BladeburnersFactionName = "Bladeburners";
if (Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_7__["factionExists"])(BladeburnersFactionName)) {
const EsperEyewear = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EsperEyewear,
repCost: 1.25e3,
moneyCost: 1.65e8,
info: "Ballistic-grade protective and retractable eyewear that was designed specifically " + "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, lasers, blinding flashes, and gas. It is also " + "embedded with a data processing chip that can be programmed to display an " + "AR HUD to assist the user in field missions.",
bladeburner_success_chance_mult: 1.03,
dexterity_mult: 1.05,
isSpecial: true
});
EsperEyewear.addToFactions([BladeburnersFactionName]);
resetAugmentation(EsperEyewear);
const EMS4Recombination = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].EMS4Recombination,
repCost: 2.5e3,
moneyCost: 2.75e8,
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, " + "improve reflexes, and improve memory among other things.",
bladeburner_success_chance_mult: 1.03,
bladeburner_analysis_mult: 1.05,
bladeburner_stamina_gain_mult: 1.02,
isSpecial: true
});
EMS4Recombination.addToFactions([BladeburnersFactionName]);
resetAugmentation(EMS4Recombination);
const OrionShoulder = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].OrionShoulder,
repCost: 6.25e3,
moneyCost: 5.5e8,
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.",
defense_mult: 1.05,
strength_mult: 1.05,
dexterity_mult: 1.05,
bladeburner_success_chance_mult: 1.04,
isSpecial: true
});
OrionShoulder.addToFactions([BladeburnersFactionName]);
resetAugmentation(OrionShoulder);
const HyperionV1 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV1,
repCost: 1.25e4,
moneyCost: 2.75e9,
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.",
bladeburner_success_chance_mult: 1.06,
isSpecial: true
});
HyperionV1.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV1);
const HyperionV2 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV2,
repCost: 2.5e4,
moneyCost: 5.5e9,
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-efficient, more accurate, and can fire plasma bolts at a much " + "higher velocity than the V1 model.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].HyperionV1],
bladeburner_success_chance_mult: 1.08,
isSpecial: true
});
HyperionV2.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV2);
const GolemSerum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].GolemSerum,
repCost: 3.125e4,
moneyCost: 1.1e10,
info: "A serum that permanently enhances many aspects of human capabilities, " + "including strength, speed, immune system enhancements, and mitochondrial efficiency. The " + "serum was originally developed by the Chinese military in an attempt to " + "create super soldiers.",
strength_mult: 1.07,
defense_mult: 1.07,
dexterity_mult: 1.07,
agility_mult: 1.07,
bladeburner_stamina_gain_mult: 1.05,
isSpecial: true
});
GolemSerum.addToFactions([BladeburnersFactionName]);
resetAugmentation(GolemSerum);
const VangelisVirus = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus,
repCost: 1.875e4,
moneyCost: 2.75e9,
info: "A synthetic symbiotic virus that is injected into human brain tissue. The Vangelis virus " + "heightens the senses and focus of its host, and also enhances its intuition.",
dexterity_exp_mult: 1.1,
bladeburner_analysis_mult: 1.1,
bladeburner_success_chance_mult: 1.04,
isSpecial: true
});
VangelisVirus.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus);
const VangelisVirus3 = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus3,
repCost: 3.75e4,
moneyCost: 1.1e10,
info: "An improved version of Vangelis, a synthetic symbiotic virus that is " + "injected into human brain tissue. On top of the benefits of the original " + "virus, this also grants an accelerated healing factor and enhanced " + "reflexes.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].VangelisVirus],
defense_exp_mult: 1.1,
dexterity_exp_mult: 1.1,
bladeburner_analysis_mult: 1.15,
bladeburner_success_chance_mult: 1.05,
isSpecial: true
});
VangelisVirus3.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus3);
const INTERLINKED = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].INTERLINKED,
repCost: 2.5e4,
moneyCost: 5.5e9,
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.",
strength_exp_mult: 1.05,
defense_exp_mult: 1.05,
dexterity_exp_mult: 1.05,
agility_exp_mult: 1.05,
bladeburner_max_stamina_mult: 1.1,
isSpecial: true
});
INTERLINKED.addToFactions([BladeburnersFactionName]);
resetAugmentation(INTERLINKED);
const BladeRunner = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeRunner,
repCost: 2e4,
moneyCost: 8.25e9,
info: "A cybernetic foot augmentation that was specifically 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.",
agility_mult: 1.05,
bladeburner_max_stamina_mult: 1.05,
bladeburner_stamina_gain_mult: 1.05,
isSpecial: true
});
BladeRunner.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeRunner);
const BladeArmor = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor,
repCost: 1.25e4,
moneyCost: 1.375e9,
info: "A powered exoskeleton suit 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 " + "physical abilities.",
strength_mult: 1.04,
defense_mult: 1.04,
dexterity_mult: 1.04,
agility_mult: 1.04,
bladeburner_stamina_gain_mult: 1.02,
bladeburner_success_chance_mult: 1.03,
isSpecial: true
});
BladeArmor.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmor);
const BladeArmorPowerCells = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorPowerCells,
repCost: 1.875e4,
moneyCost: 2.75e9,
info: "Upgrades the BLADE-51b Tesla Armor with Ion Power Cells, which are capable of " + "more efficiently storing and using power.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_success_chance_mult: 1.05,
bladeburner_stamina_gain_mult: 1.02,
bladeburner_max_stamina_mult: 1.05,
isSpecial: true
});
BladeArmorPowerCells.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorPowerCells);
const BladeArmorEnergyShielding = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorEnergyShielding,
repCost: 2.125e4,
moneyCost: 5.5e9,
info: "Upgrades the BLADE-51b Tesla Armor with a plasma energy propulsion system " + "that is capable of projecting an energy shielding force field.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
defense_mult: 1.05,
bladeburner_success_chance_mult: 1.06,
isSpecial: true
});
BladeArmorEnergyShielding.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorEnergyShielding);
const BladeArmorUnibeam = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorUnibeam,
repCost: 3.125e4,
moneyCost: 1.65e10,
info: "Upgrades the BLADE-51b Tesla Armor with a concentrated deuterium-fluoride laser " + "weapon. It's precision and accuracy makes it useful for quickly neutralizing " + "threats while keeping casualties to a minimum.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_success_chance_mult: 1.08,
isSpecial: true
});
BladeArmorUnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorUnibeam);
const BladeArmorOmnibeam = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorOmnibeam,
repCost: 6.25e4,
moneyCost: 2.75e10,
info: "Upgrades the BLADE-51b Tesla Armor Unibeam augmentation to use a " + "multiple-fiber system. This upgraded weapon uses multiple fiber laser " + "modules that combine together to form a single, more powerful beam of up to " + "2000MW.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorUnibeam],
bladeburner_success_chance_mult: 1.1,
isSpecial: true
});
BladeArmorOmnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorOmnibeam);
const BladeArmorIPU = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmorIPU,
repCost: 1.5e4,
moneyCost: 1.1e9,
info: "Upgrades the BLADE-51b Tesla Armor with an AI Information Processing " + "Unit that was specially designed to analyze Synthoid related data and " + "information.",
prereqs: [_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladeArmor],
bladeburner_analysis_mult: 1.15,
bladeburner_success_chance_mult: 1.02,
isSpecial: true
});
BladeArmorIPU.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorIPU);
const BladesSimulacrum = new _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"]({
name: _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].BladesSimulacrum,
repCost: 1.25e3,
moneyCost: 1.5e11,
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 specifically " + "weaponized by Bladeburner units to be used against Synthoids.",
stats: react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_18___default.a.Fragment, null, "This augmentation allows you to perform Bladeburner actions and other actions (such as working, commiting crimes, etc.) at the same time."),
isSpecial: true
});
BladesSimulacrum.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladesSimulacrum);
} // Update costs based on how many have been purchased
mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_14__["SourceFileFlags"][11]], _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length);
for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"]) {
if (_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"].hasOwnProperty(name)) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name].baseCost *= mult;
}
}
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].reapplyAllAugmentations();
} //Resets an Augmentation during (re-initizliation)
function resetAugmentation(newAugObject) {
if (!(newAugObject instanceof _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"])) {
throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation");
}
var name = newAugObject.name;
if (augmentationExists(name)) {
delete _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name];
}
AddToAugmentations(newAugObject);
}
function applyAugmentation(aug, reapply = false) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name].owned = true;
const augObj = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name]; // Apply multipliers
for (const mult in augObj.mults) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"][mult] == null) {
console.warn(`Augmentation has unrecognized multiplier property: ${mult}`);
} else {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"][mult] *= augObj.mults[mult];
}
} // Special logic for NeuroFlux Governor
if (aug.name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
if (!reapply) {
_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][aug.name].level = aug.level;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].name == _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations[i].level = aug.level;
return; // break;
}
}
}
} // Push onto Player's Augmentation list
if (!reapply) {
var ownedAug = new _PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__["PlayerOwnedAugmentation"](aug.name);
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].augmentations.push(ownedAug);
}
}
function installAugmentations() {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length == 0) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("You have not purchased any Augmentations to install!");
return false;
}
let augmentationList = "";
let nfgIndex = -1;
for (let i = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length - 1; i >= 0; i--) {
if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i].name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
nfgIndex = i;
break;
}
}
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations.length; ++i) {
const ownedAug = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i];
const aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][ownedAug.name];
if (aug == null) {
console.error(`Invalid augmentation: ${ownedAug.name}`);
continue;
}
applyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations[i]);
if (ownedAug.name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor && i !== nfgIndex) continue;
let level = "";
if (ownedAug.name === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
level = ` - ${ownedAug.level}`;
}
augmentationList += aug.name + level + " ";
}
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].queuedAugmentations = [];
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " + "to install the following Augmentations: " + augmentationList + " You wake up in your home...you feel different...");
Object(_Prestige__WEBPACK_IMPORTED_MODULE_9__[/* prestigeAugmentation */ "a"])();
}
function augmentationExists(name) {
return _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"].hasOwnProperty(name);
}
function displayAugmentationsContent(contentEl) {
if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_11__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_11__["Page"].Augmentations)) {
return;
}
if (!(contentEl instanceof HTMLElement)) {
return;
}
function backup() {
_SaveObject__WEBPACK_IMPORTED_MODULE_10__[/* saveObject */ "b"].exportGame();
Object(_ExportBonus__WEBPACK_IMPORTED_MODULE_12__["onExport"])(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"]);
}
react_dom__WEBPACK_IMPORTED_MODULE_19___default.a.render(react__WEBPACK_IMPORTED_MODULE_18___default.a.createElement(_ui_Root__WEBPACK_IMPORTED_MODULE_4__["AugmentationsRoot"], {
exportGameFn: backup,
installAugmentationsFn: installAugmentations
}), contentEl);
}
function isRepeatableAug(aug) {
const augName = aug instanceof _Augmentation__WEBPACK_IMPORTED_MODULE_0__["Augmentation"] ? aug.name : aug;
if (augName === _data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
return true;
}
return false;
}
/***/ }),
/* 80 */
/*!********************************!*\
!*** ./src/NetscriptWorker.js ***!
\********************************/
/*! exports provided: NetscriptPorts, prestigeWorkerScripts, startWorkerScript, createAndAddWorkerScript, updateOnlineScriptTimes, loadAllRunningScripts, runScriptFromScript */
/*! exports used: NetscriptPorts, loadAllRunningScripts, prestigeWorkerScripts, runScriptFromScript, startWorkerScript, updateOnlineScriptTimes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return prestigeWorkerScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return startWorkerScript; });
/* unused harmony export createAndAddWorkerScript */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return updateOnlineScriptTimes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return loadAllRunningScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return runScriptFromScript; });
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Netscript/killWorkerScript */ 70);
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Netscript/WorkerScript */ 247);
/* harmony import */ var _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Netscript/WorkerScripts */ 112);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Netscript/WorkerScriptStartStopEventEmitter */ 147);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Netscript_Pid__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Netscript/Pid */ 302);
/* harmony import */ var _Netscript_Pid__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Netscript_Pid__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _JSInterpreter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./JSInterpreter */ 447);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./NetscriptEvaluator */ 68);
/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./NetscriptFunctions */ 446);
/* harmony import */ var _NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./NetscriptJSEvaluator */ 776);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptPort */ 154);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_NetscriptPort__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Script/RunningScript */ 194);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Script/RunningScriptHelpers */ 444);
/* harmony import */ var _Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 120);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! escodegen */ 457);
/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(escodegen__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 113);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 290);
/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var acorn__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! acorn */ 104);
/* harmony import */ var acorn_walk__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! acorn-walk */ 203);
/**
* Functions for handling WorkerScripts, which are the underlying mechanism
* that allows for scripts to run
*/
// Netscript Ports are instantiated here
const NetscriptPorts = [];
for (var i = 0; i < _Constants__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts; ++i) {
NetscriptPorts.push(new _NetscriptPort__WEBPACK_IMPORTED_MODULE_11__["NetscriptPort"]());
}
function prestigeWorkerScripts() {
for (const ws of _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__["workerScripts"].values()) {
ws.env.stopFlag = true;
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__["killWorkerScript"])(ws);
}
_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__["WorkerScriptStartStopEventEmitter"].emitEvent();
_Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__["workerScripts"].clear();
}
// 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_8__[/* makeRuntimeRejectMsg */ "b"])(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_10__[/* 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_8__[/* makeRuntimeRejectMsg */ "b"])(
workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || ""));
throw workerScript;
} else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__[/* isScriptErrorMessage */ "a"])(e)) {
workerScript.errorMessage = e;
throw workerScript;
}
throw e; // Don't know what to do with it, let's rethrow.
});
}
function startNetscript1Script(workerScript) {
const 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_20__["dialogBoxCreate"])("Error processing Imports in " + workerScript.name + ": " + e);
workerScript.env.stopFlag = true;
workerScript.running = false;
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__["killWorkerScript"])(workerScript);
return;
}
var interpreterInitialization = function(int, scope) {
//Add the Netscript environment
var ns = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_9__["NetscriptFunctions"])(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 === "manualHack") {
let tempWrapper = function() {
let fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns
for (let i = 0; i < arguments.length-1; ++i) {
if (typeof arguments[i] === 'object' || arguments[i].constructor === Array) {
fnArgs.push(int.pseudoToNative(arguments[i]));
} else {
fnArgs.push(arguments[i]);
}
}
let cb = arguments[arguments.length-1];
let fnPromise = entry.apply(null, fnArgs);
fnPromise.then(function(res) {
cb(res);
}).catch(function(err) {
console.error(err);
});
}
int.setProperty(scope, name, int.createAsyncFunction(tempWrapper));
} else if (name === "sprintf" || name === "vsprintf" || name === "scp" ||
name == "write" || name === "read" || name === "tryWrite" ||
name === "run" || name === "exec") {
let tempWrapper = function() {
let fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns
for (let i = 0; i < arguments.length; ++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_7__[/* Interpreter */ "a"](codeWithImports, interpreterInitialization, codeLineOffset);
} catch(e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__["dialogBoxCreate"])("Syntax ERROR in " + workerScript.name + ": " + e);
workerScript.env.stopFlag = true;
workerScript.running = false;
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__["killWorkerScript"])(workerScript);
return;
}
return new Promise(function(resolve, reject) {
function runInterpreter() {
try {
if (workerScript.env.stopFlag) { return reject(workerScript); }
if (interpreter.step()) {
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_18__["setTimeoutRef"])(runInterpreter, _Settings_Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].CodeInstructionRunTime);
} else {
resolve(workerScript);
}
} catch(e) {
e = e.toString();
if (!Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__[/* isScriptErrorMessage */ "a"])(e)) {
e = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__[/* makeRuntimeRejectMsg */ "b"])(workerScript, e);
}
workerScript.errorMessage = e;
return reject(workerScript);
}
}
try {
runInterpreter();
} catch(e) {
if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["isString"])(e)) {
workerScript.errorMessage = e;
return reject(workerScript);
} else if (e instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__["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
const ast = Object(acorn__WEBPACK_IMPORTED_MODULE_24__[/* parse */ "b"])(code, { ecmaVersion: 9, 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;
}
let generatedCode = ""; // Generated Javascript Code
let hasImports = false;
// Walk over the tree and process ImportDeclaration nodes
Object(acorn_walk__WEBPACK_IMPORTED_MODULE_25__[/* simple */ "b"])(ast, {
ImportDeclaration: (node) => {
hasImports = true;
let scriptName = node.source.value;
if (scriptName.startsWith("./")) {
scriptName = scriptName.slice(2);
}
let script = getScript(scriptName);
if (script == null) {
throw new Error("'Import' failed due to invalid script: " + scriptName);
}
let scriptAst = Object(acorn__WEBPACK_IMPORTED_MODULE_24__[/* parse */ "b"])(script.code, { ecmaVersion:9, 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
Object(acorn_walk__WEBPACK_IMPORTED_MODULE_25__[/* simple */ "b"])(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_19__["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 = [];
Object(acorn_walk__WEBPACK_IMPORTED_MODULE_25__[/* simple */ "b"])(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_19__["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_19__["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;
}
/**
* Used to start a RunningScript (by creating and starting its
* corresponding WorkerScript), and add the RunningScript to the server on which
* it is active
* @param {RunningScript} runningScriptObj - Script that's being run
* @param {Server} server - Server on which the script is to be run
* @returns {number} pid of started script
*/
function startWorkerScript(runningScript, server, parent) {
if (createAndAddWorkerScript(runningScript, server, parent)) {
// Push onto runningScripts.
// This has to come after createAndAddWorkerScript() because that fn updates RAM usage
server.runScript(runningScript, _Player__WEBPACK_IMPORTED_MODULE_12__["Player"].hacknet_node_money_mult);
// Once the WorkerScript is constructed in createAndAddWorkerScript(), the RunningScript
// object should have a PID assigned to it, so we return that
return runningScript.pid;
}
return 0;
}
/**
* Given a RunningScript object, constructs its corresponding WorkerScript,
* adds it to the global 'workerScripts' pool, and begins executing it.
* @param {RunningScript} runningScriptObj - Script that's being run
* @param {Server} server - Server on which the script is to be run
* returns {boolean} indicating whether or not the workerScript was successfully added
*/
function createAndAddWorkerScript(runningScriptObj, server, parent) {
// Update server's ram usage
let threads = 1;
if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) {
threads = runningScriptObj.threads;
} else {
runningScriptObj.threads = 1;
}
const ramUsage = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_22__["roundToTwo"])(Object(_Script_RunningScriptHelpers__WEBPACK_IMPORTED_MODULE_14__["getRamUsageFromRunningScript"])(runningScriptObj) * threads);
const ramAvailable = server.maxRam - server.ramUsed;
if (ramUsage > ramAvailable) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__["dialogBoxCreate"])(
`Not enough RAM to run script ${runningScriptObj.filename} with args ` +
`${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21__["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 false;
}
server.ramUsed = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_22__["roundToTwo"])(server.ramUsed + ramUsage);
// Get the pid
const pid = Object(_Netscript_Pid__WEBPACK_IMPORTED_MODULE_4__["generateNextPid"])();
if (pid === -1) {
throw new Error(
`Failed to start script because could not find available PID. This is most ` +
`because you have too many scripts running.`,
);
}
// Create the WorkerScript. NOTE: WorkerScript ctor will set the underlying
// RunningScript's PID as well
const s = new _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__["WorkerScript"](runningScriptObj, pid, _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_9__["NetscriptFunctions"]);
s.ramUsage = ramUsage;
// Add the WorkerScript to the global pool
_Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__["workerScripts"].set(pid, s);
_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__["WorkerScriptStartStopEventEmitter"].emitEvent();
// Start the script's execution
let p = null; // Script's resulting promise
if (s.name.endsWith(".js") || s.name.endsWith(".ns")) {
p = startNetscript2Script(s);
} else {
p = startNetscript1Script(s);
if (!(p instanceof Promise)) { return false; }
}
// Once the code finishes (either resolved or rejected, doesnt matter), set its
// running status to false
p.then(function(w) {
// On natural death, the earnings are transfered to the parent if it still exists.
if(parent && parent.running) {
parent.scriptRef.onlineExpGained += runningScriptObj.onlineExpGained;
parent.scriptRef.onlineMoneyMade += runningScriptObj.onlineMoneyMade;
}
// If the WorkerScript is no longer "running", then this means its execution was
// already stopped somewhere else (maybe by something like exit()). This prevents
// the script from being cleaned up twice
if (!w.running) { return; }
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__["killWorkerScript"])(s);
w.log("", "Script finished running");
}).catch(function(w) {
if (w instanceof Error) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
console.error("Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString());
return;
} else if (w instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__["WorkerScript"]) {
if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__[/* isScriptErrorMessage */ "a"])(w.errorMessage)) {
const errorTextArray = w.errorMessage.split("|");
if (errorTextArray.length != 4) {
console.error("ERROR: Something wrong with Error text in evaluator...");
console.error("Error text: " + errorText);
return;
}
const serverIp = errorTextArray[1];
const scriptName = errorTextArray[2];
const errorMsg = errorTextArray[3];
let msg = `RUNTIME ERROR ${scriptName}@${serverIp} `
if (w.args.length > 0) {
msg += `Args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21__["arrayToString"])(w.args)} `
}
msg += " ";
msg += errorMsg;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__["dialogBoxCreate"])(msg);
w.log("", "Script crashed with runtime error");
} else {
w.log("", "Script killed");
return; // Already killed, so stop here
}
w.running = false;
w.env.stopFlag = true;
} else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_8__[/* isScriptErrorMessage */ "a"])(w)) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_20__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
console.error("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_20__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev");
console.error(w);
}
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_0__["killWorkerScript"])(s);
});
return true;
}
/**
* Updates the online running time stat of all running scripts
*/
function updateOnlineScriptTimes(numCycles = 1) {
var time = (numCycles * _engine__WEBPACK_IMPORTED_MODULE_6__["Engine"]._idleSpeed) / 1000; //seconds
for (const ws of _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_2__["workerScripts"].values()) {
ws.scriptRef.onlineRunningTime += time;
}
}
/**
* Called when the game is loaded. Loads all running scripts (from all servers)
* into worker scripts so that they will start running
*/
function loadAllRunningScripts() {
let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1);
if (skipScriptLoad) { console.info("Skipping the load of any scripts during startup"); }
for (const property in _Server_AllServers__WEBPACK_IMPORTED_MODULE_16__["AllServers"]) {
if (_Server_AllServers__WEBPACK_IMPORTED_MODULE_16__["AllServers"].hasOwnProperty(property)) {
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_16__["AllServers"][property];
// Reset each server's RAM usage to 0
server.ramUsed = 0;
// Reset modules on all scripts
for (let i = 0; i < server.scripts.length; ++i) {
server.scripts[i].markUpdated();
}
if (skipScriptLoad) {
// Start game with no scripts
server.runningScripts.length = 0;
} else {
for (let j = 0; j < server.runningScripts.length; ++j) {
createAndAddWorkerScript(server.runningScripts[j], server);
// Offline production
Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_15__[/* scriptCalculateOfflineProduction */ "c"])(server.runningScripts[j]);
}
}
}
}
}
/**
* Run a script from inside another script (run(), exec(), spawn(), etc.)
*/
function runScriptFromScript(caller, server, scriptname, args, workerScript, threads=1) {
// Sanitize arguments
if (!(workerScript instanceof _Netscript_WorkerScript__WEBPACK_IMPORTED_MODULE_1__["WorkerScript"])) {
return 0;
}
if (typeof scriptname !== "string" || !Array.isArray(args)) {
workerScript.log(caller, `Invalid arguments: scriptname='${scriptname} args='${ags}'`);
console.error(`runScriptFromScript() failed due to invalid arguments`);
return 0;
}
// Check if the script is already running
let runningScriptObj = server.getRunningScript(scriptname, args);
if (runningScriptObj != null) {
workerScript.log(caller, `'${scriptname}' is already running on '${server.hostname}'`);
return 0;
}
// 'null/undefined' arguments are not allowed
for (let i = 0; i < args.length; ++i) {
if (args[i] == null) {
workerScript.log(caller, "Cannot execute a script with null/undefined as an argument");
return 0;
}
}
// Check if the script exists and if it does run it
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === scriptname) {
// Check for admin rights and that there is enough RAM availble to run
const script = server.scripts[i];
let ramUsage = script.ramUsage;
threads = Math.round(Number(threads));
if (threads === 0) { return 0; }
ramUsage = ramUsage * threads;
const ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
workerScript.log(caller, `You do not have root access on '${server.hostname}'`);
return 0;
} else if (ramUsage > ramAvailable){
workerScript.log(caller, `Cannot run script '${scriptname}' (t=${threads}) on '${server.hostname}' because there is not enough available RAM!`);
return 0;
} else {
// Able to run script
workerScript.log(caller, `'${scriptname}' on '${server.hostname}' with ${threads} threads and args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_21__["arrayToString"])(args)}.`);
let runningScriptObj = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_13__["RunningScript"](script, args);
runningScriptObj.threads = threads;
return startWorkerScript(runningScriptObj, server, workerScript);
}
}
}
workerScript.log(caller, `Could not find script '${scriptname}' on '${server.hostname}'`);
return 0;
}
/***/ }),
/* 81 */
/*!**************************!*\
!*** ./src/Missions.jsx ***!
\**************************/
/*! 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 */ 11);
/* 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 */ 15);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 71);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ui/React/Reputation */ 59);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 229);
/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 45);
/* 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 */ 72);
/* 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 _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 49);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! jsplumb */ 1067);
/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_13__);
// For some reason `jsplumb` needs to be imported exactly like this,
// lowercase p, and later in the code used as `jsPlumb` uppercase P. wtf.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
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.warn(`Node ${this.el.id} is being 'untargeted' when it has no target count`);
return;
}
--this.targetedCount;
};
/**
* Hacking mission instance
* @param rep {number} How much reputation the player has for the faction
* @param fac {Faction} Faction for which this mission is being conducted
*/
function HackingMission(rep, fac) {
this.faction = fac;
this.started = false;
this.time = 180000; // 5 minutes to start, milliseconds
this.playerCores = [];
this.playerNodes = []; // Non-core nodes
this.playerAtk = 0;
this.playerDef = 0;
this.enemyCores = [];
this.enemyDatabases = [];
this.enemyNodes = []; // Non-core nodes
this.enemyAtk = 0;
this.enemyDef = 0;
this.miscNodes = [];
this.selectedNode = []; // Which of the player's nodes are currently selected
this.actionButtons = []; // DOM buttons for actions
this.availablePositions = [];
for (var r = 0; r < 8; ++r) {
for (var c = 0; c < 8; ++c) {
this.availablePositions.push([r, c]);
}
}
this.map = [];
for (var i = 0; i < 8; ++i) {
this.map.push([null, null, null, null, null, null, null, null]);
}
this.jsplumbinstance = null;
this.difficulty = rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1;
this.reward = 250 + rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion;
}
HackingMission.prototype.init = function () {
// Create Header DOM
this.createPageDom(); // Create player starting nodes
var home = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer();
for (var i = 0; i < home.cpuCores; ++i) {
var stats = {
atk: _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5 + 30,
def: _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20,
hp: _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4
};
this.playerCores.push(new Node(NodeTypes.Core, stats));
this.playerCores[i].setControlledByPlayer();
this.setNodePosition(this.playerCores[i], i, 0);
this.removeAvailablePosition(i, 0);
} // Randomly generate enemy nodes (CPU and Firewall) based on difficulty
var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4)));
var numFirewalls = Math.min(20, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_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_7__["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"].faction_rep_mult * favorMult;
var headerText = document.createElement("p");
react_dom__WEBPACK_IMPORTED_MODULE_13___default.a.render(react__WEBPACK_IMPORTED_MODULE_12___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_12___default.a.Fragment, null, "You are about to start a hacking mission! You will gain ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_6__["Reputation"])(gain), " faction reputation with ", this.faction.name, " if you win. Click the 'Start' button to begin."), headerText);
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;
}); // 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.error("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.error("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.error("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.error("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.error("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.error("Pressing Action button without selected node");
return;
}
this.selectedNode.forEach(function (node) {
if (node.conn) {
var endpoints = node.conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
}
node.action = NodeActions.Fortify;
});
});
var timeDisplay = document.createElement("p");
container.appendChild(headerText);
container.appendChild(inGameGuideBtn);
container.appendChild(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_5__["formatNumber"])(this.playerAtk, 1) + " " + "Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].atk;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].atk;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].atk;
}
this.enemyAtk = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML = "Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyAtk, 1) + " " + "Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyDef, 1);
};
HackingMission.prototype.calculateDefenses = function () {
var total = 0;
for (var i = 0; i < this.playerCores.length; ++i) {
total += this.playerCores[i].def;
}
for (var i = 0; i < this.playerNodes.length; ++i) {
total += this.playerNodes[i].def;
}
this.playerDef = total;
document.getElementById("hacking-mission-player-stats").innerHTML = "Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerAtk, 1) + " " + "Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.playerDef, 1);
total = 0;
for (var i = 0; i < this.enemyCores.length; ++i) {
total += this.enemyCores[i].def;
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
total += this.enemyDatabases[i].def;
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
total += this.enemyNodes[i].def;
}
this.enemyDef = total;
document.getElementById("hacking-mission-enemy-stats").innerHTML = "Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyAtk, 1) + " " + "Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(this.enemyDef, 1);
};
HackingMission.prototype.removeAvailablePosition = function (x, y) {
for (var i = 0; i < this.availablePositions.length; ++i) {
if (this.availablePositions[i][0] === x && this.availablePositions[i][1] === y) {
this.availablePositions.splice(i, 1);
return;
}
}
console.warn(`removeAvailablePosition() did not remove ${x}, ${y}`);
};
HackingMission.prototype.setNodePosition = function (nodeObj, x, y) {
if (!(nodeObj instanceof Node)) {
console.warn("Non-Node object passed into setNodePOsition");
return;
}
if (isNaN(x) || isNaN(y)) {
console.error(`Invalid values (${x}, ${y}) passed as (x, y) for setNodePosition`);
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_7__["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) {
this.configurePlayerNodeElement(this.playerCores[i].el);
}
};
HackingMission.prototype.createNodeDomElement = function (nodeObj) {
var nodeDiv = document.createElement("a"),
txtEl = document.createElement('p');
nodeObj.el = nodeDiv; // Set the node element's id based on its coordinates
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
nodeDiv.setAttribute("id", id);
txtEl.setAttribute("id", id + "-txt"); // Set node classes for owner
nodeDiv.classList.add("hack-mission-node");
if (nodeObj.plyrCtrl) {
nodeDiv.classList.add("hack-mission-player-node");
} else if (nodeObj.enmyCtrl) {
nodeDiv.classList.add("hack-mission-enemy-node");
} // Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-cpu-node");
break;
case NodeTypes.Firewall:
txt = "Firewall " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-firewall-node");
break;
case NodeTypes.Database:
txt = "Database " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-database-node");
break;
case NodeTypes.Spam:
txt = "Spam " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-spam-node");
break;
case NodeTypes.Transfer:
txt = "Transfer " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-transfer-node");
break;
case NodeTypes.Shield:
default:
txt = "Shield " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
nodeDiv.classList.add("hack-mission-shield-node");
break;
}
txt += " Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.atk, 1) + " Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.def, 1);
txtEl.innerHTML = txt;
nodeDiv.appendChild(txtEl);
document.getElementById("hacking-mission-map").appendChild(nodeDiv);
};
HackingMission.prototype.updateNodeDomElement = function (nodeObj) {
if (nodeObj.el == null) {
console.error("Calling updateNodeDomElement on a Node without an element");
return;
}
let id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
let txtEl = document.getElementById(id + "-txt"); // Set node classes based on type
let txt;
switch (nodeObj.type) {
case NodeTypes.Core:
txt = "CPU Core " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Firewall:
txt = "Firewall " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Database:
txt = "Database " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Spam:
txt = "Spam " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Transfer:
txt = "Transfer " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
case NodeTypes.Shield:
default:
txt = "Shield " + "HP: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.hp, 1);
break;
}
txt += " Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.atk, 1) + " Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(nodeObj.def, 1);
if (nodeObj.action) {
txt += " " + nodeObj.action;
}
txtEl.innerHTML = txt;
};
/**
* Gets a Node DOM elements 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.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.error(`Unexpected values (${x}, ${y}) for (x, y)`);
return null;
}
return this.map[x][y];
};
function selectNode(hackMissionInst, el) {
var nodeObj = hackMissionInst.getNodeFromElement(el);
if (nodeObj == null) {
console.error("Failed 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.error("Failed 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.error("Failed getting Node object");
} // Add event listener
const selectNodeWrapper = () => {
selectNode(this, el);
};
el.addEventListener("click", selectNodeWrapper);
const multiselectNodeWrapper = () => {
multiselectNode(this, 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_10__["clearEventListeners"])("hack-mission-start-btn");
startBtn.classList.remove("a-link-button");
startBtn.classList.add("a-link-button-inactive");
};
HackingMission.prototype.initJsPlumb = function () {
var instance = jsPlumb.getInstance({
DragOptions: {
cursor: "pointer",
zIndex: 2000
},
PaintStyle: {
gradient: {
stops: [[0, "#FFFFFF"], [1, "#FFFFFF"]]
},
stroke: "#FFFFFF",
strokeWidth: 8
}
});
this.jsplumbinstance = instance; // All player cores are sources
for (var i = 0; i < this.playerCores.length; ++i) {
instance.makeSource(this.playerCores[i].el, {
deleteEndpointsOnEmpty: true,
maxConnections: 1,
anchor: "Continuous",
connector: "Flowchart"
});
} // Everything else is a target
for (var i = 0; i < this.enemyCores.length; ++i) {
instance.makeTarget(this.enemyCores[i].el, {
maxConnections: -1,
anchor: "Continuous",
connector: "Flowchart"
});
}
for (var i = 0; i < this.enemyDatabases.length; ++i) {
instance.makeTarget(this.enemyDatabases[i].el, {
maxConnections: -1,
anchor: "Continuous",
connector: ["Flowchart"]
});
}
for (var i = 0; i < this.enemyNodes.length; ++i) {
instance.makeTarget(this.enemyNodes[i].el, {
maxConnections: -1,
anchor: "Continuous",
connector: "Flowchart"
});
}
for (var i = 0; i < this.miscNodes.length; ++i) {
instance.makeTarget(this.miscNodes[i].el, {
maxConnections: -1,
anchor: "Continuous",
connector: "Flowchart"
});
} // Clicking a connection drops it
instance.bind("click", conn => {
// Cannot drop enemy's connections
const sourceNode = this.getNodeFromElement(conn.source);
if (sourceNode.enmyCtrl) {
return;
}
var endpoints = conn.endpoints;
endpoints[0].detachFrom(endpoints[1]);
}); // Connection events
instance.bind("connection", info => {
var targetNode = this.getNodeFromElement(info.target); // Do not detach for enemy nodes
var thisNode = this.getNodeFromElement(info.source);
if (thisNode.enmyCtrl) {
return;
} // If the node is not reachable, drop the connection
if (!this.nodeReachable(targetNode)) {
info.sourceEndpoint.detachFrom(info.targetEndpoint);
return;
}
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = info.connection;
var targetNode = this.getNodeFromElement(info.target);
++targetNode.targetedCount;
}); // Detach Connection events
instance.bind("connectionDetached", info => {
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = null;
var targetNode = this.getNodeFromElement(info.target);
targetNode.untarget();
});
}; // Drops all connections where the specified node is the source
HackingMission.prototype.dropAllConnectionsFromNode = function (node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length - 1; i >= 0; --i) {
if (allConns[i].source == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
}; // Drops all connections where the specified node is the target
HackingMission.prototype.dropAllConnectionsToNode = function (node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length - 1; i >= 0; --i) {
if (allConns[i].target == node.el) {
allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
}
}
node.beingTargeted = false;
};
var storedCycles = 0;
HackingMission.prototype.process = function (numCycles = 1) {
if (!this.started) {
return;
}
storedCycles += numCycles;
if (storedCycles < 2) {
return;
} // Only process every 3 cycles minimum
var res = false; // Process actions of all player nodes
this.playerCores.forEach(node => {
res |= this.processNode(node, storedCycles);
});
this.playerNodes.forEach(node => {
if (node.type === NodeTypes.Transfer || node.type === NodeTypes.Shield || node.type === NodeTypes.Firewall) {
res |= this.processNode(node, storedCycles);
}
}); // Process actions of all enemy nodes
this.enemyCores.forEach(node => {
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
});
this.enemyNodes.forEach(node => {
if (node.type === NodeTypes.Transfer || node.type === NodeTypes.Shield || node.type === NodeTypes.Firewall) {
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
}
}); // The hp of enemy databases increases slowly
this.enemyDatabases.forEach(node => {
node.maxhp += 0.1 * storedCycles;
node.hp += 0.1 * storedCycles;
});
if (res) {
this.calculateAttacks();
this.calculateDefenses();
} // Win if all enemy databases are conquered
if (this.enemyDatabases.length === 0) {
this.finishMission(true);
return;
} // Lose if all your cores are gone
if (this.playerCores.length === 0) {
this.finishMission(false);
return;
} // Defense/hp of misc nodes increases slowly over time
this.miscNodes.forEach(node => {
node.def += 0.1 * storedCycles;
node.maxhp += 0.05 * storedCycles;
node.hp += 0.1 * storedCycles;
if (node.hp > node.maxhp) {
node.hp = node.maxhp;
}
this.updateNodeDomElement(node);
}); // Update timer and check if player lost
this.time -= storedCycles * _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed;
if (this.time <= 0) {
this.finishMission(false);
return;
}
this.updateTimer();
storedCycles = 0;
}; // Returns a bool representing whether defenses need to be re-calculated
HackingMission.prototype.processNode = function (nodeObj, numCycles = 1) {
if (nodeObj.action == null) {
return;
}
var targetNode = null,
def,
atk;
if (nodeObj.conn) {
if (nodeObj.conn.target != null) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
} else {
targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
}
if (targetNode == null) {// Player is in the middle of dragging the connection,
// so the target node is null. Do nothing here
} else if (targetNode.plyrCtrl) {
def = this.playerDef;
atk = this.enemyAtk;
} else if (targetNode.enmyCtrl) {
def = this.enemyDef;
atk = this.playerAtk;
} else {
// Misc Node
def = targetNode.def;
nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk;
}
} // Calculations are per second, so divide everything by 5
var calcStats = false,
plyr = nodeObj.plyrCtrl;
var enmyHacking = this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking;
switch (nodeObj.action) {
case NodeActions.Attack:
if (targetNode == null) {
break;
}
if (nodeObj.conn == null) {
break;
}
var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.hp -= dmg / 5 * numCycles;
break;
case NodeActions.Scan:
if (targetNode == null) {
break;
}
if (nodeObj.conn == null) {
break;
}
var eff = this.calculateScanEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.def -= eff / 5 * numCycles;
calcStats = true;
break;
case NodeActions.Weaken:
if (targetNode == null) {
break;
}
if (nodeObj.conn == null) {
break;
}
var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
targetNode.atk -= eff / 5 * numCycles;
calcStats = true;
break;
case NodeActions.Fortify:
var eff = this.calculateFortifyEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
nodeObj.def += eff / 5 * numCycles;
calcStats = true;
break;
case NodeActions.Overflow:
var eff = this.calculateOverflowEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
if (nodeObj.def < eff) {
break;
}
nodeObj.def -= eff / 5 * numCycles;
nodeObj.atk += eff / 5 * numCycles;
calcStats = true;
break;
default:
console.error(`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.error("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;
var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult;
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_12___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_12___default.a.Fragment, null, "Mission won! You earned ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_6__["Reputation"])(gain), " reputation with ", this.faction.name));
_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain);
this.faction.playerReputation += gain;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation.");
} // Clear mission container
var container = document.getElementById("mission-container");
while (container.firstChild) {
container.removeChild(container.firstChild);
} // Return to Faction page
document.getElementById("mainmenu-container").style.visibility = "visible";
document.getElementById("character-overview-wrapper").style.visibility = "visible";
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name);
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 82 */,
/* 83 */,
/* 84 */,
/* 85 */
/*!******************************!*\
!*** ./src/Gang/AllGangs.ts ***!
\******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadAllGangs = exports.resetGangs = exports.AllGangs = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
exports.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() {
exports.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,
},
};
}
exports.resetGangs = resetGangs;
function loadAllGangs(saveString) {
exports.AllGangs = JSON.parse(saveString, JSONReviver_1.Reviver);
}
exports.loadAllGangs = loadAllGangs;
/***/ }),
/* 86 */
/*!******************************************!*\
!*** ./src/Terminal/DirectoryHelpers.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Helper functions that implement "directory" functionality in the Terminal.
* These aren't "real" directories, it's more of a pseudo-directory implementation
* that uses mainly string manipulation.
*
* This file contains functions that deal only with that string manipulation.
* Functions that need to access/process Server-related things can be
* found in ./DirectoryServerHelpers.ts
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.evaluateFilePath = exports.evaluateDirectoryPath = exports.isInRootDirectory = exports.getAllParentDirectories = exports.getFirstParentDirectory = exports.isValidFilePath = exports.isValidDirectoryPath = exports.isValidDirectoryName = exports.isValidFilename = exports.removeTrailingSlash = exports.removeLeadingSlash = void 0;
/**
* Removes leading forward slash ("/") from a string.
*/
function removeLeadingSlash(s) {
if (s.startsWith("/")) {
return s.slice(1);
}
return s;
}
exports.removeLeadingSlash = removeLeadingSlash;
/**
* Removes trailing forward slash ("/") from a string.
* Note that this will also remove the slash if it is the leading slash (i.e. if s = "/")
*/
function removeTrailingSlash(s) {
if (s.endsWith("/")) {
return s.slice(0, -1);
}
return s;
}
exports.removeTrailingSlash = removeTrailingSlash;
/**
* Checks whether a string is a valid filename. Only used for the filename itself,
* not the entire filepath
*/
function isValidFilename(filename) {
// Allows alphanumerics, hyphens, underscores, and percentage signs
// Must have a file extension
const regex = /^[.a-zA-Z0-9_-]+[.][a-zA-Z0-9]+(?:-\d+(?:\.\d*)?%-INC)?$/;
// match() returns null if no match is found
return filename.match(regex) != null;
}
exports.isValidFilename = isValidFilename;
/**
* Checks whether a string is a valid directory name. Only used for the directory itself,
* not an entire path
*/
function isValidDirectoryName(name) {
// Allows alphanumerics, hyphens, underscores, and percentage signs.
// Name can begin with a single period, but otherwise cannot have any
const regex = /^.?[a-zA-Z0-9_-]+$/;
// match() returns null if no match is found
return name.match(regex) != null;
}
exports.isValidDirectoryName = isValidDirectoryName;
/**
* Checks whether a string is a valid directory path.
* This only checks if it has the proper formatting. It does NOT check
* if the directories actually exist on Terminal
*/
function isValidDirectoryPath(path) {
let t_path = path;
if (t_path.length === 0) {
return false;
}
if (t_path.length === 1) {
return t_path === "/";
}
// A full path must have a leading slash, but we'll ignore it for the checks
if (t_path.startsWith("/")) {
t_path = t_path.slice(1);
}
else {
return false;
}
// Trailing slash does not matter
t_path = removeTrailingSlash(t_path);
// Check that every section of the path is a valid directory name
const dirs = t_path.split("/");
for (const dir of dirs) {
// Special case, "." and ".." are valid for path
if (dir === "." || dir === "..") {
continue;
}
if (!isValidDirectoryName(dir)) {
return false;
}
}
return true;
}
exports.isValidDirectoryPath = isValidDirectoryPath;
/**
* Checks whether a string is a valid file path. This only checks if it has the
* proper formatting. It dose NOT check if the file actually exists on Terminal
*/
function isValidFilePath(path) {
if (path == null || typeof path !== "string") {
return false;
}
const t_path = path;
// Impossible for filename to have less than length of 3
if (t_path.length < 3) {
return false;
}
// Full filepath can't end with trailing slash because it must be a file
if (t_path.endsWith("/")) {
return false;
}
// Everything after the last forward slash is the filename. Everything before
// it is the file path
const fnSeparator = t_path.lastIndexOf("/");
if (fnSeparator === -1) {
return isValidFilename(t_path);
}
const fn = t_path.slice(fnSeparator + 1);
const dirPath = t_path.slice(0, fnSeparator + 1);
return isValidDirectoryPath(dirPath) && isValidFilename(fn);
}
exports.isValidFilePath = isValidFilePath;
/**
* Returns a formatted string for the first parent directory in a filepath. For example:
* /home/var/test/ -> home/
* If there is no first parent directory, then it returns "/" for root
*/
function getFirstParentDirectory(path) {
let t_path = path;
t_path = removeLeadingSlash(t_path);
t_path = removeTrailingSlash(t_path);
if (t_path.lastIndexOf("/") === -1) {
return "/";
}
const dirs = t_path.split("/");
if (dirs.length === 0) {
return "/";
}
return dirs[0] + "/";
}
exports.getFirstParentDirectory = getFirstParentDirectory;
/**
* Given a filepath, returns a formatted string for all of the parent directories
* in that filepath. For example:
* /home/var/tes -> home/var/
* /home/var/test/ -> home/var/test/
* If there are no parent directories, it returns the empty string
*/
function getAllParentDirectories(path) {
const t_path = path;
const lastSlash = t_path.lastIndexOf("/");
if (lastSlash === -1) {
return "";
}
return t_path.slice(0, lastSlash + 1);
}
exports.getAllParentDirectories = getAllParentDirectories;
/**
* Checks if a file path refers to a file in the root directory.
*/
function isInRootDirectory(path) {
if (!isValidFilePath(path)) {
return false;
}
if (path == null || path.length === 0) {
return false;
}
return (path.lastIndexOf("/") <= 0);
}
exports.isInRootDirectory = isInRootDirectory;
/**
* Evaluates a directory path, including the processing of linux dots.
* Returns the full, proper path, or null if an invalid path is passed in
*/
function evaluateDirectoryPath(path, currPath) {
let t_path = path;
// If the path begins with a slash, then its an absolute path. Otherwise its relative
// For relative paths, we need to prepend the current directory
if (!t_path.startsWith("/") && currPath != null) {
t_path = currPath + (currPath.endsWith("/") ? "" : "/") + t_path;
}
if (!isValidDirectoryPath(t_path)) {
return null;
}
// Trim leading/trailing slashes
t_path = removeLeadingSlash(t_path);
t_path = removeTrailingSlash(t_path);
const dirs = t_path.split("/");
const reconstructedPath = [];
for (const dir of dirs) {
if (dir === ".") {
// Current directory, do nothing
continue;
}
else if (dir === "..") {
// Parent directory
const res = reconstructedPath.pop();
if (res == null) {
return null; // Array was empty, invalid path
}
}
else {
reconstructedPath.push(dir);
}
}
return "/" + reconstructedPath.join("/");
}
exports.evaluateDirectoryPath = evaluateDirectoryPath;
/**
* Evaluates a file path, including the processing of linux dots.
* Returns the full, proper path, or null if an invalid path is passed in
*/
function evaluateFilePath(path, currPath) {
let t_path = path;
// If the path begins with a slash, then its an absolute path. Otherwise its relative
// For relative paths, we need to prepend the current directory
if (!t_path.startsWith("/") && currPath != null) {
t_path = currPath + (currPath.endsWith("/") ? "" : "/") + t_path;
}
if (!isValidFilePath(t_path)) {
return null;
}
// Trim leading/trailing slashes
t_path = removeLeadingSlash(t_path);
const dirs = t_path.split("/");
const reconstructedPath = [];
for (const dir of dirs) {
if (dir === ".") {
// Current directory, do nothing
continue;
}
else if (dir === "..") {
// Parent directory
const res = reconstructedPath.pop();
if (res == null) {
return null; // Array was empty, invalid path
}
}
else {
reconstructedPath.push(dir);
}
}
return "/" + reconstructedPath.join("/");
}
exports.evaluateFilePath = evaluateFilePath;
/***/ }),
/* 87 */
/*!***************************************!*\
!*** ./src/Message/MessageHelpers.js ***!
\***************************************/
/*! exports provided: Messages, checkForMessagesToSend, sendMessage, showMessage, loadMessages, initMessages, Message */
/*! exports used: Messages, checkForMessagesToSend, initMessages, loadMessages, showMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Messages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkForMessagesToSend; });
/* unused harmony export sendMessage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return showMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initMessages; });
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Message */ 73);
/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Message__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Missions */ 81);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../RedPill */ 103);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
//Sends message to player, including a pop up
function sendMessage(msg, forced=false) {
msg.recvd = true;
if (forced || !_Settings_Settings__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressMessages) {
showMessage(msg);
}
addMessageToServer(msg, "home");
}
function showMessage(msg) {
var txt = "Message received from unknown sender:
" +
"" + msg.msg + "
" +
"This message was saved as " + msg.filename + " onto your home computer.";
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt);
}
//Adds a message to a server
function addMessageToServer(msg, serverHostname) {
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_7__["GetServerByHostname"])(serverHostname);
if (server == null) {
console.warn(`Could not find server ${serverHostname}`);
return;
}
for (var i = 0; i < server.messages.length; ++i) {
if (server.messages[i].filename === msg.filename) {
return; //Already exists
}
}
server.messages.push(msg);
}
//Checks if any of the 'timed' messages should be sent
function checkForMessagesToSend() {
var jumper0 = Messages[MessageFilenames.Jumper0];
var jumper1 = Messages[MessageFilenames.Jumper1];
var jumper2 = Messages[MessageFilenames.Jumper2];
var jumper3 = Messages[MessageFilenames.Jumper3];
var jumper4 = Messages[MessageFilenames.Jumper4];
var cybersecTest = Messages[MessageFilenames.CyberSecTest];
var nitesecTest = Messages[MessageFilenames.NiteSecTest];
var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest];
var redpill = Messages[MessageFilenames.RedPill];
var redpillOwned = false;
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].TheRedPill].owned) {
redpillOwned = true;
}
if (redpill && redpillOwned && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].sourceFiles.length === 0 && !_RedPill__WEBPACK_IMPORTED_MODULE_6__["redPillFlag"] && !_Missions__WEBPACK_IMPORTED_MODULE_4__[/* inMission */ "c"]) {
sendMessage(redpill, true);
} else if (redpill && redpillOwned) {
//If player has already destroyed a BitNode, message is not forced
if (!_RedPill__WEBPACK_IMPORTED_MODULE_6__["redPillFlag"] && !_Missions__WEBPACK_IMPORTED_MODULE_4__[/* inMission */ "c"]) {
sendMessage(redpill);
}
} else if (jumper0 && !jumper0.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 25) {
sendMessage(jumper0);
const flightName = _Programs_Programs__WEBPACK_IMPORTED_MODULE_3__["Programs"].Flight.name;
const homeComp = _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].getHomeComputer();
if (!homeComp.programs.includes(flightName)) {
homeComp.programs.push(flightName);
}
} else if (jumper1 && !jumper1.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 40) {
sendMessage(jumper1);
} else if (cybersecTest && !cybersecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 50) {
sendMessage(cybersecTest);
} else if (jumper2 && !jumper2.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 175) {
sendMessage(jumper2);
} else if (nitesecTest && !nitesecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 200) {
sendMessage(nitesecTest);
} else if (jumper3 && !jumper3.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 350) {
sendMessage(jumper3);
} else if (jumper4 && !jumper4.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 490) {
sendMessage(jumper4);
} else if (bitrunnersTest && !bitrunnersTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hacking_skill >= 500) {
sendMessage(bitrunnersTest);
}
}
function AddToAllMessages(msg) {
Messages[msg.filename] = msg;
}
let Messages = {}
function loadMessages(saveString) {
Messages = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_10__["Reviver"]);
}
let MessageFilenames = {
Jumper0: "j0.msg",
Jumper1: "j1.msg",
Jumper2: "j2.msg",
Jumper3: "j3.msg",
Jumper4: "j4.msg",
CyberSecTest: "csec-test.msg",
NiteSecTest: "nitesec-test.msg",
BitRunnersTest: "19dfj3l1nd.msg",
RedPill: "icarus.msg",
}
function initMessages() {
//Reset
Messages = {};
//jump3R Messages
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper0,
"I know you can sense it. I know you're searching for it. " +
"It's why you spend night after " +
"night at your computer.
It's real, I've seen it. And I can " +
"help you find it. But not right now. You're not ready yet.
" +
"Use this program to track your progress
" +
"The fl1ght.exe program was added to your home computer
" +
"-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper1,
"Soon you will be contacted by a hacking group known as CyberSec. " +
"They can help you with your search.
" +
"You should join them, garner their favor, and " +
"exploit them for their Augmentations. But do not trust them. " +
"They are not what they seem. No one is.
" +
"-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper2,
"Do not try to save the world. There is no world to save. If " +
"you want to find the truth, worry only about yourself. Ethics and " +
"morals will get you killed.
Watch out for a hacking group known as NiteSec." +
"
-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper3,
"You must learn to walk before you can run. And you must " +
"run before you can fly. Look for the black hand.
" +
"I.I.I.I
-jump3R"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.Jumper4,
"To find what you are searching for, you must understand the bits. " +
"The bits are all around us. The runners will help you.
" +
"-jump3R"));
//Messages from hacking factions
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.CyberSecTest,
"We've been watching you. Your skills are very impressive. But you're wasting " +
"your talents. If you join us, you can put your skills to good use and change " +
"the world for the better. If you join us, we can unlock your full potential.
" +
"But first, you must pass our test. Find and install the backdoor on our server.
" +
"-CyberSec"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.NiteSecTest,
"People say that the corrupted governments and corporations rule the world. " +
"Yes, maybe they do. But do you know who everyone really fears? People " +
"like us. Because they can't hide from us. Because they can't fight shadows " +
"and ideas with bullets.
" +
"Join us, and people will fear you, too.
" +
"Find and install the backdoor on our server. Then, we will contact you again." +
"
-NiteSec"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.BitRunnersTest,
"We know what you are doing. We know what drives you. We know " +
"what you are looking for.
" +
"We can help you find the answers.
" +
"run4theh111z"));
AddToAllMessages(new _Message__WEBPACK_IMPORTED_MODULE_0__["Message"](MessageFilenames.RedPill,
"@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*% " +
")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B) " +
"@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB " +
"DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
}
/***/ }),
/* 88 */,
/* 89 */,
/* 90 */
/*!**********************************************!*\
!*** ./utils/uiHelpers/removeElementById.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeElementById = void 0;
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 190);
const removeElement_1 = __webpack_require__(/*! ./removeElement */ 224);
/**
* 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;
/***/ }),
/* 91 */
/*!*****************************************!*\
!*** ./utils/helpers/exceptionAlert.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exceptionAlert = void 0;
const DialogBox_1 = __webpack_require__(/*! ../DialogBox */ 13);
function exceptionAlert(e) {
console.error(e);
DialogBox_1.dialogBoxCreate("Caught an exception: " + e + "
" +
"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: getRandomInt_1.getRandomInt(1, 100), countGrowth: getRandomInt_1.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_1.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: getRandomInt_1.getRandomInt(1, 150), countGrowth: getRandomInt_1.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_1.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: getRandomInt_1.getRandomInt(1, 150), countGrowth: getRandomInt_1.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_1.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: getRandomInt_1.getRandomInt(1, 150), countGrowth: getRandomInt_1.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_1.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: getRandomInt_1.getRandomInt(1, 150), countGrowth: getRandomInt_1.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,
});
}
process(player) {
// Edge case condition...if Operation Daedalus is complete trigger the BitNode
if (RedPill_1.redPillFlag === false && this.blackops.hasOwnProperty("Operation Daedalus")) {
return RedPill_1.hackWorldDaemon(player.bitNodeN);
}
// If the Player starts doing some other actions, set action to idle and alert
if (Augmentations_1.Augmentations[AugmentationNames_1.AugmentationNames.BladesSimulacrum].owned === false && player.isWorking) {
if (this.action.type !== ActionTypes_1.ActionTypes["Idle"]) {
let msg = "Your Bladeburner action was cancelled because you started doing something else.";
if (this.automateEnabled) {
msg += `
Your automation was disabled as well. You will have to re-enable it through the Bladeburner console`;
this.automateEnabled = false;
}
if (!Settings_1.Settings.SuppressBladeburnerPopup) {
DialogBox_1.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 >= Constants_1.BladeburnerConstants.CyclesPerSecond) {
let seconds = Math.floor(this.storedCycles / Constants_1.BladeburnerConstants.CyclesPerSecond);
seconds = Math.min(seconds, 5); // Max of 5 'ticks'
this.storedCycles -= seconds * Constants_1.BladeburnerConstants.CyclesPerSecond;
// Stamina
this.calculateMaxStamina(player);
this.stamina += (this.calculateStaminaGainPerSecond(player) * seconds);
this.stamina = Math.min(this.maxStamina, this.stamina);
// Count increase for contracts/operations
for (const contract of Object.values(this.contracts)) {
contract.count += (seconds * contract.countGrowth / Constants_1.BladeburnerConstants.ActionCountGrowthPeriod);
}
for (const op of Object.values(this.operations)) {
op.count += (seconds * op.countGrowth / Constants_1.BladeburnerConstants.ActionCountGrowthPeriod);
}
// Chaos goes down very slowly
for (const cityName of Constants_1.BladeburnerConstants.CityNames) {
const city = this.cities[cityName];
if (!(city instanceof City_1.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();
// Add instead of setting because we might have gone over the required time for the event
this.randomEventCounter += getRandomInt_1.getRandomInt(240, 600);
}
this.processAction(player, 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_1.ActionIdentifier({ type: this.automateActionLow.type, name: this.automateActionLow.name });
this.startAction(player, 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_1.ActionIdentifier({ type: this.automateActionHigh.type, name: this.automateActionHigh.name });
this.startAction(player, this.action);
}
}
}
}
}
getTypeAndNameFromActionId(actionId) {
const res = { type: '', name: '' };
const types = Object.keys(ActionTypes_1.ActionTypes);
for (let i = 0; i < types.length; ++i) {
if (actionId.type === ActionTypes_1.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;
}
getContractNamesNetscriptFn() {
return Object.keys(this.contracts);
}
getOperationNamesNetscriptFn() {
return Object.keys(this.operations);
}
getBlackOpNamesNetscriptFn() {
return Object.keys(BlackOperations_1.BlackOperations);
}
getGeneralActionNamesNetscriptFn() {
return Object.keys(GeneralActions_1.GeneralActions);
}
getSkillNamesNetscriptFn() {
return Object.keys(Skills_1.Skills);
}
startActionNetscriptFn(player, type, name, workerScript) {
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.startAction", errorLogText);
return false;
}
// Special logic for Black Ops
if (actionId.type === ActionTypes_1.ActionTypes["BlackOp"]) {
// Can't start a BlackOp if you don't have the required rank
const action = this.getActionObject(actionId);
if (action == null)
throw new Error(`Action not found ${actionId.type}, ${actionId.name}`);
if (!(action instanceof BlackOperation_1.BlackOperation))
throw new Error(`Action should be BlackOperation but isn't`);
//const blackOp = (action as BlackOperation);
if (action.reqdRank > this.rank) {
workerScript.log("bladeburner.startAction", `Insufficient rank to start Black Op '${actionId.name}'.`);
return false;
}
// Can't start a BlackOp if its already been done
if (this.blackops[actionId.name] != null) {
workerScript.log("bladeburner.startAction", `Black Op ${actionId.name} has already been completed.`);
return false;
}
// Can't start a BlackOp if you haven't done the one before it
const blackops = [];
for (const nm in BlackOperations_1.BlackOperations) {
if (BlackOperations_1.BlackOperations.hasOwnProperty(nm)) {
blackops.push(nm);
}
}
blackops.sort(function (a, b) {
return (BlackOperations_1.BlackOperations[a].reqdRank - BlackOperations_1.BlackOperations[b].reqdRank); // Sort black ops in intended order
});
const i = blackops.indexOf(actionId.name);
if (i === -1) {
workerScript.log("bladeburner.startAction", `Invalid Black Op: '${name}'`);
return false;
}
if (i > 0 && this.blackops[blackops[i - 1]] == null) {
workerScript.log("bladeburner.startAction", `Preceding Black Op must be completed before starting '${actionId.name}'.`);
return false;
}
}
try {
this.startAction(player, actionId);
workerScript.log("bladeburner.startAction", `Starting bladeburner action with type '${type}' and name ${name}"`);
return true;
}
catch (e) {
this.resetAction();
workerScript.log("bladeburner.startAction", errorLogText);
return false;
}
}
getActionTimeNetscriptFn(player, type, name, workerScript) {
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.getActionTime", errorLogText);
return -1;
}
const actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log("bladeburner.getActionTime", errorLogText);
return -1;
}
switch (actionId.type) {
case ActionTypes_1.ActionTypes["Contract"]:
case ActionTypes_1.ActionTypes["Operation"]:
case ActionTypes_1.ActionTypes["BlackOp"]:
case ActionTypes_1.ActionTypes["BlackOperation"]:
return actionObj.getActionTime(this);
case ActionTypes_1.ActionTypes["Training"]:
case ActionTypes_1.ActionTypes["Field Analysis"]:
case ActionTypes_1.ActionTypes["FieldAnalysis"]:
return 30;
case ActionTypes_1.ActionTypes["Recruitment"]:
return this.getRecruitmentTime(player);
case ActionTypes_1.ActionTypes["Diplomacy"]:
case ActionTypes_1.ActionTypes["Hyperbolic Regeneration Chamber"]:
return 60;
default:
workerScript.log("bladeburner.getActionTime", errorLogText);
return -1;
}
}
getActionEstimatedSuccessChanceNetscriptFn(player, type, name, workerScript) {
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.getActionEstimatedSuccessChance", errorLogText);
return [-1, -1];
}
const actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log("bladeburner.getActionEstimatedSuccessChance", errorLogText);
return [-1, -1];
}
switch (actionId.type) {
case ActionTypes_1.ActionTypes["Contract"]:
case ActionTypes_1.ActionTypes["Operation"]:
case ActionTypes_1.ActionTypes["BlackOp"]:
case ActionTypes_1.ActionTypes["BlackOperation"]:
return actionObj.getEstSuccessChance(this);
case ActionTypes_1.ActionTypes["Training"]:
case ActionTypes_1.ActionTypes["Field Analysis"]:
case ActionTypes_1.ActionTypes["FieldAnalysis"]:
return [1, 1];
case ActionTypes_1.ActionTypes["Recruitment"]:
const recChance = this.getRecruitmentSuccessChance(player);
return [recChance, recChance];
default:
workerScript.log("bladeburner.getActionEstimatedSuccessChance", errorLogText);
return [-1, -1];
}
}
getActionCountRemainingNetscriptFn(type, name, workerScript) {
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.getActionCountRemaining", errorLogText);
return -1;
}
const actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log("bladeburner.getActionCountRemaining", errorLogText);
return -1;
}
switch (actionId.type) {
case ActionTypes_1.ActionTypes["Contract"]:
case ActionTypes_1.ActionTypes["Operation"]:
return Math.floor(actionObj.count);
case ActionTypes_1.ActionTypes["BlackOp"]:
case ActionTypes_1.ActionTypes["BlackOperation"]:
if (this.blackops[name] != null) {
return 0;
}
else {
return 1;
}
case ActionTypes_1.ActionTypes["Training"]:
case ActionTypes_1.ActionTypes["Field Analysis"]:
case ActionTypes_1.ActionTypes["FieldAnalysis"]:
return Infinity;
default:
workerScript.log("bladeburner.getActionCountRemaining", errorLogText);
return -1;
}
}
getSkillLevelNetscriptFn(skillName, workerScript) {
if (skillName === "" || !Skills_1.Skills.hasOwnProperty(skillName)) {
workerScript.log("bladeburner.getSkillLevel", `Invalid skill: '${skillName}'`);
return -1;
}
if (this.skills[skillName] == null) {
return 0;
}
else {
return this.skills[skillName];
}
}
getSkillUpgradeCostNetscriptFn(skillName, workerScript) {
if (skillName === "" || !Skills_1.Skills.hasOwnProperty(skillName)) {
workerScript.log("bladeburner.getSkillUpgradeCost", `Invalid skill: '${skillName}'`);
return -1;
}
const skill = Skills_1.Skills[skillName];
if (this.skills[skillName] == null) {
return skill.calculateCost(0);
}
else {
return skill.calculateCost(this.skills[skillName]);
}
}
upgradeSkillNetscriptFn(skillName, workerScript) {
const errorLogText = `Invalid skill: '${skillName}'`;
if (!Skills_1.Skills.hasOwnProperty(skillName)) {
workerScript.log("bladeburner.upgradeSkill", errorLogText);
return false;
}
const skill = Skills_1.Skills[skillName];
let currentLevel = 0;
if (this.skills[skillName] && !isNaN(this.skills[skillName])) {
currentLevel = this.skills[skillName];
}
const cost = skill.calculateCost(currentLevel);
if (skill.maxLvl && currentLevel >= skill.maxLvl) {
workerScript.log("bladeburner.upgradeSkill", `Skill '${skillName}' is already maxed.`);
return false;
}
if (this.skillPoints < cost) {
workerScript.log("bladeburner.upgradeSkill", `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);
workerScript.log("bladeburner.upgradeSkill", `'${skillName}' upgraded to level ${this.skills[skillName]}`);
return true;
}
getTeamSizeNetscriptFn(type, name, workerScript) {
if (type === "" && name === "") {
return this.teamSize;
}
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.getTeamSize", errorLogText);
return -1;
}
const actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log("bladeburner.getTeamSize", errorLogText);
return -1;
}
if (actionId.type === ActionTypes_1.ActionTypes["Operation"] ||
actionId.type === ActionTypes_1.ActionTypes["BlackOp"] ||
actionId.type === ActionTypes_1.ActionTypes["BlackOperation"]) {
return actionObj.teamCount;
}
else {
return 0;
}
}
setTeamSizeNetscriptFn(type, name, size, workerScript) {
const errorLogText = `Invalid action: type='${type}' name='${name}'`;
const actionId = this.getActionIdFromTypeAndName(type, name);
if (actionId == null) {
workerScript.log("bladeburner.setTeamSize", errorLogText);
return -1;
}
if (actionId.type !== ActionTypes_1.ActionTypes["Operation"] &&
actionId.type !== ActionTypes_1.ActionTypes["BlackOp"] &&
actionId.type !== ActionTypes_1.ActionTypes["BlackOperation"]) {
workerScript.log("bladeburner.setTeamSize", "Only valid for 'Operations' and 'BlackOps'");
return -1;
}
const actionObj = this.getActionObject(actionId);
if (actionObj == null) {
workerScript.log("bladeburner.setTeamSize", errorLogText);
return -1;
}
let sanitizedSize = Math.round(size);
if (isNaN(sanitizedSize) || sanitizedSize < 0) {
workerScript.log("bladeburner.setTeamSize", `Invalid size: ${size}`);
return -1;
}
if (this.teamSize < sanitizedSize) {
sanitizedSize = this.teamSize;
}
actionObj.teamCount = sanitizedSize;
workerScript.log("bladeburner.setTeamSize", `Team size for '${name}' set to ${sanitizedSize}.`);
return sanitizedSize;
}
joinBladeburnerFactionNetscriptFn(workerScript) {
const bladeburnerFac = Factions_1.Factions["Bladeburners"];
if (bladeburnerFac.isMember) {
return true;
}
else if (this.rank >= Constants_1.BladeburnerConstants.RankNeededForFaction) {
FactionHelpers_1.joinFaction(bladeburnerFac);
workerScript.log("bladeburner.joinBladeburnerFaction", "Joined Bladeburners faction.");
return true;
}
else {
workerScript.log("bladeburner.joinBladeburnerFaction", `You do not have the required rank (${this.rank}/${Constants_1.BladeburnerConstants.RankNeededForFaction}).`);
return false;
}
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Bladeburner", this);
}
/**
* Initiatizes a Bladeburner object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Bladeburner, value.data);
}
}
exports.Bladeburner = Bladeburner;
JSONReviver_1.Reviver.constructors.Bladeburner = Bladeburner;
/***/ }),
/* 95 */,
/* 96 */,
/* 97 */,
/* 98 */
/*!***********************************************!*\
!*** ./src/StockMarket/data/PositionTypes.ts ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PositionTypes = void 0;
var PositionTypes;
(function (PositionTypes) {
PositionTypes["Long"] = "L";
PositionTypes["Short"] = "S";
})(PositionTypes = exports.PositionTypes || (exports.PositionTypes = {}));
/***/ }),
/* 99 */,
/* 100 */,
/* 101 */,
/* 102 */,
/* 103 */
/*!************************!*\
!*** ./src/RedPill.js ***!
\************************/
/*! exports provided: redPillFlag, hackWorldDaemon */
/*! 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__, "redPillFlag", function() { return redPillFlag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hackWorldDaemon", function() { return hackWorldDaemon; });
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode/BitNode */ 127);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Prestige */ 173);
/* harmony import */ var _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SourceFile/PlayerOwnedSourceFile */ 443);
/* harmony import */ var _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SourceFile/SourceFiles */ 227);
/* harmony import */ var _SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/YesNoBox */ 61);
/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 49);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 149);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11__);
/**
* Implementation for what happens when you destroy a BitNode
*/
// 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) {
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_7__["setTimeoutRef"])(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 + " █ ";
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, quick=false) {
// Clear Red Pill screen first
var container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(container);
redPillFlag = true;
_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadRedPillContent();
if(quick) {
return loadBitVerse(currentNodeNumber, flume, quick);
}
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.error(e.toString());
});
}
function giveSourceFile(bitNodeNumber) {
var sourceFileKey = "SourceFile"+ bitNodeNumber.toString();
var sourceFile = _SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_6__["SourceFiles"][sourceFileKey];
if (sourceFile == null) {
console.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"].sourceFiles.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].sourceFiles[i].n === bitNodeNumber) {
alreadyOwned = true;
ownedSourceFile = _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].sourceFiles[i];
break;
}
}
if (alreadyOwned && ownedSourceFile) {
if (ownedSourceFile.lvl >= 3 && ownedSourceFile.n !== 12) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["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_8__["dialogBoxCreate"])(sourceFile.name + " was upgraded to level " + ownedSourceFile.lvl + " for " +
"destroying its corresponding BitNode!");
}
} else {
var playerSrcFile = new _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_4__["PlayerOwnedSourceFile"](bitNodeNumber, 1);
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].sourceFiles.push(playerSrcFile);
if (bitNodeNumber === 5 && _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence === 0) { // Artificial Intelligence
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence = 1;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You received a Source-File for destroying a Bit Node!
" +
sourceFile.name + "
" + sourceFile.info);
}
}
// Keeps track of what Source-Files the player will have AFTER the current bitnode
// is destroyed. Updated every time loadBitVerse() is called
let nextSourceFileFlags = [];
function loadBitVerse(destroyedBitNodeNum, flume=false, quick=false) {
// Clear the screen
const container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(container);
// Update NextSourceFileFlags
nextSourceFileFlags = _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_5__["SourceFileFlags"].slice();
if (!flume) {
if (nextSourceFileFlags[destroyedBitNodeNum] < 3)
++nextSourceFileFlags[destroyedBitNodeNum];
}
// Create the Bit Verse
const bitVerseImage = document.createElement("pre");
const bitNodes = [];
for (let i = 1; i <= 12; ++i) {
bitNodes.push(createBitNode(i));
}
bitVerseImage.innerHTML =
" O " +
" | O O | O O | " +
" O | | / __| \\ | | O " +
" O | O | | O / | O | | O | O " +
" | | | | |_/ |/ | \\_ \\_| | | | | " +
" O | | | O | | O__/ | / \\__ | | O | | | O " +
" | | | | | | | / /| O / \\| | | | | | | " +
"O | | | \\| | O / _/ | / O | |/ | | | O " +
"| | | |O / | | O / | O O | | \\ O| | | | " +
"| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | | " +
" \\| O | |_/ |\\| \\ O \\__| \\_| | O |/ " +
" | | |_/ | | \\| / | \\_| | | " +
" \\| / \\| | / / \\ |/ " +
" | "+bitNodes[9]+" | | / | "+bitNodes[10]+" | " +
" "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+" " +
" | | | / / \\ \\ | | | " +
" \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/ " +
" \\ | / / | | \\ \\ | / " +
" \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ / " +
" \\|| | | | | | | | | ||/ " +
" \\| \\_ | | | | | | _/ |/ " +
" \\ \\| / \\ / \\ |/ / " +
" "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+" " +
" | | | | | | | | " +
" \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/
";
container.appendChild(bitVerseImage);
// BitNode event listeners
for (let i = 1; i <= 12; ++i) {
(function(i) {
const elemId = "bitnode-" + i.toString();
const elem = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_10__["clearEventListeners"])(elemId);
if (elem == null) { return; }
if (i >= 1 && i <= 12) {
elem.addEventListener("click", function() {
const bitNodeKey = "BitNode" + i;
const bitNode = _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodes"][bitNodeKey];
if (bitNode == null) {
console.error(`Could not find BitNode object for number: ${i}`);
return;
}
const maxSourceFileLevel = i === 12 ? "∞" : "3";
const popupBoxText = `BitNode-${i}: ${bitNode.name} ` +
`Source-File Level: ${nextSourceFileFlags[i]} / ${maxSourceFileLevel}
` +
`${bitNode.info}`;
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxCreate"])(popupBoxText);
createBitNodeYesNoEventListener(i, destroyedBitNodeNum, flume);
});
} else {
elem.addEventListener("click", function() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("Not yet implemented! Coming soon!")
});
}
}(i)); // Immediate invocation closure
}
if(quick) {
return Promise.resolve(true);
}
// 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.error(e.toString());
});
}
// Returns string with DOM element for Bit Node
function createBitNode(n) {
const bitNodeStr = "BitNode" + n.toString();
const bitNode = _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodes"][bitNodeStr];
if (bitNode == null) { return "O"; }
const level = nextSourceFileFlags[n];
let cssClass;
if (n === 12 && level >= 2) {
// Repeating BitNode
cssClass = "level-2";
} else {
cssClass = `level-${level}`;
}
return `O` +
"" +
`BitNode-${bitNode.number.toString()} ${bitNode.name} ` +
`${bitNode.desc} ` +
"";
}
function createBitNodeYesNoEventListener(newBitNode, destroyedBitNode, flume=false) {
const yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxGetYesButton"])();
yesBtn.innerHTML = "Enter BitNode-" + newBitNode;
yesBtn.addEventListener("click", function() {
if (!flume) {
giveSourceFile(destroyedBitNode);
} else {
if(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_5__["SourceFileFlags"][5] === 0 && newBitNode !== 5) {
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence = 0;
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence_exp = 0;
}
}
if (newBitNode === 5 && _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence === 0) {
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence = 1;
}
redPillFlag = false;
const container = document.getElementById("red-pill-content");
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(container);
// Set new Bit Node
_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].bitNodeN = newBitNode;
// 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[class=terminal-input]').prop('disabled', false);
Object(_Prestige__WEBPACK_IMPORTED_MODULE_3__[/* prestigeSourceFile */ "b"])(flume);
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxClose"])();
});
const noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxGetNoButton"])();
noBtn.innerHTML = "Back";
noBtn.addEventListener("click", function() {
Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxClose"])();
});
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 104 */,
/* 105 */,
/* 106 */,
/* 107 */
/*!*******************************************!*\
!*** ./src/Corporation/data/Constants.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorporationConstants = void 0;
const CyclesPerMarketCycle = 50;
const AllCorporationStates = ["START", "PURCHASE", "PRODUCTION", "SALE", "EXPORT"];
exports.CorporationConstants = {
INITIALSHARES: 1e9,
SHARESPERPRICEUPDATE: 1e6,
IssueNewSharesCooldown: 216e3,
SellSharesCooldown: 18e3,
CyclesPerMarketCycle: CyclesPerMarketCycle,
CyclesPerIndustryStateCycle: CyclesPerMarketCycle / AllCorporationStates.length,
SecsPerMarketCycle: CyclesPerMarketCycle / 5,
Cities: ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"],
WarehouseInitialCost: 5e9,
WarehouseInitialSize: 100,
WarehouseUpgradeBaseCost: 1e9,
OfficeInitialCost: 4e9,
OfficeInitialSize: 3,
OfficeUpgradeBaseCost: 1e9,
BribeThreshold: 100e12,
BribeToRepRatio: 1e9,
ProductProductionCostRatio: 5,
DividendMaxPercentage: 50,
EmployeeSalaryMultiplier: 3,
CyclesPerEmployeeRaise: 400,
EmployeeRaiseAmount: 50,
BaseMaxProducts: 3,
AllCorporationStates: AllCorporationStates,
};
/***/ }),
/* 108 */,
/* 109 */
/*!**************************************************!*\
!*** ./src/PersonObjects/formulas/reputation.ts ***!
\**************************************************/
/*! no static exports found */
/*! exports used: getFactionFieldWorkRepGain, getFactionSecurityWorkRepGain, getHackingWorkRepGain */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFactionFieldWorkRepGain = exports.getFactionSecurityWorkRepGain = exports.getHackingWorkRepGain = void 0;
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
function mult(f) {
let favorMult = 1 + (f.favor / 100);
if (isNaN(favorMult)) {
favorMult = 1;
}
return favorMult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkRepGain;
}
function getHackingWorkRepGain(p, f) {
return (p.hacking_skill + p.intelligence / 3) /
Constants_1.CONSTANTS.MaxSkillLevel * p.faction_rep_mult *
p.getIntelligenceBonus(1) * mult(f);
}
exports.getHackingWorkRepGain = getHackingWorkRepGain;
function getFactionSecurityWorkRepGain(p, f) {
const t = 0.9 * (p.hacking_skill / Constants_1.CONSTANTS.MaxSkillLevel +
p.strength / Constants_1.CONSTANTS.MaxSkillLevel +
p.defense / Constants_1.CONSTANTS.MaxSkillLevel +
p.dexterity / Constants_1.CONSTANTS.MaxSkillLevel +
p.agility / Constants_1.CONSTANTS.MaxSkillLevel +
p.intelligence / Constants_1.CONSTANTS.MaxSkillLevel) / 4.5;
return t * p.faction_rep_mult * mult(f) * p.getIntelligenceBonus(1);
}
exports.getFactionSecurityWorkRepGain = getFactionSecurityWorkRepGain;
function getFactionFieldWorkRepGain(p, f) {
const t = 0.9 * (p.hacking_skill / Constants_1.CONSTANTS.MaxSkillLevel +
p.strength / Constants_1.CONSTANTS.MaxSkillLevel +
p.defense / Constants_1.CONSTANTS.MaxSkillLevel +
p.dexterity / Constants_1.CONSTANTS.MaxSkillLevel +
p.agility / Constants_1.CONSTANTS.MaxSkillLevel +
p.charisma / Constants_1.CONSTANTS.MaxSkillLevel +
p.intelligence / Constants_1.CONSTANTS.MaxSkillLevel) / 5.5;
return t * p.faction_rep_mult * mult(f) * p.getIntelligenceBonus(1);
}
exports.getFactionFieldWorkRepGain = getFactionFieldWorkRepGain;
/***/ }),
/* 110 */,
/* 111 */
/*!********************************************!*\
!*** ./src/StockMarket/data/OrderTypes.ts ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrderTypes = void 0;
var OrderTypes;
(function (OrderTypes) {
OrderTypes["LimitBuy"] = "Limit Buy Order";
OrderTypes["LimitSell"] = "Limit Sell Order";
OrderTypes["StopBuy"] = "Stop Buy Order";
OrderTypes["StopSell"] = "Stop Sell Order";
})(OrderTypes = exports.OrderTypes || (exports.OrderTypes = {}));
/***/ }),
/* 112 */
/*!****************************************!*\
!*** ./src/Netscript/WorkerScripts.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.workerScripts = void 0;
exports.workerScripts = new Map();
/***/ }),
/* 113 */
/*!****************************************!*\
!*** ./utils/helpers/arrayToString.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayToString = void 0;
/**
* Returns the input array as a comma separated string.
*
* Does several things that Array.toString() doesn't do
* - Adds brackets around the array
* - Adds quotation marks around strings
*/
function arrayToString(a) {
const vals = [];
for (let i = 0; i < a.length; ++i) {
let elem = a[i];
if (Array.isArray(elem)) {
elem = arrayToString(elem);
}
else if (typeof elem === "string") {
elem = `"${elem}"`;
}
vals.push(elem);
}
return `[${vals.join(", ")}]`;
}
exports.arrayToString = arrayToString;
/***/ }),
/* 114 */
/*!****************************!*\
!*** ./src/SaveObject.jsx ***!
\****************************/
/*! 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 */ 67);
/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Alias__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 11);
/* 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 */ 15);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Fconf_Fconf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf/Fconf */ 193);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Fconf/FconfSettings */ 39);
/* harmony import */ var _Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Gang/AllGangs */ 85);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Message/MessageHelpers */ 87);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 47);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./ui/createStatusText */ 141);
/* harmony import */ var _ui_createStatusText__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _ExportBonus__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./ExportBonus */ 150);
/* harmony import */ var _ExportBonus__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_ExportBonus__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 49);
/* 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 */ 29);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! decimal.js */ 65);
/* 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 = "";
this.LastExportBonus = "";
}
BitburnerSaveObject.prototype.getSaveString = function () {
this.PlayerSave = JSON.stringify(_Player__WEBPACK_IMPORTED_MODULE_9__["Player"]); // Delete all logs from all running scripts
var TempAllServers = JSON.parse(JSON.stringify(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"]), _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_4__["Factions"]);
this.SpecialServerIpsSave = JSON.stringify(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__["SpecialServerIps"]);
this.AliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__["Aliases"]);
this.GlobalAliasesSave = JSON.stringify(_Alias__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]);
this.MessagesSave = JSON.stringify(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* Messages */ "a"]);
this.StockMarketSave = JSON.stringify(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["StockMarket"]);
this.SettingsSave = JSON.stringify(_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"]);
this.FconfSettingsSave = JSON.stringify(_Fconf_FconfSettings__WEBPACK_IMPORTED_MODULE_6__["FconfSettings"]);
this.VersionSave = JSON.stringify(_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].Version);
this.LastExportBonus = JSON.stringify(_ExportBonus__WEBPACK_IMPORTED_MODULE_17__["LastExportBonus"]);
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].inGang()) {
this.AllGangsSave = JSON.stringify(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__["AllGangs"]);
}
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
return saveString;
};
BitburnerSaveObject.prototype.saveGame = function (db) {
var saveString = this.getSaveString(); // 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.error("Error saving game to IndexedDB: " + e);
};
try {
window.localStorage.setItem("bitburnerSave", saveString);
} catch (e) {
if (e.code == 22) {
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_15__["createStatusText"])("Save failed for localStorage! Check console(F12)");
console.error("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_15__["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_9__["Player"].companyPosition != null && typeof _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition !== "string") {
console.log("Changed Player.companyPosition value to be compatible with v0.41.2");
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition.data.positionName;
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition == null) {
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].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;
}
}
} // This version allowed players to hold multiple jobs
if (ver < "0.43.0") {
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyName !== "" && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition != null && _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition !== "") {
console.log("Copied player's companyName and companyPosition properties to the Player.jobs map for v0.43.0");
_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].jobs[_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyName] = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition;
}
delete _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].companyPosition;
}
}
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_9__["loadPlayer"])(saveObj.PlayerSave);
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["loadAllServers"])(saveObj.AllServersSave);
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["loadCompanies"])(saveObj.CompaniesSave);
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_4__["loadFactions"])(saveObj.FactionsSave);
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__["loadSpecialServerIps"])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])(saveObj.AliasesSave);
} catch (e) {
console.warn(`Could not load Aliases from save`);
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])("");
}
} else {
console.warn(`Save file did not contain an Aliases property`);
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])(saveObj.GlobalAliasesSave);
} catch (e) {
console.warn(`Could not load GlobalAliases from save`);
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])("");
}
} else {
console.warn(`Save file did not contain a GlobalAliases property`);
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* loadMessages */ "d"])(saveObj.MessagesSave);
} catch (e) {
console.warn(`Could not load Messages from save`);
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
} else {
console.warn(`Save file did not contain a Messages property`);
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])(saveObj.StockMarketSave);
} catch (e) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])("");
}
} else {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].load(saveObj.SettingsSave);
} catch (e) {
console.error("ERROR: Failed to parse Settings. Re-initing default values");
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].init();
}
} else {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].init();
}
if (saveObj.hasOwnProperty("FconfSettingsSave")) {
try {
Object(_Fconf_Fconf__WEBPACK_IMPORTED_MODULE_5__["loadFconf"])(saveObj.FconfSettingsSave);
} catch (e) {
console.error("ERROR: Failed to parse .fconf Settings.");
}
}
if (saveObj.hasOwnProperty("LastExportBonus")) {
try {
_ExportBonus__WEBPACK_IMPORTED_MODULE_17__["setLastExportBonus"](JSON.parse(saveObj.LastExportBonus));
} catch (err) {
_ExportBonus__WEBPACK_IMPORTED_MODULE_17__["setLastExportBonus"](new Date().getTime());
console.error("ERROR: Failed to parse .fconf Settings " + err);
}
}
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_2__["CONSTANTS"].Version) {
createNewUpdateText();
}
} catch (e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__["loadAllGangs"])(saveObj.AllGangsSave);
} catch (e) {
console.error("ERROR: Failed to parse AllGangsSave: " + e);
}
}
return true;
}
function loadImportedGame(saveObj, saveString) {
var tempSaveObj = null;
var tempPlayer = 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 = 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_21__["default"](tempPlayer.money);
JSON.parse(tempSaveObj.AllServersSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
JSON.parse(tempSaveObj.CompaniesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
JSON.parse(tempSaveObj.FactionsSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
JSON.parse(tempSaveObj.SpecialServerIpsSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
if (tempSaveObj.hasOwnProperty("AliasesSave")) {
try {
JSON.parse(tempSaveObj.AliasesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch (e) {
console.error(`Parsing Aliases save failed: ${e}`);
}
}
if (tempSaveObj.hasOwnProperty("GlobalAliases")) {
try {
JSON.parse(tempSaveObj.AliasesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch (e) {
console.error(`Parsing Global Aliases save failed: ${e}`);
}
}
if (tempSaveObj.hasOwnProperty("MessagesSave")) {
try {
JSON.parse(tempSaveObj.MessagesSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch (e) {
console.error(`Parsing Messages save failed: ${e}`);
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
} else {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
JSON.parse(tempSaveObj.StockMarketSave, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_20__["Reviver"]);
} catch (e) {
console.error(`Parsing StockMarket save failed: ${e}`);
}
}
if (saveObj.hasOwnProperty("LastExportBonus")) {
try {
_ExportBonus__WEBPACK_IMPORTED_MODULE_17__["setLastExportBonus"](JSON.parse(saveObj.LastExportBonus));
} catch (err) {
_ExportBonus__WEBPACK_IMPORTED_MODULE_17__["setLastExportBonus"](new Date().getTime());
console.error("ERROR: Failed to parse .fconf Settings " + err);
}
}
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);
}
}
if (tempPlayer.inGang() && tempSaveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__["loadAllGangs"])(tempSaveObj.AllGangsSave);
} catch (e) {
console.error(`Failed to parse AllGangsSave: {e}`);
throw e;
}
}
} catch (e) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["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_9__["loadPlayer"])(saveObj.PlayerSave);
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["loadAllServers"])(saveObj.AllServersSave);
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_1__["loadCompanies"])(saveObj.CompaniesSave);
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_4__["loadFactions"])(saveObj.FactionsSave);
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__["loadSpecialServerIps"])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])(saveObj.AliasesSave);
} catch (e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadAliases"])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])(saveObj.GlobalAliasesSave);
} catch (e) {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])("");
}
} else {
Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["loadGlobalAliases"])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* loadMessages */ "d"])(saveObj.MessagesSave);
} catch (e) {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
} else {
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_8__[/* initMessages */ "c"])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])(saveObj.StockMarketSave);
} catch (e) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])("");
}
} else {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_14__["loadStockMarket"])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].load(saveObj.SettingsSave);
} catch (e) {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].init();
}
} else {
_Settings_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].init();
}
if (saveObj.hasOwnProperty("FconfSettingsSave")) {
try {
Object(_Fconf_Fconf__WEBPACK_IMPORTED_MODULE_5__["loadFconf"])(saveObj.FconfSettingsSave);
} catch (e) {
console.error("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_2__["CONSTANTS"].Version) {
createNewUpdateText();
}
} catch (e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_7__["loadAllGangs"])(saveObj.AllGangsSave);
} catch (e) {
console.error("ERROR: Failed to parse AllGangsSave: " + e);
}
}
saveObject.saveGame(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].indexedDb);
location.reload();
return true;
}
BitburnerSaveObject.prototype.exportGame = function () {
const saveString = this.getSaveString(); // Save file name is based on current timestamp and BitNode
const epochTime = Math.round(Date.now() / 1000);
const bn = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].bitNodeN;
const filename = `bitburnerSave_BN${bn}x${_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_13__["SourceFileFlags"][bn]}_${epochTime}.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 = filename;
document.body.appendChild(a);
a.click();
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_16__["setTimeoutRef"])(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_18__["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 () {
console.log("Successfully deleted save from indexedDb");
};
request.onerror = function (e) {
console.error(`Failed to delete save from indexedDb: ${e}`);
};
Object(_ui_createStatusText__WEBPACK_IMPORTED_MODULE_15__["createStatusText"])("Game deleted!");
};
function createNewUpdateText() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["dialogBoxCreate"])("New update! " + "Please report any bugs/issues through the github repository " + "or the Bitburner subreddit (reddit.com/r/bitburner).
" + _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].LatestUpdate);
}
function createBetaUpdateText() {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["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. " + "Please report any bugs/issues through the github repository (https://github.com/danielyxie/bitburner/issues) " + "or the Bitburner subreddit (reddit.com/r/bitburner).
" + _Constants__WEBPACK_IMPORTED_MODULE_2__["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;
function openImportFileHandler(evt) {
var file = evt.target.files[0];
if (!file) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__["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 */ 143)))
/***/ }),
/* 115 */,
/* 116 */,
/* 117 */,
/* 118 */
/*!************************************!*\
!*** ./src/ui/React/MoneyRate.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoneyRate = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
function MoneyRate(money) {
return Money_1.Money(`${numeralFormat_1.numeralWrapper.formatMoney(money)} / sec`);
}
exports.MoneyRate = MoneyRate;
/***/ }),
/* 119 */,
/* 120 */
/*!*************************************!*\
!*** ./src/Script/ScriptHelpers.js ***!
\*************************************/
/*! exports provided: scriptCalculateOfflineProduction, findRunningScript, findRunningScriptByPid */
/*! exports used: findRunningScript, findRunningScriptByPid, scriptCalculateOfflineProduction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return scriptCalculateOfflineProduction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return findRunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return findRunningScriptByPid; });
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Script */ 228);
/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Script__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./RamCalculationErrorCodes */ 152);
/* harmony import */ var _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _RamCalculations__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./RamCalculations */ 489);
/* harmony import */ var _ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ScriptHelpersTS */ 66);
/* harmony import */ var _ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../engine */ 15);
/* harmony import */ var _Fconf_Fconf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Fconf/Fconf */ 193);
/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../InteractiveTutorial */ 43);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _ScriptEditor_CursorPositions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../ScriptEditor/CursorPositions */ 676);
/* harmony import */ var _ScriptEditor_CursorPositions__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ScriptEditor_CursorPositions__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Settings/SettingEnums */ 222);
/* harmony import */ var _Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Settings_SettingEnums__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Terminal/DirectoryHelpers */ 86);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../TextFile */ 137);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../ui/numeralFormat */ 7);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../utils/helpers/compareArrays */ 195);
/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_20__);
function scriptCalculateOfflineProduction(runningScriptObj) {
//The Player object stores the last update time from when we were online
const thisUpdate = new Date().getTime();
const lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].lastUpdate;
const 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
let confidence = (runningScriptObj.onlineRunningTime) / 14400;
if (confidence >= 1) {confidence = 1;}
//Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
// Grow
for (const ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;}
const serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][ip];
if (serv == null) {continue;}
const timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed);
runningScriptObj.log(`Called on ${serv.hostname} ${timesGrown} times while offline`);
const host = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][runningScriptObj.server];
const growth = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_11__["processSingleServerGrowth"])(serv, timesGrown, _Player__WEBPACK_IMPORTED_MODULE_8__["Player"], host.cpuCores);
runningScriptObj.log(`'${serv.hostname}' grown by ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_17__["numeralWrapper"].format(growth * 100 - 100, '0.000000%')} while offline`);
}
}
// Offline EXP gain
// A script's offline production will always be at most half of its online production.
const expGain = confidence * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed;
_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].gainHackingExp(expGain);
// Update script stats
runningScriptObj.offlineRunningTime += timePassed;
runningScriptObj.offlineExpGained += expGain;
// Weaken
for (const ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;}
const serv = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][ip];
if (serv == null) {continue;}
const host = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][runningScriptObj.server];
const timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed);
runningScriptObj.log(`Called weaken() on ${serv.hostname} ${timesWeakened} times while offline`);
const coreBonus = 1+(host.cpuCores-1)/16;
serv.weaken(_Constants__WEBPACK_IMPORTED_MODULE_4__["CONSTANTS"].ServerWeakenAmount * timesWeakened * coreBonus);
}
}
}
//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_19__["compareArrays"])(server.runningScripts[i].args, args)) {
return server.runningScripts[i];
}
}
return null;
}
//Returns a RunningScript object matching the pid on the
//designated server, and false otherwise
function findRunningScriptByPid(pid, server) {
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].pid === pid) {
return server.runningScripts[i];
}
}
return null;
}
/***/ }),
/* 121 */
/*!*********************************************!*\
!*** ./src/PersonObjects/formulas/skill.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateExp = exports.calculateSkill = void 0;
function calculateSkill(exp, mult = 1) {
return Math.max(Math.floor(mult * (32 * Math.log(exp + 534.5) - 200)), 1);
}
exports.calculateSkill = calculateSkill;
function calculateExp(skill, mult = 1) {
return Math.exp((skill / mult + 200) / 32) - 534.6;
}
exports.calculateExp = calculateExp;
/***/ }),
/* 122 */
/*!*****************************************!*\
!*** ./src/Corporation/Corporation.tsx ***!
\*****************************************/
/*! no static exports found */
/*! exports used: Corporation */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Corporation = void 0;
const CorporationState_1 = __webpack_require__(/*! ./CorporationState */ 1142);
const CorporationUnlockUpgrades_1 = __webpack_require__(/*! ./data/CorporationUnlockUpgrades */ 694);
const CorporationUpgrades_1 = __webpack_require__(/*! ./data/CorporationUpgrades */ 693);
const Warehouse_1 = __webpack_require__(/*! ./Warehouse */ 495);
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 107);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const LiteratureHelpers_1 = __webpack_require__(/*! ../Literature/LiteratureHelpers */ 523);
const LiteratureNames_1 = __webpack_require__(/*! ../Literature/data/LiteratureNames */ 144);
const navigationTracking_1 = __webpack_require__(/*! ../ui/navigationTracking */ 18);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const createElement_1 = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
const isString_1 = __webpack_require__(/*! ../../utils/helpers/isString */ 72);
const removeElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/removeElementById */ 90);
// UI Related Imports
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const react_dom_1 = __importDefault(__webpack_require__(/*! react-dom */ 21));
const Root_1 = __webpack_require__(/*! ./ui/Root */ 1133);
const Routing_1 = __webpack_require__(/*! ./ui/Routing */ 1089);
const decimal_js_1 = __importDefault(__webpack_require__(/*! decimal.js */ 65));
let corpRouting;
let companyManagementDiv;
class Corporation {
constructor(params = {}) {
this.name = "The Corporation";
//A division/business sector is represented by the object:
this.divisions = [];
//Financial stats
this.funds = new decimal_js_1.default(150e9);
this.revenue = new decimal_js_1.default(0);
this.expenses = new decimal_js_1.default(0);
this.fundingRound = 0;
this.public = false; //Publicly traded
this.totalShares = Constants_1.CorporationConstants.INITIALSHARES; // Total existing shares
this.numShares = Constants_1.CorporationConstants.INITIALSHARES; // Total shares owned by player
this.shareSalesUntilPriceUpdate = Constants_1.CorporationConstants.SHARESPERPRICEUPDATE;
this.shareSaleCooldown = 0; // Game cycles until player can sell shares again
this.issueNewSharesCooldown = 0; // Game cycles until player can issue shares again
this.dividendPercentage = 0;
this.dividendTaxPercentage = 50;
this.issuedShares = 0;
this.sharePrice = 0;
this.storedCycles = 0;
this.state = new CorporationState_1.CorporationState();
this.name = params.name ? params.name : "The Corporation";
const numUnlockUpgrades = Object.keys(CorporationUnlockUpgrades_1.CorporationUnlockUpgrades).length;
const numUpgrades = Object.keys(CorporationUpgrades_1.CorporationUpgrades).length;
this.unlockUpgrades = Array(numUnlockUpgrades).fill(0);
this.upgrades = Array(numUpgrades).fill(0);
this.upgradeMultipliers = Array(numUpgrades).fill(1);
}
addFunds(amt) {
if (!isFinite(amt)) {
console.error('Trying to add invalid amount of funds. Report to a developper.');
return;
}
this.funds = this.funds.plus(amt);
}
getState() {
return this.state.getState();
}
storeCycles(numCycles = 1) {
this.storedCycles += numCycles;
}
process(player) {
if (this.storedCycles >= Constants_1.CorporationConstants.CyclesPerIndustryStateCycle) {
const state = this.getState();
const marketCycles = 1;
const gameCycles = (marketCycles * Constants_1.CorporationConstants.CyclesPerIndustryStateCycle);
this.storedCycles -= gameCycles;
this.divisions.forEach((ind) => {
ind.process(marketCycles, state, this);
});
// Process cooldowns
if (this.shareSaleCooldown > 0) {
this.shareSaleCooldown -= gameCycles;
}
if (this.issueNewSharesCooldown > 0) {
this.issueNewSharesCooldown -= gameCycles;
}
//At the start of a new cycle, calculate profits from previous cycle
if (state === "START") {
this.revenue = new decimal_js_1.default(0);
this.expenses = new decimal_js_1.default(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);
});
const profit = this.revenue.minus(this.expenses);
const cycleProfit = profit.times(marketCycles * Constants_1.CorporationConstants.SecsPerMarketCycle);
if (isNaN(this.funds) || this.funds === Infinity || this.funds === -Infinity) {
DialogBox_1.dialogBoxCreate("There was an error calculating your Corporations funds and they got reset to 0. " +
"This is a bug. Please report to game developer.
" +
"(Your funds have been set to $150b for the inconvenience)");
this.funds = new decimal_js_1.default(150e9);
}
// Process dividends
if (this.dividendPercentage > 0 && cycleProfit > 0) {
// Validate input again, just to be safe
if (isNaN(this.dividendPercentage) || this.dividendPercentage < 0 || this.dividendPercentage > Constants_1.CorporationConstants.DividendMaxPercentage) {
console.error(`Invalid Corporation dividend percentage: ${this.dividendPercentage}`);
}
else {
const totalDividends = (this.dividendPercentage / 100) * cycleProfit;
const retainedEarnings = cycleProfit - totalDividends;
const dividendsPerShare = totalDividends / this.totalShares;
const profit = this.numShares * dividendsPerShare * (1 - (this.dividendTaxPercentage / 100));
player.gainMoney(profit);
player.recordMoneySource(profit, "corporation");
this.addFunds(retainedEarnings);
}
}
else {
this.addFunds(cycleProfit);
}
this.updateSharePrice();
}
this.state.nextState();
if (navigationTracking_1.routing.isOn(navigationTracking_1.Page.Corporation))
this.rerender(player);
}
}
determineValuation() {
let val, profit = (this.revenue.minus(this.expenses)).toNumber();
if (this.public) {
// Account for dividends
if (this.dividendPercentage > 0) {
profit *= ((100 - this.dividendPercentage) / 100);
}
val = this.funds.toNumber() + (profit * 85e3);
val *= (Math.pow(1.1, this.divisions.length));
val = Math.max(val, 0);
}
else {
val = 10e9 + Math.max(this.funds.toNumber(), 0) / 3; //Base valuation
if (profit > 0) {
val += (profit * 315e3);
val *= (Math.pow(1.1, this.divisions.length));
}
else {
val = 10e9 * Math.pow(1.1, this.divisions.length);
}
val -= (val % 1e6); //Round down to nearest millionth
}
return val * BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation;
}
getTargetSharePrice() {
// Note: totalShares - numShares is not the same as issuedShares because
// issuedShares does not account for private investors
return this.determineValuation() / (2 * (this.totalShares - this.numShares) + 1);
}
updateSharePrice() {
const targetPrice = this.getTargetSharePrice();
if (this.sharePrice <= targetPrice) {
this.sharePrice *= (1 + (Math.random() * 0.01));
}
else {
this.sharePrice *= (1 - (Math.random() * 0.01));
}
if (this.sharePrice <= 0.01) {
this.sharePrice = 0.01;
}
}
immediatelyUpdateSharePrice() {
this.sharePrice = this.getTargetSharePrice();
}
// Calculates how much money will be made and what the resulting stock price
// will be when the player sells his/her shares
// @return - [Player profit, final stock price, end shareSalesUntilPriceUpdate property]
calculateShareSale(numShares) {
let sharesTracker = numShares;
let sharesUntilUpdate = this.shareSalesUntilPriceUpdate;
let sharePrice = this.sharePrice;
let sharesSold = 0;
let profit = 0;
const maxIterations = Math.ceil(numShares / Constants_1.CorporationConstants.SHARESPERPRICEUPDATE);
if (isNaN(maxIterations) || maxIterations > 10e6) {
console.error(`Something went wrong or unexpected when calculating share sale. Maxiterations calculated to be ${maxIterations}`);
return [0, 0, 0];
}
for (let i = 0; i < maxIterations; ++i) {
if (sharesTracker < sharesUntilUpdate) {
profit += (sharePrice * sharesTracker);
sharesUntilUpdate -= sharesTracker;
break;
}
else {
profit += (sharePrice * sharesUntilUpdate);
sharesUntilUpdate = Constants_1.CorporationConstants.SHARESPERPRICEUPDATE;
sharesTracker -= sharesUntilUpdate;
sharesSold += sharesUntilUpdate;
// Calculate what new share price would be
sharePrice = this.determineValuation() / (2 * (this.totalShares + sharesSold - this.numShares));
}
}
return [profit, sharePrice, sharesUntilUpdate];
}
convertCooldownToString(cd) {
// The cooldown value is based on game cycles. Convert to a simple string
const seconds = cd / 5;
const SecondsPerMinute = 60;
const SecondsPerHour = 3600;
if (seconds > SecondsPerHour) {
return `${Math.floor(seconds / SecondsPerHour)} hour(s)`;
}
else if (seconds > SecondsPerMinute) {
return `${Math.floor(seconds / SecondsPerMinute)} minute(s)`;
}
else {
return `${Math.floor(seconds)} second(s)`;
}
}
//One time upgrades that unlock new features
unlock(upgrade) {
const upgN = upgrade[0], price = upgrade[1];
while (this.unlockUpgrades.length <= upgN) {
this.unlockUpgrades.push(0);
}
if (this.funds.lt(price)) {
DialogBox_1.dialogBoxCreate("You don't have enough funds to unlock this!");
return;
}
this.unlockUpgrades[upgN] = 1;
this.funds = this.funds.minus(price);
// Apply effects for one-time upgrades
if (upgN === 5) {
this.dividendTaxPercentage -= 5;
}
else if (upgN === 6) {
this.dividendTaxPercentage -= 10;
}
}
//Levelable upgrades
upgrade(upgrade) {
const 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);
}
const totalCost = basePrice * Math.pow(priceMult, this.upgrades[upgN]);
if (this.funds.lt(totalCost)) {
DialogBox_1.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 (let i = 0; i < this.divisions.length; ++i) {
const industry = this.divisions[i];
for (const city in industry.warehouses) {
if (industry.warehouses.hasOwnProperty(city) && industry.warehouses[city] instanceof Warehouse_1.Warehouse) {
industry.warehouses[city].updateSize(this, industry);
}
}
}
}
}
getProductionMultiplier() {
const mult = this.upgradeMultipliers[0];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getStorageMultiplier() {
const mult = this.upgradeMultipliers[1];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getDreamSenseGain() {
const gain = this.upgradeMultipliers[2] - 1;
return gain <= 0 ? 0 : gain;
}
getAdvertisingMultiplier() {
const mult = this.upgradeMultipliers[3];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getEmployeeCreMultiplier() {
const mult = this.upgradeMultipliers[4];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getEmployeeChaMultiplier() {
const mult = this.upgradeMultipliers[5];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getEmployeeIntMultiplier() {
const mult = this.upgradeMultipliers[6];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getEmployeeEffMultiplier() {
const mult = this.upgradeMultipliers[7];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getSalesMultiplier() {
const mult = this.upgradeMultipliers[8];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
getScientificResearchMultiplier() {
const mult = this.upgradeMultipliers[9];
if (isNaN(mult) || mult < 1) {
return 1;
}
else {
return mult;
}
}
// Adds the Corporation Handbook (Starter Guide) to the player's home computer.
// This is a lit file that gives introductory info to the player
// This occurs when the player clicks the "Getting Started Guide" button on the overview panel
getStarterGuide(player) {
// Check if player already has Corporation Handbook
const homeComp = player.getHomeComputer();
let hasHandbook = false;
const handbookFn = LiteratureNames_1.LiteratureNames.CorporationManagementHandbook;
for (let i = 0; i < homeComp.messages.length; ++i) {
if (isString_1.isString(homeComp.messages[i]) && homeComp.messages[i] === handbookFn) {
hasHandbook = true;
break;
}
}
if (!hasHandbook) {
homeComp.messages.push(handbookFn);
}
LiteratureHelpers_1.showLiterature(handbookFn);
return;
}
createUI(player) {
companyManagementDiv = createElement_1.createElement("div", {
id: "cmpy-mgmt-container",
position: "fixed",
class: "generic-menupage-container",
});
const game = document.getElementById("entire-game-container");
if (game)
game.appendChild(companyManagementDiv);
corpRouting = new Routing_1.CorporationRouting(this);
this.rerender(player);
}
rerender(player) {
if (companyManagementDiv == null || corpRouting == null) {
console.warn(`Corporation.rerender() called when companyManagementDiv, corpRouting, or eventHandler is null`);
return;
}
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Corporation))
return;
react_dom_1.default.render(react_1.default.createElement(Root_1.CorporationRoot, { corp: this, routing: corpRouting, player: player }), companyManagementDiv);
}
clearUI() {
if (companyManagementDiv instanceof HTMLElement) {
react_dom_1.default.unmountComponentAtNode(companyManagementDiv);
removeElementById_1.removeElementById(companyManagementDiv.id);
}
companyManagementDiv = null;
const character = document.getElementById("character-overview-wrapper");
if (character)
character.style.visibility = "visible";
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Corporation", this);
}
/**
* Initiatizes a Corporation object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Corporation, value.data);
}
}
exports.Corporation = Corporation;
JSONReviver_1.Reviver.constructors.Corporation = Corporation;
/***/ }),
/* 123 */,
/* 124 */,
/* 125 */
/*!********************************!*\
!*** ./src/Faction/Faction.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Faction = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const FactionInfo_1 = __webpack_require__(/*! ./FactionInfo */ 695);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
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;
}
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;
}
let favorGain = 0, rep = this.playerReputation + this.rolloverRep;
let reqdRep = Constants_1.CONSTANTS.FactionReputationToFavorBase *
Math.pow(Constants_1.CONSTANTS.FactionReputationToFavorMult, this.favor);
while (rep > 0) {
if (rep >= reqdRep) {
++favorGain;
rep -= reqdRep;
}
else {
break;
}
reqdRep *= Constants_1.CONSTANTS.FactionReputationToFavorMult;
}
return [favorGain, rep];
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Faction", this);
}
/**
* Initiatizes a Faction object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Faction, value.data);
}
}
exports.Faction = Faction;
JSONReviver_1.Reviver.constructors.Faction = Faction;
/***/ }),
/* 126 */
/*!*********************************!*\
!*** ./src/ui/React/Hashes.tsx ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hashes = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function Hashes(hashes) {
return React.createElement("span", { className: "money-gold samefont" }, typeof hashes === 'number' ? numeralFormat_1.numeralWrapper.formatHashes(hashes) : hashes);
}
exports.Hashes = Hashes;
/***/ }),
/* 127 */
/*!********************************!*\
!*** ./src/BitNode/BitNode.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initBitNodeMultipliers = exports.BitNodes = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ./BitNodeMultipliers */ 19);
class BitNode {
constructor(n, name, desc = "", info = "") {
this.number = n;
this.name = name;
this.desc = desc;
this.info = info;
}
}
exports.BitNodes = {};
exports.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.
" +
"This is the first BitNode that you play through. It has no special " +
"modifications or mechanics.
" +
"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:
" +
"Level 1: 16% " +
"Level 2: 24% " +
"Level 3: 28%");
exports.BitNodes["BitNode2"] = new BitNode(2, "Rise of the Underworld", "From the shadows, they rose", //Gangs
"From the shadows, they rose.
Organized crime groups quickly filled the void of power " +
"left behind from the collapse of Western government in the 2050s. 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.
" +
"In this BitNode:
" +
"Your hacking level is reduced by 20% " +
"The growth rate and maximum amount of money available on servers are significantly decreased " +
"The amount of money gained from crimes and Infiltration is tripled " +
"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 " +
"Every Augmentation in the game will be available through the Factions listed above " +
"For every Faction NOT listed above, reputation gains are halved " +
"You will no longer gain passive reputation with Factions
" +
"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 allows you to form gangs in other BitNodes " +
"once your karma decreases to a certain value. " +
"It also increases the player's crime success rate, crime money, and charisma multipliers by:
" +
"Level 1: 24% " +
"Level 2: 36% " +
"Level 3: 42%");
exports.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.
" +
"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.
" +
"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:
" +
"The price and reputation cost of all Augmentations is tripled " +
"The starting and maximum amount of money on servers is reduced by 75% " +
"Server growth rate is reduced by 80% " +
"You now only need 75 favour with a faction in order to donate to it, rather than 150
" +
"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: " +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.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.
" +
"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.
" +
"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.
" +
"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.");
exports.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.
" +
"In this BitNode:
" +
"The base security level of servers is doubled " +
"The starting money on servers is halved, but the maximum money remains the same " +
"Most methods of earning money now give significantly less " +
"Infiltration gives 50% more reputation and money " +
"Corporations have 50% lower valuations and are therefore less profitable " +
"Augmentations are more expensive " +
"Hacking experience gain rates are reduced
" +
"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.
" +
"In addition, this Source-File will unlock the getBitNodeMultipliers() and getServer() Netscript functions, " +
"as well as the formulas API, and will also raise all of your hacking-related multipliers by:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.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.
" +
"In this BitNode you will be able to access the Bladeburner Division at the NSA, which provides a new mechanic " +
"for progression. Furthermore:
" +
"Hacking and Hacknet Nodes will be less profitable " +
"Your hacking level is reduced by 65% " +
"Hacking experience gain from scripts is reduced by 75% " +
"Corporations have 80% lower valuations and are therefore less profitable " +
"Working for companies is 50% less profitable " +
"Crimes and Infiltration are 25% less profitable
" +
"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:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.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.
" +
"In this BitNode you will be able to access the Bladeburner API, which allows you to access Bladeburner " +
"functionality through Netscript. Furthermore:
" +
"The rank you gain from Bladeburner contracts/operations is reduced by 40% " +
"Bladeburner skills cost twice as many skill points " +
"Augmentations are 3x more expensive " +
"Hacking and Hacknet Nodes will be significantly less profitable " +
"Your hacking level is reduced by 65% " +
"Hacking experience gain from scripts is reduced by 75% " +
"Corporations have 80% lower valuations and are therefore less profitable " +
"Working for companies is 50% less profitable " +
"Crimes and Infiltration are 25% less profitable
" +
"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:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.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.
" +
"In this BitNode:
" +
"You start with $250 million " +
"The only way to earn money is by trading on the stock market " +
"You start with a WSE membership and access to the TIX API " +
"You are able to short stocks and place different types of orders (limit/stop) " +
"You can immediately donate to factions to gain reputation
" +
"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:
" +
"Level 1: Permanent access to WSE and TIX API " +
"Level 2: Ability to short stocks in other BitNodes " +
"Level 3: Ability to use limit/stop orders in other BitNodes
" +
"This Source-File also increases your hacking growth multipliers by: " +
" Level 1: 12% Level 2: 18% Level 3: 21%");
exports.BitNodes["BitNode9"] = new BitNode(9, "Hacktocracy", "Hacknet Unleashed", "When Fulcrum Technologies released their open-source Linux distro Chapeau, it quickly " +
"became the OS of choice for the underground hacking community. Chapeau became especially notorious for " +
"powering the Hacknet, a global, decentralized network used for nefarious purposes. Fulcrum quickly " +
"abandoned the project and dissociated themselves from it.
" +
"This BitNode unlocks the Hacknet Server, an upgraded version of the Hacknet Node. Hacknet Servers generate " +
"hashes, which can be spent on a variety of different upgrades.
" +
"In this BitNode:
" +
"Your stats are significantly decreased " +
"You cannnot purchase additional servers " +
"Hacking is significantly less profitable
" +
"Destroying this BitNode will give you Source-File 9, 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:
" +
"Level 1: Permanently unlocks the Hacknet Server in other BitNodes " +
"Level 2: You start with 128GB of RAM on your home computer when entering a new BitNode " +
"Level 3: Grants a highly-upgraded Hacknet Server when entering a new BitNode
" +
"(Note that the Level 3 effect of this Source-File only applies when entering a new BitNode, NOT " +
"when installing Augmentations)");
exports.BitNodes["BitNode10"] = new BitNode(10, "Digital Carbon", "Your body is not who you are", "In 2084, VitaLife unveiled to the world the Persona Core, a technology that allowed people " +
"to digitize their consciousness. Their consciousness could then be transferred into Synthoids " +
"or other bodies by trasmitting the digitized data. Human bodies became nothing more than 'sleeves' for the " +
"human consciousness. Mankind had finally achieved immortality - at least for those that could afford it.
" +
"This BitNode unlocks Sleeve technology. Sleeve technology allows you to:
" +
"1. Re-sleeve: Purchase and transfer your consciousness into a new body " +
"2. Duplicate Sleeves: Duplicate your consciousness into Synthoids, allowing you to perform different tasks synchronously
" +
"In this BitNode:
" +
"Your stats are significantly decreased " +
"All methods of gaining money are half as profitable (except Stock Market) " +
"Purchased servers are more expensive, have less max RAM, and a lower maximum limit " +
"Augmentations are 5x as expensive and require twice as much reputation
" +
"Destroying this BitNode will give you Source-File 10, or if you already have this Source-File it will " +
"upgrade its level up to a maximum of 3. This Source-File unlocks Sleeve technology in other BitNodes. " +
"Each level of this Source-File also grants you a Duplicate Sleeve");
exports.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.
" +
"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.
" +
"In this BitNode:
" +
"Your hacking stat and experience gain are halved " +
"The starting and maximum amount of money available on servers is significantly decreased " +
"The growth rate of servers is significantly reduced " +
"Weakening a server is twice as effective " +
"Company wages are decreased by 50% " +
"Corporation valuations are 90% lower and are therefore significantly less profitable " +
"Hacknet Node production is significantly decreased " +
"Crime and Infiltration are more lucrative " +
"Augmentations are twice as expensive
" +
"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:
" +
"It also reduces the price increase for every aug bought by:
" +
"Level 1: 4% " +
"Level 2: 6% " +
"Level 3: 7%");
exports.BitNodes["BitNode12"] = new BitNode(12, "The Recursion", "Repeat.", "To iterate is human, to recurse divine.
" +
"Every time this BitNode is destroyed, it becomes slightly harder. Destroying this BitNode will give you Source-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 lets you start any BitNodes with NeuroFlux Governor equal to the level of this source file.");
// Books: Frontera, Shiner
exports.BitNodes["BitNode13"] = new BitNode(13, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes
exports.BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON");
exports.BitNodes["BitNode15"] = new BitNode(15, "", "COMING SOON");
exports.BitNodes["BitNode16"] = new BitNode(16, "", "COMING SOON");
exports.BitNodes["BitNode17"] = new BitNode(17, "", "COMING SOON");
exports.BitNodes["BitNode18"] = new BitNode(18, "", "COMING SOON");
exports.BitNodes["BitNode19"] = new BitNode(19, "", "COMING SOON");
exports.BitNodes["BitNode20"] = new BitNode(20, "", "COMING SOON");
exports.BitNodes["BitNode21"] = new BitNode(21, "", "COMING SOON");
exports.BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON");
exports.BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON");
exports.BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON");
function initBitNodeMultipliers(p) {
if (p.bitNodeN == null) {
p.bitNodeN = 1;
}
for (const mult in BitNodeMultipliers_1.BitNodeMultipliers) {
if (BitNodeMultipliers_1.BitNodeMultipliers.hasOwnProperty(mult)) {
BitNodeMultipliers_1.BitNodeMultipliers[mult] = 1;
}
}
switch (p.bitNodeN) {
case 1: // Source Genesis (every multiplier is 1)
break;
case 2: // Rise of the Underworld
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.8;
BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate = 0.8;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 3;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 3;
BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkRepGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.FactionPassiveRepGain = 0;
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 0;
break;
case 3: // Corporatocracy
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.8;
BitNodeMultipliers_1.BitNodeMultipliers.RepToDonateToFaction = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationRepCost = 3;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = 3;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.HomeComputerRamCost = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 3;
break;
case 4: // The Singularity
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.15;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.05;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ClassGymExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkRepGain = 0.75;
break;
case 5: // Artificial intelligence
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingSecurity = 2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.15;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationRep = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.5;
break;
case 6: // Bladeburner
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.35;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingSecurity = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.FactionPassiveRepGain = 0;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.DaedalusAugsRequirement = 1.166; // Results in 35 Augs needed
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 5;
break;
case 7: // Bladeburner 2079
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerRank = 0.6;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerSkillCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = 3;
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.35;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingSecurity = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 0.75;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.FactionPassiveRepGain = 0;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataApiCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.DaedalusAugsRequirement = 1.166; // Results in 35 Augs needed
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 5;
break;
case 8: // Ghost of Wall Street
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.3;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoneyGain = 0;
BitNodeMultipliers_1.BitNodeMultipliers.ManualHackMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.RepToDonateToFaction = 0;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0;
BitNodeMultipliers_1.BitNodeMultipliers.CodingContractMoney = 0;
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 10;
break;
case 9: // Hacktocracy
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.StrengthLevelMultiplier = 0.45;
BitNodeMultipliers_1.BitNodeMultipliers.DefenseLevelMultiplier = 0.45;
BitNodeMultipliers_1.BitNodeMultipliers.DexterityLevelMultiplier = 0.45;
BitNodeMultipliers_1.BitNodeMultipliers.AgilityLevelMultiplier = 0.45;
BitNodeMultipliers_1.BitNodeMultipliers.CharismaLevelMultiplier = 0.45;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerLimit = 0;
BitNodeMultipliers_1.BitNodeMultipliers.HomeComputerRamCost = 5;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.05;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingSecurity = 2.5;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataCost = 5;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataApiCost = 4;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerRank = 0.9;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerSkillCost = 1.2;
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 3;
break;
case 10: // Digital Carbon
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.StrengthLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.DefenseLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.DexterityLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.AgilityLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.CharismaLevelMultiplier = 0.4;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ManualHackMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CodingContractMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = 5;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationRepCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.HomeComputerRamCost = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerCost = 5;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerLimit = 0.6;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerMaxRam = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerRank = 0.8;
BitNodeMultipliers_1.BitNodeMultipliers.GangKarmaRequirement = 3;
break;
case 11: //The Big Crash
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate = 0.2;
BitNodeMultipliers_1.BitNodeMultipliers.ServerWeakenRate = 2;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = 3;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = 0.5;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = 2;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = 2.5;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationRep = 2.5;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = 0.1;
BitNodeMultipliers_1.BitNodeMultipliers.CodingContractMoney = 0.25;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataCost = 4;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataApiCost = 4;
break;
case 12: { //The Recursion
let sf12Lvl = 0;
for (let i = 0; i < p.sourceFiles.length; i++) {
if (p.sourceFiles[i].n === 12) {
sf12Lvl = p.sourceFiles[i].lvl;
}
}
const inc = Math.pow(1.02, sf12Lvl);
const dec = 1 / inc;
// Multiplier for number of augs needed for Daedalus increases
// up to a maximum of 1.34, which results in 40 Augs required
BitNodeMultipliers_1.BitNodeMultipliers.DaedalusAugsRequirement = Math.min(inc, 1.34);
BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.StrengthLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.DefenseLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.DexterityLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.AgilityLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CharismaLevelMultiplier = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ServerWeakenRate = dec;
//Does not scale, otherwise security might start at 300+
BitNodeMultipliers_1.BitNodeMultipliers.ServerStartingSecurity = 1.5;
BitNodeMultipliers_1.BitNodeMultipliers.HomeComputerRamCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerLimit = dec;
BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerMaxRam = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ManualHackMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ScriptHackMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CodingContractMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.ClassGymExpGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.HackExpGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkRepGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.FactionPassiveRepGain = dec;
BitNodeMultipliers_1.BitNodeMultipliers.RepToDonateToFaction = inc;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationRepCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.AugmentationMoneyCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney = dec;
BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationRep = dec;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataApiCost = inc;
BitNodeMultipliers_1.BitNodeMultipliers.CorporationValuation = dec;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerRank = dec;
BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerSkillCost = inc;
break;
}
default:
console.warn("Player.bitNodeN invalid");
break;
}
}
exports.initBitNodeMultipliers = initBitNodeMultipliers;
/***/ }),
/* 128 */,
/* 129 */
/*!****************************************!*\
!*** ./utils/uiHelpers/createPopup.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPopup = void 0;
const createElement_1 = __webpack_require__(/*! ./createElement */ 51);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 190);
/**
* Creates the necessary DOM elements to present an in-game popup to the player.
* @param id The (hopefully) unique identifier for the popup container.
* @param elems The collection of HTML Elements to show within the popup.
*/
function createPopup(id, elems, options = {}) {
const container = createElement_1.createElement("div", {
class: "popup-box-container",
display: "flex",
id: id,
});
const content = createElement_1.createElement("div", {
class: "popup-box-content",
id: `${id}-content`,
});
for (const elem of elems) {
content.appendChild(elem);
}
// Configurable Options
if (options.backgroundColor) {
content.style.backgroundColor = options.backgroundColor;
}
container.appendChild(content);
getElementById_1.getElementById("entire-game-container").appendChild(container);
return container;
}
exports.createPopup = createPopup;
/***/ }),
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */
/*!***************************************!*\
!*** ./src/Server/ServerPurchases.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.purchaseRamForHomeComputer = exports.purchaseServer = exports.getPurchaseServerMaxRam = exports.getPurchaseServerLimit = exports.getPurchaseServerCost = void 0;
/**
* Implements functions for purchasing servers or purchasing more RAM for
* the home computer
*/
const AllServers_1 = __webpack_require__(/*! ./AllServers */ 20);
const ServerHelpers_1 = __webpack_require__(/*! ./ServerHelpers */ 22);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const YesNoBox_1 = __webpack_require__(/*! ../../utils/YesNoBox */ 61);
const isPowerOfTwo_1 = __webpack_require__(/*! ../../utils/helpers/isPowerOfTwo */ 997);
// Returns the cost of purchasing a server with the given RAM
// Returns Infinity for invalid 'ram' arguments
/**
* @param ram Amount of RAM on purchased server (GB)
* @returns Cost of purchasing the given server. Returns infinity for invalid arguments
*/
function getPurchaseServerCost(ram) {
const sanitizedRam = Math.round(ram);
if (isNaN(sanitizedRam) || !isPowerOfTwo_1.isPowerOfTwo(sanitizedRam)) {
return Infinity;
}
if (sanitizedRam > getPurchaseServerMaxRam()) {
return Infinity;
}
return sanitizedRam * Constants_1.CONSTANTS.BaseCostFor1GBOfRamServer * BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerCost;
}
exports.getPurchaseServerCost = getPurchaseServerCost;
function getPurchaseServerLimit() {
return Math.round(Constants_1.CONSTANTS.PurchasedServerLimit * BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerLimit);
}
exports.getPurchaseServerLimit = getPurchaseServerLimit;
function getPurchaseServerMaxRam() {
const ram = Math.round(Constants_1.CONSTANTS.PurchasedServerMaxRam * BitNodeMultipliers_1.BitNodeMultipliers.PurchasedServerMaxRam);
// Round this to the nearest power of 2
return 1 << 31 - Math.clz32(ram);
}
exports.getPurchaseServerMaxRam = getPurchaseServerMaxRam;
// Manually purchase a server (NOT through Netscript)
function purchaseServer(ram, p) {
const cost = getPurchaseServerCost(ram);
//Check if player has enough money
if (!p.canAfford(cost)) {
DialogBox_1.dialogBoxCreate("You don't have enough money to purchase this server!", false);
return;
}
//Maximum server limit
if (p.purchasedServers.length >= getPurchaseServerLimit()) {
DialogBox_1.dialogBoxCreate("You have reached the maximum limit of " + getPurchaseServerLimit() + " servers. " +
"You cannot purchase any more. You can " +
"delete some of your purchased servers using the deleteServer() Netscript function in a script");
return;
}
const hostname = YesNoBox_1.yesNoTxtInpBoxGetInput();
if (hostname == "") {
DialogBox_1.dialogBoxCreate("You must enter a hostname for your new server!");
return;
}
// Create server
const newServ = ServerHelpers_1.safetlyCreateUniqueServer({
adminRights: true,
hostname: hostname,
ip: AllServers_1.createUniqueRandomIp(),
isConnectedTo: false,
maxRam: ram,
organizationName: "",
purchasedByPlayer: true,
});
AllServers_1.AddToAllServers(newServ);
// Add to Player's purchasedServers array
p.purchasedServers.push(newServ.ip);
// Connect new server to home computer
const homeComputer = p.getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
p.loseMoney(cost);
DialogBox_1.dialogBoxCreate("Server successfully purchased with hostname " + hostname);
}
exports.purchaseServer = purchaseServer;
// Manually upgrade RAM on home computer (NOT through Netscript)
function purchaseRamForHomeComputer(cost, p) {
if (!p.canAfford(cost)) {
DialogBox_1.dialogBoxCreate("You do not have enough money to purchase additional RAM for your home computer");
return;
}
const homeComputer = p.getHomeComputer();
if (homeComputer.maxRam >= Constants_1.CONSTANTS.HomeComputerMaxRam) {
DialogBox_1.dialogBoxCreate(`You cannot upgrade your home computer RAM because it is at its maximum possible value`);
return;
}
homeComputer.maxRam *= 2;
p.loseMoney(cost);
DialogBox_1.dialogBoxCreate("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
}
exports.purchaseRamForHomeComputer = purchaseRamForHomeComputer;
/***/ }),
/* 137 */
/*!*************************!*\
!*** ./src/TextFile.ts ***!
\*************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTextFile = exports.getTextFile = exports.TextFile = void 0;
const SetTimeoutRef_1 = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
const DialogBox_1 = __webpack_require__(/*! ../utils/DialogBox */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 29);
/**
* Represents a plain text file that is typically stored on a server.
*/
class TextFile {
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();
SetTimeoutRef_1.setTimeoutRef(() => {
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}
${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;
}
/**
* Initiatizes a TextFile from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(TextFile, value.data);
}
}
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.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
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.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
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;
/***/ }),
/* 138 */
/*!********************************!*\
!*** ./src/Company/Company.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Company = void 0;
const CompanyPosition_1 = __webpack_require__(/*! ./CompanyPosition */ 286);
const posNames = __importStar(__webpack_require__(/*! ./data/companypositionnames */ 58));
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const DefaultConstructorParams = {
name: "",
info: "",
companyPositions: {},
expMultiplier: 1,
salaryMultiplier: 1,
jobStatReqOffset: 0,
};
class Company {
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);
}
}
hasAgentPositions() {
return (this.companyPositions[posNames.AgentCompanyPositions[0]] != null);
}
hasBusinessConsultantPositions() {
return (this.companyPositions[posNames.BusinessConsultantCompanyPositions[0]] != null);
}
hasBusinessPositions() {
return (this.companyPositions[posNames.BusinessCompanyPositions[0]] != null);
}
hasEmployeePositions() {
return (this.companyPositions[posNames.MiscCompanyPositions[1]] != null);
}
hasITPositions() {
return (this.companyPositions[posNames.ITCompanyPositions[0]] != null);
}
hasSecurityPositions() {
return (this.companyPositions[posNames.SecurityCompanyPositions[2]] != null);
}
hasSoftwareConsultantPositions() {
return (this.companyPositions[posNames.SoftwareConsultantCompanyPositions[0]] != null);
}
hasSoftwarePositions() {
return (this.companyPositions[posNames.SoftwareCompanyPositions[0]] != null);
}
hasWaiterPositions() {
return (this.companyPositions[posNames.MiscCompanyPositions[0]] != null);
}
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];
}
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);
}
/**
* Initiatizes a Company from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Company, value.data);
}
}
exports.Company = Company;
JSONReviver_1.Reviver.constructors.Company = Company;
/***/ }),
/* 139 */
/*!************************************************!*\
!*** ./src/Hacknet/formulas/HacknetServers.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateServerCost = exports.calculateCacheUpgradeCost = exports.calculateCoreUpgradeCost = exports.calculateRamUpgradeCost = exports.calculateLevelUpgradeCost = exports.calculateHashGainRate = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 34);
function calculateHashGainRate(level, ramUsed, maxRam, cores, mult) {
const baseGain = Constants_1.HacknetServerConstants.HashesPerLevel * level;
const ramMultiplier = Math.pow(1.07, Math.log2(maxRam));
const coreMultiplier = 1 + (cores - 1) / 5;
const ramRatio = (1 - ramUsed / maxRam);
return baseGain *
ramMultiplier *
coreMultiplier *
ramRatio *
mult *
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney;
}
exports.calculateHashGainRate = calculateHashGainRate;
function calculateLevelUpgradeCost(startingLevel, extraLevels = 1, costMult = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingLevel >= Constants_1.HacknetServerConstants.MaxLevel) {
return Infinity;
}
const mult = Constants_1.HacknetServerConstants.UpgradeLevelMult;
let totalMultiplier = 0;
let currLevel = startingLevel;
for (let i = 0; i < sanitizedLevels; ++i) {
totalMultiplier += Math.pow(mult, currLevel);
++currLevel;
}
return 10 * Constants_1.HacknetServerConstants.BaseCost * totalMultiplier * costMult;
}
exports.calculateLevelUpgradeCost = calculateLevelUpgradeCost;
function calculateRamUpgradeCost(startingRam, extraLevels = 1, costMult = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingRam >= Constants_1.HacknetServerConstants.MaxRam) {
return Infinity;
}
let totalCost = 0;
let numUpgrades = Math.round(Math.log2(startingRam));
let currentRam = startingRam;
for (let i = 0; i < sanitizedLevels; ++i) {
const baseCost = currentRam * Constants_1.HacknetServerConstants.RamBaseCost;
const mult = Math.pow(Constants_1.HacknetServerConstants.UpgradeRamMult, numUpgrades);
totalCost += (baseCost * mult);
currentRam *= 2;
++numUpgrades;
}
totalCost *= costMult;
return totalCost;
}
exports.calculateRamUpgradeCost = calculateRamUpgradeCost;
function calculateCoreUpgradeCost(startingCores, extraLevels = 1, costMult = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingCores >= Constants_1.HacknetServerConstants.MaxCores) {
return Infinity;
}
const mult = Constants_1.HacknetServerConstants.UpgradeCoreMult;
let totalCost = 0;
let currentCores = startingCores;
for (let i = 0; i < sanitizedLevels; ++i) {
totalCost += Math.pow(mult, currentCores - 1);
++currentCores;
}
totalCost *= Constants_1.HacknetServerConstants.CoreBaseCost;
totalCost *= costMult;
return totalCost;
}
exports.calculateCoreUpgradeCost = calculateCoreUpgradeCost;
function calculateCacheUpgradeCost(startingCache, extraLevels = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingCache >= Constants_1.HacknetServerConstants.MaxCache) {
return Infinity;
}
const mult = Constants_1.HacknetServerConstants.UpgradeCacheMult;
let totalCost = 0;
let currentCache = startingCache;
for (let i = 0; i < sanitizedLevels; ++i) {
totalCost += Math.pow(mult, currentCache - 1);
++currentCache;
}
totalCost *= Constants_1.HacknetServerConstants.CacheBaseCost;
return totalCost;
}
exports.calculateCacheUpgradeCost = calculateCacheUpgradeCost;
function calculateServerCost(n, mult = 1) {
if (n - 1 >= Constants_1.HacknetServerConstants.MaxServers) {
return Infinity;
}
return Constants_1.HacknetServerConstants.BaseCost * Math.pow(Constants_1.HacknetServerConstants.PurchaseMult, n - 1) * mult;
}
exports.calculateServerCost = calculateServerCost;
/***/ }),
/* 140 */,
/* 141 */
/*!************************************!*\
!*** ./src/ui/createStatusText.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: createStatusText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStatusText = void 0;
const SetTimeoutRef_1 = __webpack_require__(/*! ../utils/SetTimeoutRef */ 76);
const getElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 190);
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.style.display = "block";
statusElement.classList.add("status-text");
statusElement.innerText = text;
const handler = () => {
statusElement.innerText = "";
statusElement.style.display = "none";
statusElement.classList.remove("status-text");
};
x = SetTimeoutRef_1.setTimeoutRef(handler, threeSeconds);
}
exports.createStatusText = createStatusText;
/***/ }),
/* 142 */
/*!*******************************************!*\
!*** ./src/Bladeburner/data/Constants.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BladeburnerConstants = void 0;
exports.BladeburnerConstants = {
CityNames: ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"],
CyclesPerSecond: 5,
StaminaGainPerSecond: 0.0085,
BaseStaminaLoss: 0.285,
MaxStaminaToGainFactor: 70000,
DifficultyToTimeFactor: 10,
/**
* The difficulty multiplier affects stamina loss and hp loss of an action. Also affects
* experience gain. Its formula is:
* difficulty ^ exponentialFactor + difficulty / linearFactor
*/
DiffMultExponentialFactor: 0.28,
DiffMultLinearFactor: 650,
/**
* These factors are used to calculate action time.
* They affect how much action time is reduced based on your agility and dexterity
*/
EffAgiLinearFactor: 10e3,
EffDexLinearFactor: 10e3,
EffAgiExponentialFactor: 0.04,
EffDexExponentialFactor: 0.035,
BaseRecruitmentTimeNeeded: 300,
PopulationThreshold: 1e9,
PopulationExponent: 0.7,
ChaosThreshold: 50,
BaseStatGain: 1,
BaseIntGain: 0.003,
ActionCountGrowthPeriod: 480,
RankToFactionRepFactor: 2,
RankNeededForFaction: 25,
ContractSuccessesPerLevel: 3,
OperationSuccessesPerLevel: 2.5,
RanksPerSkillPoint: 3,
ContractBaseMoneyGain: 250e3,
HrcHpGain: 2,
HrcStaminaGain: 1, // Percentage Stamina gained from Hyperbolic Regeneration Chamber
};
/***/ }),
/* 143 */,
/* 144 */
/*!************************************************!*\
!*** ./src/Literature/data/LiteratureNames.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LiteratureNames = void 0;
exports.LiteratureNames = {
HackersStartingHandbook: "hackers-starting-handbook.lit",
CorporationManagementHandbook: "corporation-management-handbook.lit",
HistoryOfSynthoids: "history-of-synthoids.lit",
AGreenTomorrow: "A-Green-Tomorrow.lit",
AlphaOmega: "alpha-omega.lit",
SimulatedReality: "simulated-reality.lit",
BeyondMan: "beyond-man.lit",
BrighterThanTheSun: "brighter-than-the-sun.lit",
DemocracyIsDead: "democracy-is-dead.lit",
Sector12Crime: "sector-12-crime.lit",
ManAndMachine: "man-and-machine.lit",
SecretSocieties: "secret-societies.lit",
TheFailedFrontier: "the-failed-frontier.lit",
CodedIntelligence: "coded-intelligence.lit",
SyntheticMuscles: "synthetic-muscles.lit",
TensionsInTechRace: "tensions-in-tech-race.lit",
CostOfImmortality: "cost-of-immortality.lit",
TheHiddenWorld: "the-hidden-world.lit",
TheNewGod: "the-new-god.lit",
NewTriads: "new-triads.lit",
TheSecretWar: "the-secret-war.lit",
};
/***/ }),
/* 145 */,
/* 146 */,
/* 147 */
/*!************************************************************!*\
!*** ./src/Netscript/WorkerScriptStartStopEventEmitter.ts ***!
\************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkerScriptStartStopEventEmitter = void 0;
/**
* Event emitter that triggers when scripts are started/stopped
*/
const EventEmitter_1 = __webpack_require__(/*! ../utils/EventEmitter */ 487);
exports.WorkerScriptStartStopEventEmitter = new EventEmitter_1.EventEmitter();
/***/ }),
/* 148 */,
/* 149 */
/*!******************************************************!*\
!*** ./utils/uiHelpers/removeChildrenFromElement.ts ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeChildrenFromElement = void 0;
const isString_1 = __webpack_require__(/*! ../helpers/isString */ 72);
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 190);
/**
* 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;
/***/ }),
/* 150 */
/*!*****************************!*\
!*** ./src/ExportBonus.tsx ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setLastExportBonus = exports.onExport = exports.canGetBonus = exports.LastExportBonus = void 0;
const Factions_1 = __webpack_require__(/*! ./Faction/Factions */ 17);
exports.LastExportBonus = 0;
const bonusTimer = 24 * 60 * 60 * 1000; // 24h
function canGetBonus() {
const now = (new Date()).getTime();
if (now - exports.LastExportBonus > bonusTimer)
return true;
return false;
}
exports.canGetBonus = canGetBonus;
function onExport(p) {
if (!canGetBonus())
return;
for (const facName of p.factions) {
Factions_1.Factions[facName].favor++;
}
exports.LastExportBonus = (new Date()).getTime();
}
exports.onExport = onExport;
function setLastExportBonus(unixTime) {
exports.LastExportBonus = unixTime;
}
exports.setLastExportBonus = setLastExportBonus;
/***/ }),
/* 151 */
/*!**************************!*\
!*** ./utils/LogBox.tsx ***!
\**************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logBoxCreate = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const react_dom_1 = __importDefault(__webpack_require__(/*! react-dom */ 21));
const killWorkerScript_1 = __webpack_require__(/*! ../src/Netscript/killWorkerScript */ 70);
const createElement_1 = __webpack_require__(/*! ./uiHelpers/createElement */ 51);
const removeElementById_1 = __webpack_require__(/*! ./uiHelpers/removeElementById */ 90);
let gameContainer;
(function () {
function getGameContainer() {
const container = document.getElementById("entire-game-container");
if (container == null) {
throw new Error(`Failed to find game container DOM element`);
}
gameContainer = container;
document.removeEventListener("DOMContentLoaded", getGameContainer);
}
document.addEventListener("DOMContentLoaded", getGameContainer);
})();
function ScriptLogPopup(props) {
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
react_1.useEffect(() => {
const id = setInterval(rerender, 1000);
return () => clearInterval(id);
}, []);
function close() {
const content = document.getElementById(props.id);
if (content == null)
return;
react_dom_1.default.unmountComponentAtNode(content);
removeElementById_1.removeElementById(props.id);
}
react_1.useEffect(() => {
function closeHandler(event) {
if (event.keyCode === 27) {
close();
}
}
document.addEventListener('keydown', closeHandler);
return () => {
document.removeEventListener('keydown', closeHandler);
};
}, []);
function kill() {
killWorkerScript_1.killWorkerScript(props.script, props.script.server, true);
close();
}
function drag(event) {
event.preventDefault();
let x = event.clientX;
let y = event.clientY;
let left = props.container.offsetLeft + props.container.clientWidth / 2;
let top = props.container.offsetTop + props.container.clientWidth / 5;
function mouseMove(event) {
left += event.clientX - x;
top += event.clientY - y;
props.container.style.left = left + 'px';
props.container.style.top = top + 'px';
// reset right and bottom to avoid the window stretching
props.container.style.right = '';
props.container.style.bottom = '';
x = event.clientX;
y = event.clientY;
}
function mouseUp() {
document.removeEventListener('mouseup', mouseUp);
document.removeEventListener('mousemove', mouseMove);
}
document.addEventListener('mouseup', mouseUp);
document.addEventListener('mousemove', mouseMove);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("div", { className: "log-box-header", onMouseDown: drag },
react_1.default.createElement("p", null,
props.script.filename,
" ",
props.script.args.map((x) => `${x}`).join(' ')),
react_1.default.createElement("div", null,
react_1.default.createElement("button", { className: "log-box-button", onClick: kill }, "Kill Script"),
react_1.default.createElement("button", { className: "log-box-button", onClick: close }, "Close"))),
react_1.default.createElement("div", { className: "log-box-log-container" },
react_1.default.createElement("p", null, props.script.logs.map((line, i) => react_1.default.createElement("span", { key: i },
line,
react_1.default.createElement("br", null)))))));
}
function logBoxCreate(script) {
const id = script.server + "-" + script.filename + script.args.map((x) => `${x}`).join('-');
if (document.getElementById(id) !== null)
return;
const container = createElement_1.createElement("div", {
class: "log-box-container",
id: id,
});
gameContainer.appendChild(container);
react_dom_1.default.render(react_1.default.createElement(ScriptLogPopup, { script: script, id: id, container: container }), container);
}
exports.logBoxCreate = logBoxCreate;
/***/ }),
/* 152 */
/*!************************************************!*\
!*** ./src/Script/RamCalculationErrorCodes.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RamCalculationErrorCode = void 0;
var RamCalculationErrorCode;
(function (RamCalculationErrorCode) {
RamCalculationErrorCode[RamCalculationErrorCode["SyntaxError"] = -1] = "SyntaxError";
RamCalculationErrorCode[RamCalculationErrorCode["ImportError"] = -2] = "ImportError";
RamCalculationErrorCode[RamCalculationErrorCode["URLImportError"] = -3] = "URLImportError";
})(RamCalculationErrorCode = exports.RamCalculationErrorCode || (exports.RamCalculationErrorCode = {}));
/***/ }),
/* 153 */
/*!**********************************************!*\
!*** ./src/Hacknet/formulas/HacknetNodes.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateNodeCost = exports.calculateCoreUpgradeCost = exports.calculateRamUpgradeCost = exports.calculateLevelUpgradeCost = exports.calculateMoneyGainRate = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 34);
function calculateMoneyGainRate(level, ram, cores, mult) {
const gainPerLevel = Constants_1.HacknetNodeConstants.MoneyGainPerLevel;
const levelMult = (level * gainPerLevel);
const ramMult = Math.pow(1.035, ram - 1);
const coresMult = ((cores + 5) / 6);
return levelMult *
ramMult *
coresMult *
mult *
BitNodeMultipliers_1.BitNodeMultipliers.HacknetNodeMoney;
}
exports.calculateMoneyGainRate = calculateMoneyGainRate;
function calculateLevelUpgradeCost(startingLevel, extraLevels = 1, costMult = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingLevel >= Constants_1.HacknetNodeConstants.MaxLevel) {
return Infinity;
}
const mult = Constants_1.HacknetNodeConstants.UpgradeLevelMult;
let totalMultiplier = 0;
let currLevel = startingLevel;
for (let i = 0; i < sanitizedLevels; ++i) {
totalMultiplier += (Constants_1.HacknetNodeConstants.LevelBaseCost * Math.pow(mult, currLevel));
++currLevel;
}
return Constants_1.HacknetNodeConstants.BaseCost / 2 * totalMultiplier * costMult;
}
exports.calculateLevelUpgradeCost = calculateLevelUpgradeCost;
function calculateRamUpgradeCost(startingRam, extraLevels = 1, costMult = 1) {
const sanitizedLevels = Math.round(extraLevels);
if (isNaN(sanitizedLevels) || sanitizedLevels < 1) {
return 0;
}
if (startingRam >= Constants_1.HacknetNodeConstants.MaxRam) {
return Infinity;
}
let totalCost = 0;
let numUpgrades = Math.round(Math.log2(startingRam));
let currentRam = startingRam;
for (let i = 0; i < sanitizedLevels; ++i) {
const baseCost = currentRam * Constants_1.HacknetNodeConstants.RamBaseCost;
const mult = Math.pow(Constants_1.HacknetNodeConstants.UpgradeRamMult, numUpgrades);
totalCost += (baseCost * mult);
currentRam *= 2;
++numUpgrades;
}
totalCost *= costMult;
return totalCost;
}
exports.calculateRamUpgradeCost = calculateRamUpgradeCost;
function calculateCoreUpgradeCost(startingCore, extraLevels = 1, costMult = 1) {
const sanitizedCores = Math.round(extraLevels);
if (isNaN(sanitizedCores) || sanitizedCores < 1) {
return 0;
}
if (startingCore >= Constants_1.HacknetNodeConstants.MaxCores) {
return Infinity;
}
const coreBaseCost = Constants_1.HacknetNodeConstants.CoreBaseCost;
const mult = Constants_1.HacknetNodeConstants.UpgradeCoreMult;
let totalCost = 0;
let currentCores = startingCore;
for (let i = 0; i < sanitizedCores; ++i) {
totalCost += (coreBaseCost * Math.pow(mult, currentCores - 1));
++currentCores;
}
totalCost *= costMult;
return totalCost;
}
exports.calculateCoreUpgradeCost = calculateCoreUpgradeCost;
function calculateNodeCost(n, mult = 1) {
if (n <= 0) {
return 0;
}
return Constants_1.HacknetNodeConstants.BaseCost * Math.pow(Constants_1.HacknetNodeConstants.PurchaseNextMult, n - 1) * mult;
}
exports.calculateNodeCost = calculateNodeCost;
/***/ }),
/* 154 */
/*!******************************!*\
!*** ./src/NetscriptPort.ts ***!
\******************************/
/*! no static exports found */
/*! exports used: NetscriptPort */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NetscriptPort = void 0;
const Settings_1 = __webpack_require__(/*! ./Settings/Settings */ 24);
class NetscriptPort {
constructor() {
this.data = [];
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
write(data) {
this.data.push(data);
if (this.data.length > Settings_1.Settings.MaxPortCapacity) {
return this.data.shift();
}
return null;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
tryWrite(data) {
if (this.data.length >= Settings_1.Settings.MaxPortCapacity) {
return false;
}
this.data.push(data);
return true;
}
read() {
if (this.data.length === 0) {
return "NULL PORT DATA";
}
return this.data.shift();
}
peek() {
if (this.data.length === 0) {
return "NULL PORT DATA";
}
else {
const foo = this.data.slice();
return foo[0];
}
}
full() {
return this.data.length == Settings_1.Settings.MaxPortCapacity;
}
empty() {
return this.data.length === 0;
}
clear() {
this.data.length = 0;
}
}
exports.NetscriptPort = NetscriptPort;
/***/ }),
/* 155 */,
/* 156 */,
/* 157 */,
/* 158 */
/*!*******************************************!*\
!*** ./src/Infiltration/ui/Difficulty.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.interpolate = void 0;
// I could use `any` to simply some of this but I also want to take advantage
// of the type safety that typescript provides. I'm just not sure how in this
// case.
function interpolate(settings, n, out) {
// interpolates between 2 difficulties.
function lerpD(a, b, t) {
// interpolates between 2 numbers.
function lerp(x, y, t) {
return (1 - t) * x + t * y;
}
for (const key of Object.keys(a)) {
out[key] = lerp(a[key], b[key], t);
}
return a;
}
if (n < 0)
return lerpD(settings.Trivial, settings.Trivial, 0);
if (n >= 0 && n < 1)
return lerpD(settings.Trivial, settings.Normal, n);
if (n >= 1 && n < 2)
return lerpD(settings.Normal, settings.Hard, n - 1);
if (n >= 2 && n < 3)
return lerpD(settings.Hard, settings.Impossible, n - 2);
return lerpD(settings.Impossible, settings.Impossible, 0);
}
exports.interpolate = interpolate;
/***/ }),
/* 159 */
/*!*******************************************!*\
!*** ./src/Infiltration/ui/GameTimer.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GameTimer = void 0;
const LinearProgress_1 = __importDefault(__webpack_require__(/*! @material-ui/core/LinearProgress */ 217));
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const styles_1 = __webpack_require__(/*! @material-ui/core/styles */ 471);
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const TimerProgress = styles_1.withStyles(() => ({
bar: {
transition: "none",
backgroundColor: "#adff2f",
},
}))(LinearProgress_1.default);
function GameTimer(props) {
const [v, setV] = react_1.useState(100);
const tick = 200;
react_1.useEffect(() => {
const intervalId = setInterval(() => {
setV(old => {
if (old <= 0)
props.onExpire();
return old - tick / props.millis * 100;
});
}, tick);
return () => {
clearInterval(intervalId);
};
}, []);
// https://stackoverflow.com/questions/55593367/disable-material-uis-linearprogress-animation
// TODO(hydroflame): there's like a bug where it triggers the end before the
// bar physically reaches the end
return (react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement(TimerProgress, { variant: "determinate", value: v })));
}
exports.GameTimer = GameTimer;
/***/ }),
/* 160 */
/*!********************************************!*\
!*** ./src/Infiltration/ui/KeyHandler.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyHandler = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
function KeyHandler(props) {
let elem;
react_1.useEffect(() => elem.focus());
function onKeyDown(event) {
console.log("isTrusted?", event.isTrusted);
if (!event.isTrusted) {
console.log("untrusted event!");
props.onFailure({ automated: true });
return;
}
props.onKeyDown(event);
}
// invisible autofocused element that eats all the keypress for the minigames.
return (react_1.default.createElement("div", { tabIndex: 1, ref: c => elem = c, onKeyDown: onKeyDown }));
}
exports.KeyHandler = KeyHandler;
/***/ }),
/* 161 */
/*!************************************!*\
!*** ./src/ui/React/Accordion.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Accordion = void 0;
/**
* React component to create an accordion element
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
class Accordion extends React.Component {
constructor(props) {
super(props);
this.handleHeaderClick = this.handleHeaderClick.bind(this);
this.state = {
panelOpened: props.panelInitiallyOpened ? props.panelInitiallyOpened : false,
};
}
handleHeaderClick() {
this.setState({
panelOpened: !this.state.panelOpened,
});
}
render() {
let className = "accordion-header";
if (typeof this.props.headerClass === "string") {
className = this.props.headerClass;
}
if (this.state.panelOpened)
className += " active";
return (React.createElement(React.Fragment, null,
React.createElement("button", { className: className, onClick: this.handleHeaderClick }, this.props.headerContent),
React.createElement(AccordionPanel, { opened: this.state.panelOpened, panelClass: this.props.panelClass, panelContent: this.props.panelContent })));
}
}
exports.Accordion = Accordion;
class AccordionPanel extends React.Component {
shouldComponentUpdate(nextProps) {
return this.props.opened || nextProps.opened;
}
render() {
let className = "accordion-panel";
if (typeof this.props.panelClass === "string") {
className = this.props.panelClass;
}
if (!this.props.opened)
return (React.createElement(React.Fragment, null));
return (React.createElement("div", { className: className, style: { display: "block" } }, this.props.panelContent));
}
}
/***/ }),
/* 162 */,
/* 163 */,
/* 164 */
/*!***************************************!*\
!*** ./src/ui/React/CopyableText.tsx ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CopyableText = exports.ClickableTag = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
var ClickableTag;
(function (ClickableTag) {
ClickableTag[ClickableTag["Tag_span"] = 0] = "Tag_span";
ClickableTag[ClickableTag["Tag_h1"] = 1] = "Tag_h1";
})(ClickableTag = exports.ClickableTag || (exports.ClickableTag = {}));
class CopyableText extends React.Component {
constructor(props) {
super(props);
this.copy = this.copy.bind(this);
this.tooltipClasses = this.tooltipClasses.bind(this);
this.textClasses = this.textClasses.bind(this);
this.state = {
tooltipVisible: false,
};
}
copy() {
const copyText = document.createElement("textarea");
copyText.value = this.props.value;
document.body.appendChild(copyText);
copyText.select();
copyText.setSelectionRange(0, 1e10);
document.execCommand("copy");
document.body.removeChild(copyText);
this.setState({ tooltipVisible: true });
setTimeout(() => this.setState({ tooltipVisible: false }), 1000);
}
tooltipClasses() {
let classes = "copy_tooltip_text";
if (this.state.tooltipVisible) {
classes += " copy_tooltip_text_visible";
}
return classes;
}
textClasses() {
let classes = "copy_tooltip noselect text";
if (this.state.tooltipVisible) {
classes += " copy_tooltip_copied";
}
return classes;
}
render() {
switch (this.props.tag) {
case ClickableTag.Tag_h1:
return (React.createElement("h1", { className: this.textClasses(), onClick: this.copy },
this.props.value,
React.createElement("span", { className: this.tooltipClasses() }, "Copied!")));
case ClickableTag.Tag_span:
return (React.createElement("span", { className: this.textClasses(), onClick: this.copy },
React.createElement("b", null, this.props.value),
React.createElement("span", { className: this.tooltipClasses() }, "Copied!")));
}
}
}
exports.CopyableText = CopyableText;
CopyableText.defaultProps = {
//Default span to prevent destroying current clickables
tag: ClickableTag.Tag_span,
};
/***/ }),
/* 165 */
/*!******************************************!*\
!*** ./src/Corporation/IndustryData.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetIndustryResearchTrees = exports.IndustryResearchTrees = exports.IndustryDescriptions = exports.IndustryStartingCosts = exports.Industries = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const BaseResearchTree_1 = __webpack_require__(/*! ./data/BaseResearchTree */ 1129);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
// Map of official names for each Industry
exports.Industries = {
Energy: "Energy",
Utilities: "Water Utilities",
Agriculture: "Agriculture",
Fishing: "Fishing",
Mining: "Mining",
Food: "Food",
Tobacco: "Tobacco",
Chemical: "Chemical",
Pharmaceutical: "Pharmaceutical",
Computer: "Computer Hardware",
Robotics: "Robotics",
Software: "Software",
Healthcare: "Healthcare",
RealEstate: "RealEstate",
};
// Map of how much money it takes to start each industry
exports.IndustryStartingCosts = {
Energy: 225e9,
Utilities: 150e9,
Agriculture: 40e9,
Fishing: 80e9,
Mining: 300e9,
Food: 10e9,
Tobacco: 20e9,
Chemical: 70e9,
Pharmaceutical: 200e9,
Computer: 500e9,
Robotics: 1e12,
Software: 25e9,
Healthcare: 750e9,
RealEstate: 600e9,
};
// Map of description for each industry
exports.IndustryDescriptions = {
Energy: (react_1.default.createElement(react_1.default.Fragment, null,
"Engage in the production and distribution of energy.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Energy),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Utilities: (react_1.default.createElement(react_1.default.Fragment, null,
"Distribute water and provide wastewater services.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Utilities),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Agriculture: (react_1.default.createElement(react_1.default.Fragment, null,
"Cultivate crops and breed livestock to produce food.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Agriculture),
react_1.default.createElement("br", null),
"Recommended starting Industry: YES")),
Fishing: (react_1.default.createElement(react_1.default.Fragment, null,
"Produce food through the breeding and processing of fish and fish products.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Fishing),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Mining: (react_1.default.createElement(react_1.default.Fragment, null,
"Extract and process metals from the earth.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Mining),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Food: (react_1.default.createElement(react_1.default.Fragment, null,
"Create your own restaurants all around the world.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Food),
react_1.default.createElement("br", null),
"Recommended starting Industry: YES")),
Tobacco: (react_1.default.createElement(react_1.default.Fragment, null,
"Create and distribute tobacco and tobacco-related products.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Tobacco),
react_1.default.createElement("br", null),
"Recommended starting Industry: YES")),
Chemical: (react_1.default.createElement(react_1.default.Fragment, null,
"Produce industrial chemicals.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Chemical),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Pharmaceutical: (react_1.default.createElement(react_1.default.Fragment, null,
"Discover, develop, and create new pharmaceutical drugs.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Pharmaceutical),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Computer: (react_1.default.createElement(react_1.default.Fragment, null,
"Develop and manufacture new computer hardware and networking infrastructures.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Computer),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Robotics: (react_1.default.createElement(react_1.default.Fragment, null,
"Develop and create robots.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Robotics),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
Software: (react_1.default.createElement(react_1.default.Fragment, null,
"Develop computer software and create AI Cores.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Software),
react_1.default.createElement("br", null),
"Recommended starting Industry: YES")),
Healthcare: (react_1.default.createElement(react_1.default.Fragment, null,
"Create and manage hospitals.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.Healthcare),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
RealEstate: (react_1.default.createElement(react_1.default.Fragment, null,
"Develop and manage real estate properties.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Starting cost: ",
Money_1.Money(exports.IndustryStartingCosts.RealEstate),
react_1.default.createElement("br", null),
"Recommended starting Industry: NO")),
};
// Map of available Research for each Industry. This data is held in a
// ResearchTree object
exports.IndustryResearchTrees = {
Energy: BaseResearchTree_1.getBaseResearchTreeCopy(),
Utilities: BaseResearchTree_1.getBaseResearchTreeCopy(),
Agriculture: BaseResearchTree_1.getBaseResearchTreeCopy(),
Fishing: BaseResearchTree_1.getBaseResearchTreeCopy(),
Mining: BaseResearchTree_1.getBaseResearchTreeCopy(),
Food: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Tobacco: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Chemical: BaseResearchTree_1.getBaseResearchTreeCopy(),
Pharmaceutical: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Computer: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Robotics: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Software: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
Healthcare: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
RealEstate: BaseResearchTree_1.getProductIndustryResearchTreeCopy(),
};
function resetIndustryResearchTrees() {
exports.IndustryResearchTrees.Energy = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Utilities = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Agriculture = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Fishing = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Mining = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Food = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Tobacco = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Chemical = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Pharmaceutical = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Computer = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Robotics = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Software = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.Healthcare = BaseResearchTree_1.getBaseResearchTreeCopy();
exports.IndustryResearchTrees.RealEstate = BaseResearchTree_1.getBaseResearchTreeCopy();
}
exports.resetIndustryResearchTrees = resetIndustryResearchTrees;
/***/ }),
/* 166 */,
/* 167 */,
/* 168 */
/*!*********************************!*\
!*** ./src/Exploits/Exploit.ts ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
The game cannot block every possible exploits. Specially since one of them is
that you can just edit your save file and that's impragmatic to prevent.
So instead we have source file minus 1. It is not obtained by destroying a
BitNode but instead it is awarded when the player finds innovative ways to break
the game, this serves 2 purpose, [one] the developpers don't have to spend time
trying to implement anti-cheat measures and [two] finding ways to break a
hacking game is very much in the spirit of the game.
Source-File minus 1 is extremely weak because it can be fully level up quickly.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.sanitizeExploits = exports.ExploitName = exports.Exploit = void 0;
var Exploit;
(function (Exploit) {
Exploit["UndocumentedFunctionCall"] = "UndocumentedFunctionCall";
Exploit["Unclickable"] = "Unclickable";
Exploit["PrototypeTampering"] = "PrototypeTampering";
Exploit["Bypass"] = "Bypass";
// To the players reading this. Yes you're supposed to add EditSaveFile by
// editing your save file, yes you could add them all, no we don't care
// that's not the point.
Exploit["EditSaveFile"] = "EditSaveFile";
})(Exploit = exports.Exploit || (exports.Exploit = {}));
const names = {
'UndocumentedFunctionCall': 'by looking beyond the documentation.',
'EditSaveFile': 'by editing your save file.',
'PrototypeTampering': 'by tampering with Numbers prototype.',
'Unclickable': 'by clicking the unclickable.',
'Bypass': 'by circumventing the ram cost of document.',
};
function ExploitName(exploit) {
return names[exploit];
}
exports.ExploitName = ExploitName;
function sanitizeExploits(exploits) {
return exploits.filter((e) => Object.keys(Exploit).includes(e));
}
exports.sanitizeExploits = sanitizeExploits;
/***/ }),
/* 169 */
/*!*****************************!*\
!*** ./src/Crime/Crimes.ts ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Crimes = void 0;
const Crime_1 = __webpack_require__(/*! ./Crime */ 682);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
exports.Crimes = {
Shoplift: new Crime_1.Crime("Shoplift", Constants_1.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_1.Crime("Rob Store", Constants_1.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: 7.5 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
Mug: new Crime_1.Crime("Mug", Constants_1.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_1.Crime("Larceny", Constants_1.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: 15 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
DealDrugs: new Crime_1.Crime("Deal Drugs", Constants_1.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_1.Crime("Bond Forgery", Constants_1.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: 60 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
TraffickArms: new Crime_1.Crime("Traffick Arms", Constants_1.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_1.Crime("Homicide", Constants_1.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_1.Crime("Grand Theft Auto", Constants_1.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: 16 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
Kidnap: new Crime_1.Crime("Kidnap", Constants_1.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: 26 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
Assassination: new Crime_1.Crime("Assassination", Constants_1.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: 65 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
kills: 1,
}),
Heist: new Crime_1.Crime("Heist", Constants_1.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: 130 * Constants_1.CONSTANTS.IntelligenceCrimeBaseExpGain,
}),
};
/***/ }),
/* 170 */,
/* 171 */,
/* 172 */,
/* 173 */
/*!*************************!*\
!*** ./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 _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentation/AugmentationHelpers */ 79);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./BitNode/BitNode */ 127);
/* harmony import */ var _BitNode_BitNode__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Bladeburner/Bladeburner */ 94);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CinematicText */ 450);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Corporation_IndustryData__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Corporation/IndustryData */ 165);
/* harmony import */ var _Corporation_IndustryData__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Corporation_IndustryData__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Faction/Faction */ 125);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 71);
/* harmony import */ var _Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Hacknet/HacknetHelpers */ 25);
/* harmony import */ var _Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Message/MessageHelpers */ 87);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./NetscriptWorker */ 80);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Netscript_Pid__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Netscript/Pid */ 302);
/* harmony import */ var _Netscript_Pid__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Netscript_Pid__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Literature/data/LiteratureNames */ 144);
/* harmony import */ var _Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 47);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Terminal */ 74);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./ui/navigationTracking */ 18);
/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 91);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 90);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 129);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! decimal.js */ 65);
const BitNode8StartingMoney = 250e6;
// Prestige by purchasing augmentation
function prestigeAugmentation() {
// Set Navigation to Terminal screen, for any logic that depends on it
_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_25__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_25__["Page"].Terminal);
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_3__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"]);
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].prestigeAugmentation();
// Now actually go to the Terminal Screen (and reset it)
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* Terminal */ "a"].resetTerminalInput();
_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].loadTerminalContent();
$("#terminal tr:not(:last)").remove();
Object(_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* postNetburnerText */ "b"])();
// Delete all Worker Scripts objects
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__[/* prestigeWorkerScripts */ "c"])();
var homeComp = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer();
// Delete all servers except home computer
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["prestigeAllServers"])();
// Delete Special Server IPs
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["prestigeSpecialServerIps"])(); // Must be done before initForeignServers()
// Reset home computer (only the programs) and add to AllServers
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["AddToAllServers"])(homeComp);
Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_20__["prestigeHomeComputer"])(homeComp);
if (Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "b"])(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].Neurolink) &&
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].Neurolink].owned) {
homeComp.programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].FTPCrackProgram.name);
homeComp.programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].RelaySMTPProgram.name);
}
if (Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "b"])(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].CashRoot) &&
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].CashRoot].owned) {
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].setMoney(1e6);
homeComp.programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].BruteSSHProgram.name);
}
if (Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "b"])(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].PCMatrix) &&
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].PCMatrix].owned) {
homeComp.programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].DeepscanV1.name);
homeComp.programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_8__["Programs"].AutoLink.name);
}
// Re-create foreign servers
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["initForeignServers"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer());
// Gain favor for Companies
for (var member in _Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"]) {
if (_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"].hasOwnProperty(member)) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"][member].gainFavor();
}
}
// Gain favor for factions
for (var member in _Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"].hasOwnProperty(member)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][member].gainFavor();
}
}
// Stop a Terminal action if there is onerror
if (_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"]._actionInProgress) {
_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"]._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* Terminal */ "a"].finishAction(true);
}
// Re-initialize things - This will update any changes
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["initFactions"])(); // Factions must be initialized before augmentations
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* initAugmentations */ "d"])(); // Calls reapplyAllAugmentations() and resets Player multipliers
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].reapplyAllSourceFiles();
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["initCompanies"])();
// Messages
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_14__[/* initMessages */ "c"])();
// Gang
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].inGang()) {
const faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gang.facName];
if (faction instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_10__["Faction"]) {
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_12__["joinFaction"])(faction);
}
}
// Cancel Bladeburner action
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"]) {
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.prestige();
}
// BitNode 8: Ghost of Wall Street
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 8) {_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money = new decimal_js__WEBPACK_IMPORTED_MODULE_31__["default"](BitNode8StartingMoney);}
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 8 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][8] > 0) {
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasWseAccount = true;
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess = true;
}
// Reset Stock market
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__["initStockMarket"])();
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__["initSymbolToStockMap"])();
}
// Refresh Main Menu (the 'World' menu, specifically)
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
// Red Pill
if (Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "b"])(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].TheRedPill) &&
_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].TheRedPill].owned) {
var WorldDaemon = _Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["SpecialServerNames"].WorldDaemon]];
var DaedalusServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["SpecialServerNames"].DaedalusServer]];
if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);
}
}
Object(_Netscript_Pid__WEBPACK_IMPORTED_MODULE_17__["resetPidCounter"])();
}
// Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile(flume) {
Object(_BitNode_BitNode__WEBPACK_IMPORTED_MODULE_3__["initBitNodeMultipliers"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"]);
Object(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["updateSourceFileFlags"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"]);
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].prestigeSourceFile();
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_15__[/* prestigeWorkerScripts */ "c"])(); // Delete all Worker Scripts objects
var homeComp = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer();
// Delete all servers except home computer
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["prestigeAllServers"])(); // Must be done before initForeignServers()
// Delete Special Server IPs
Object(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_22__["prestigeSpecialServerIps"])();
// Reset home computer (only the programs) and add to AllServers
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["AddToAllServers"])(homeComp);
Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_20__["prestigeHomeComputer"])(homeComp);
// Re-create foreign servers
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_19__["initForeignServers"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer());
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][9] >= 2) {
homeComp.setMaxRam(128);
} else if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][1] > 0) {
homeComp.setMaxRam(32);
} else {
homeComp.setMaxRam(8);
}
homeComp.cpuCores = 1;
// Reset favor for Companies
for (var member in _Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"]) {
if (_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"].hasOwnProperty(member)) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["Companies"][member].favor = 0;
}
}
// Reset favor for factions
for (var member in _Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"]) {
if (_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"].hasOwnProperty(member)) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["Factions"][member].favor = 0;
}
}
// Stop a Terminal action if there is one
if (_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"]._actionInProgress) {
_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"]._actionInProgress = false;
_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* Terminal */ "a"].finishAction(true);
}
// Delete all Augmentations
for (var name in _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) {
if (_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) {
delete _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][name];
}
}
// Give levels of NeuroFluxGoverner for Source-File 12. Must be done here before Augmentations are recalculated
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][12] > 0) {
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations.push({name: _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_2__["AugmentationNames"].NeuroFluxGovernor, level: _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][12]})
}
// Re-initialize things - This will update any changes
Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_11__["initFactions"])(); // Factions must be initialized before augmentations
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* initAugmentations */ "d"])(); // Calls reapplyAllAugmentations() and resets Player multipliers
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].reapplyAllSourceFiles();
Object(_Company_Companies__WEBPACK_IMPORTED_MODULE_6__["initCompanies"])();
// Clear terminal
$("#terminal tr:not(:last)").remove();
Object(_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* postNetburnerText */ "b"])();
// Messages
Object(_Message_MessageHelpers__WEBPACK_IMPORTED_MODULE_14__[/* initMessages */ "c"])();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
_Terminal__WEBPACK_IMPORTED_MODULE_24__[/* Terminal */ "a"].resetTerminalInput();
_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].loadTerminalContent();
// BitNode 3: Corporatocracy
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 3) {
homeComp.messages.push(_Literature_data_LiteratureNames__WEBPACK_IMPORTED_MODULE_18__["LiteratureNames"].CorporationManagementHandbook);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["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"].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_5__[/* writeCinematicText */ "b"])(cinematicText).then(function() {
var popupId = "bladeburner-bitnode-start-nsa-notification";
var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_29__["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_29__["createElement"])("br");
var okBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_29__["createElement"])("a", {
class:"a-link-button", innerText:"Got it!", padding:"8px",
clickListener:()=>{
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_28__["removeElementById"])(popupId);
return false;
},
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_30__["createPopup"])(popupId, [txt, brEl, okBtn]);
}).catch(function(e) {
Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_27__["exceptionAlert"])(e);
})
}
// BitNode 8: Ghost of Wall Street
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 8) {_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money = new decimal_js__WEBPACK_IMPORTED_MODULE_31__["default"](BitNode8StartingMoney);}
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 8 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][8] > 0) {
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasWseAccount = true;
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess = true;
}
// Bit Node 10: Digital Carbon
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 10) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_26__["dialogBoxCreate"])("Visit VitaLife in New Tokyo if you'd like to purchase a new sleeve!");
}
// Reset Stock market, gang, and corporation
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasWseAccount) {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__["initStockMarket"])();
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__["initSymbolToStockMap"])();
} else {
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_23__["deleteStockMarket"])();
}
if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].inGang()) clearGangUI();
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gang = null;
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].corporation = null; Object(_Corporation_IndustryData__WEBPACK_IMPORTED_MODULE_7__["resetIndustryResearchTrees"])();
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner = null;
// Source-File 9 (level 3) effect
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][9] >= 3) {
const hserver = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].createHacknetServer();
hserver.level = 100;
hserver.cores = 10;
hserver.cache = 5;
hserver.updateHashRate(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_money_mult);
hserver.updateHashCapacity();
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_13__[/* updateHashManagerCapacity */ "r"])();
}
// Refresh Main Menu (the 'World' menu, specifically)
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
// Gain int exp
if(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_21__["SourceFileFlags"][5] !== 0 && !flume)
_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(300);
Object(_Netscript_Pid__WEBPACK_IMPORTED_MODULE_17__["resetPidCounter"])();
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 174 */
/*!**********************************************!*\
!*** ./src/StockMarket/BuyingAndSelling.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sellShort = exports.shortStock = exports.sellStock = exports.buyStock = void 0;
const StockMarketHelpers_1 = __webpack_require__(/*! ./StockMarketHelpers */ 288);
const PositionTypes_1 = __webpack_require__(/*! ./data/PositionTypes */ 98);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const React = __importStar(__webpack_require__(/*! react */ 0));
/**
* Attempt to buy a stock in the long position
* @param {Stock} stock - Stock to buy
* @param {number} shares - Number of shares to buy
* @param {WorkerScript} workerScript - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} - true if successful, false otherwise
*/
function buyStock(stock, shares, workerScript = null, opts = {}) {
// Validate arguments
shares = Math.round(shares);
if (shares <= 0) {
return false;
}
if (stock == null || isNaN(shares)) {
if (workerScript) {
workerScript.log("buyStock", `Invalid arguments: stock='${stock}' shares='${shares}'`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate("Failed to buy stock. This may be a bug, contact developer");
}
return false;
}
// Does player have enough money?
const totalPrice = StockMarketHelpers_1.getBuyTransactionCost(stock, shares, PositionTypes_1.PositionTypes.Long);
if (totalPrice == null) {
return false;
}
if (Player_1.Player.money.lt(totalPrice)) {
if (workerScript) {
workerScript.log("buyStock", `You do not have enough money to purchase this position. You need ${numeralFormat_1.numeralWrapper.formatMoney(totalPrice)}.`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"You do not have enough money to purchase this. You need ",
Money_1.Money(totalPrice)));
}
return false;
}
// Would this purchase exceed the maximum number of shares?
if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) {
if (workerScript) {
workerScript.log("buyStock", `Purchasing '${shares + stock.playerShares + stock.playerShortShares}' shares would exceed ${stock.symbol}'s maximum (${stock.maxShares}) number of shares`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(`You cannot purchase this many shares. ${stock.symbol} has a maximum of ${numeralFormat_1.numeralWrapper.formatShares(stock.maxShares)} shares.`);
}
return false;
}
const origTotal = stock.playerShares * stock.playerAvgPx;
Player_1.Player.loseMoney(totalPrice);
const newTotal = origTotal + totalPrice - Constants_1.CONSTANTS.StockMarketCommission;
stock.playerShares = Math.round(stock.playerShares + shares);
stock.playerAvgPx = newTotal / stock.playerShares;
StockMarketHelpers_1.processTransactionForecastMovement(stock, shares);
if (opts.rerenderFn != null && typeof opts.rerenderFn === "function") {
opts.rerenderFn();
}
if (workerScript) {
const resultTxt = `Bought ${numeralFormat_1.numeralWrapper.formatShares(shares)} shares of ${stock.symbol} for ${numeralFormat_1.numeralWrapper.formatMoney(totalPrice)}. ` +
`Paid ${numeralFormat_1.numeralWrapper.formatMoney(Constants_1.CONSTANTS.StockMarketCommission)} in commission fees.`;
workerScript.log("buyStock", resultTxt);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"Bought ",
numeralFormat_1.numeralWrapper.formatShares(shares),
" shares of ",
stock.symbol,
" for ",
Money_1.Money(totalPrice),
". Paid ",
Money_1.Money(Constants_1.CONSTANTS.StockMarketCommission),
" in commission fees."));
}
return true;
}
exports.buyStock = buyStock;
/**
* Attempt to sell a stock in the long position
* @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to sell
* @param {WorkerScript} workerScript - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file
* returns {boolean} - true if successfully sells given number of shares OR MAX owned, false otherwise
*/
function sellStock(stock, shares, workerScript = null, opts = {}) {
// Sanitize/Validate arguments
if (stock == null || shares < 0 || isNaN(shares)) {
if (workerScript) {
workerScript.log("sellStock", `Invalid arguments: stock='${stock}' shares='${shares}'`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate("Failed to sell stock. This is probably due to an invalid quantity. Otherwise, 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;
}
const gains = StockMarketHelpers_1.getSellTransactionGain(stock, shares, PositionTypes_1.PositionTypes.Long);
if (gains == null) {
return false;
}
let netProfit = gains - (stock.playerAvgPx * shares);
if (isNaN(netProfit)) {
netProfit = 0;
}
Player_1.Player.gainMoney(gains);
Player_1.Player.recordMoneySource(netProfit, "stock");
if (workerScript) {
workerScript.scriptRef.onlineMoneyMade += netProfit;
Player_1.Player.scriptProdSinceLastAug += netProfit;
}
stock.playerShares = Math.round(stock.playerShares - shares);
if (stock.playerShares === 0) {
stock.playerAvgPx = 0;
}
StockMarketHelpers_1.processTransactionForecastMovement(stock, shares);
if (opts.rerenderFn != null && typeof opts.rerenderFn === "function") {
opts.rerenderFn();
}
if (workerScript) {
const resultTxt = `Sold ${numeralFormat_1.numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` +
`After commissions, you gained a total of ${numeralFormat_1.numeralWrapper.formatMoney(gains)}.`;
workerScript.log("sellStock", resultTxt);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"Sold ",
numeralFormat_1.numeralWrapper.formatShares(shares),
" shares of ",
stock.symbol,
". After commissions, you gained a total of ",
Money_1.Money(gains),
"."));
}
return true;
}
exports.sellStock = sellStock;
/**
* Attempt to buy a stock in the short position
* @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to short
* @param {WorkerScript} workerScript - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} - true if successful, false otherwise
*/
function shortStock(stock, shares, workerScript = null, opts = {}) {
// Validate arguments
shares = Math.round(shares);
if (shares <= 0) {
return false;
}
if (stock == null || isNaN(shares)) {
if (workerScript) {
workerScript.log("shortStock", `Invalid arguments: stock='${stock}' shares='${shares}'`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.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;
}
// Does the player have enough money?
const totalPrice = StockMarketHelpers_1.getBuyTransactionCost(stock, shares, PositionTypes_1.PositionTypes.Short);
if (totalPrice == null) {
return false;
}
if (Player_1.Player.money.lt(totalPrice)) {
if (workerScript) {
workerScript.log("shortStock", "You do not have enough " +
"money to purchase this short position. You need " +
numeralFormat_1.numeralWrapper.formatMoney(totalPrice));
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"You do not have enough money to purchase this short position. You need ",
Money_1.Money(totalPrice)));
}
return false;
}
// Would this purchase exceed the maximum number of shares?
if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) {
if (workerScript) {
workerScript.log("shortStock", `This '${shares + stock.playerShares + stock.playerShortShares}' short shares would exceed ${stock.symbol}'s maximum (${stock.maxShares}) number of shares.`);
}
else if (opts.suppressDialog !== true) {
DialogBox_1.dialogBoxCreate(`You cannot purchase this many shares. ${stock.symbol} has a maximum of ${stock.maxShares} shares.`);
}
return false;
}
const origTotal = stock.playerShortShares * stock.playerAvgShortPx;
Player_1.Player.loseMoney(totalPrice);
const newTotal = origTotal + totalPrice - Constants_1.CONSTANTS.StockMarketCommission;
stock.playerShortShares = Math.round(stock.playerShortShares + shares);
stock.playerAvgShortPx = newTotal / stock.playerShortShares;
StockMarketHelpers_1.processTransactionForecastMovement(stock, shares);
if (opts.rerenderFn != null && typeof opts.rerenderFn === "function") {
opts.rerenderFn();
}
if (workerScript) {
const resultTxt = `Bought a short position of ${numeralFormat_1.numeralWrapper.formatShares(shares)} shares of ${stock.symbol} ` +
`for ${numeralFormat_1.numeralWrapper.formatMoney(totalPrice)}. Paid ${numeralFormat_1.numeralWrapper.formatMoney(Constants_1.CONSTANTS.StockMarketCommission)} ` +
`in commission fees.`;
workerScript.log("shortStock", resultTxt);
}
else if (!opts.suppressDialog) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"Bought a short position of ",
numeralFormat_1.numeralWrapper.formatShares(shares),
" shares of ",
stock.symbol,
" for ",
Money_1.Money(totalPrice),
". Paid ",
Money_1.Money(Constants_1.CONSTANTS.StockMarketCommission),
" in commission fees."));
}
return true;
}
exports.shortStock = shortStock;
/**
* Attempt to sell a stock in the short position
* @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to sell
* @param {WorkerScript} workerScript - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} true if successfully sells given amount OR max owned, false otherwise
*/
function sellShort(stock, shares, workerScript = null, opts = {}) {
if (stock == null || isNaN(shares) || shares < 0) {
if (workerScript) {
workerScript.log("sellShort", `Invalid arguments: stock='${stock}' shares='${shares}'`);
}
else if (!opts.suppressDialog) {
DialogBox_1.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;
}
const origCost = shares * stock.playerAvgShortPx;
const totalGain = StockMarketHelpers_1.getSellTransactionGain(stock, shares, PositionTypes_1.PositionTypes.Short);
if (totalGain == null || isNaN(totalGain) || origCost == null) {
if (workerScript) {
workerScript.log("sellShort", `Failed to sell short position in a stock. This is probably either due to invalid arguments, or a bug`);
}
else if (!opts.suppressDialog) {
DialogBox_1.dialogBoxCreate(`Failed to sell short position in a stock. This is probably either due to invalid arguments, or a bug`);
}
return false;
}
let profit = totalGain - origCost;
if (isNaN(profit)) {
profit = 0;
}
Player_1.Player.gainMoney(totalGain);
Player_1.Player.recordMoneySource(profit, "stock");
if (workerScript) {
workerScript.scriptRef.onlineMoneyMade += profit;
Player_1.Player.scriptProdSinceLastAug += profit;
}
stock.playerShortShares = Math.round(stock.playerShortShares - shares);
if (stock.playerShortShares === 0) {
stock.playerAvgShortPx = 0;
}
StockMarketHelpers_1.processTransactionForecastMovement(stock, shares);
if (opts.rerenderFn != null && typeof opts.rerenderFn === "function") {
opts.rerenderFn();
}
if (workerScript) {
const resultTxt = `Sold your short position of ${numeralFormat_1.numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` +
`After commissions, you gained a total of ${numeralFormat_1.numeralWrapper.formatMoney(totalGain)}`;
workerScript.log("sellShort", resultTxt);
}
else if (!opts.suppressDialog) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"Sold your short position of ",
numeralFormat_1.numeralWrapper.formatShares(shares),
" shares of ",
stock.symbol,
". After commissions, you gained a total of ",
Money_1.Money(totalGain)));
}
return true;
}
exports.sellShort = sellShort;
/***/ }),
/* 175 */
/*!****************************************!*\
!*** ./src/Gang/GangMemberUpgrades.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberUpgrades = void 0;
const upgrades_1 = __webpack_require__(/*! ./data/upgrades */ 486);
const GangMemberUpgrade_1 = __webpack_require__(/*! ./GangMemberUpgrade */ 1053);
exports.GangMemberUpgrades = {};
(function () {
upgrades_1.gangMemberUpgradesMetadata.forEach((e) => {
exports.GangMemberUpgrades[e.name] = new GangMemberUpgrade_1.GangMemberUpgrade(e.name, e.cost, e.upgType, e.mults);
});
})();
/***/ }),
/* 176 */
/*!****************************************!*\
!*** ./src/CodingContractGenerator.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: generateContract, generateRandomContract, generateRandomContractOnHome */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateContract = exports.generateRandomContractOnHome = exports.generateRandomContract = void 0;
const CodingContracts_1 = __webpack_require__(/*! ./CodingContracts */ 93);
const Factions_1 = __webpack_require__(/*! ./Faction/Factions */ 17);
const Player_1 = __webpack_require__(/*! ./Player */ 2);
const AllServers_1 = __webpack_require__(/*! ./Server/AllServers */ 20);
const ServerHelpers_1 = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
const SpecialServerIps_1 = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
const Server_1 = __webpack_require__(/*! ./Server/Server */ 488);
const getRandomInt_1 = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 45);
function generateRandomContract() {
// First select a random problem type
const problemType = getRandomProblemType();
// Then select a random reward type. 'Money' will always be the last reward type
const reward = getRandomReward();
// Choose random server
const randServer = getRandomServer();
const contractFn = getRandomFilename(randServer, reward);
const contract = new CodingContracts_1.CodingContract(contractFn, problemType, reward);
randServer.addContract(contract);
}
exports.generateRandomContract = generateRandomContract;
function generateRandomContractOnHome() {
// First select a random problem type
const problemType = getRandomProblemType();
// Then select a random reward type. 'Money' will always be the last reward type
const reward = getRandomReward();
// Choose random server
const serv = Player_1.Player.getHomeComputer();
const contractFn = getRandomFilename(serv, reward);
const contract = new CodingContracts_1.CodingContract(contractFn, problemType, reward);
serv.addContract(contract);
}
exports.generateRandomContractOnHome = generateRandomContractOnHome;
function generateContract(params) {
// Problem Type
let problemType;
const problemTypes = Object.keys(CodingContracts_1.CodingContractTypes);
if (params.problemType != null && problemTypes.includes(params.problemType)) {
problemType = params.problemType;
}
else {
problemType = getRandomProblemType();
}
// Reward Type - This is always random for now
const reward = getRandomReward();
// Server
let server;
if (params.server != null) {
server = ServerHelpers_1.GetServerByHostname(params.server);
if (server == null) {
server = AllServers_1.AllServers[params.server];
}
if (server == null) {
server = getRandomServer();
}
}
else {
server = getRandomServer();
}
// Filename
let fn;
if (params.fn != null) {
fn = params.fn;
}
else {
fn = getRandomFilename(server, reward);
}
const contract = new CodingContracts_1.CodingContract(fn, problemType, reward);
server.addContract(contract);
}
exports.generateContract = generateContract;
// Ensures that a contract's reward type is valid
function sanitizeRewardType(rewardType) {
let type = rewardType; // Create copy
const factionsThatAllowHacking = Player_1.Player.factions.filter((fac) => {
try {
return Factions_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_1.CodingContractRewardType.FactionReputation && factionsThatAllowHacking.length === 0) {
type = CodingContracts_1.CodingContractRewardType.CompanyReputation;
}
if (type === CodingContracts_1.CodingContractRewardType.FactionReputationAll && factionsThatAllowHacking.length === 0) {
type = CodingContracts_1.CodingContractRewardType.CompanyReputation;
}
if (type === CodingContracts_1.CodingContractRewardType.CompanyReputation && Object.keys(Player_1.Player.jobs).length === 0) {
type = CodingContracts_1.CodingContractRewardType.Money;
}
return type;
}
function getRandomProblemType() {
const problemTypes = Object.keys(CodingContracts_1.CodingContractTypes);
const randIndex = getRandomInt_1.getRandomInt(0, problemTypes.length - 1);
return problemTypes[randIndex];
}
function getRandomReward() {
const reward = {
name: "",
type: getRandomInt_1.getRandomInt(0, CodingContracts_1.CodingContractRewardType.Money),
};
reward.type = sanitizeRewardType(reward.type);
// Add additional information based on the reward type
const factionsThatAllowHacking = Player_1.Player.factions.filter((fac) => {
try {
return Factions_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_1.CodingContractRewardType.FactionReputation: {
// Get a random faction that player is a part of. That
// faction must allow hacking contracts
const numFactions = factionsThatAllowHacking.length;
const randFaction = factionsThatAllowHacking[getRandomInt_1.getRandomInt(0, numFactions - 1)];
reward.name = randFaction;
break;
}
case CodingContracts_1.CodingContractRewardType.CompanyReputation: {
const allJobs = Object.keys(Player_1.Player.jobs);
if (allJobs.length > 0) {
reward.name = allJobs[getRandomInt_1.getRandomInt(0, allJobs.length - 1)];
}
else {
reward.type = CodingContracts_1.CodingContractRewardType.Money;
}
break;
}
default:
break;
}
return reward;
}
function getRandomServer() {
const servers = Object.keys(AllServers_1.AllServers);
let randIndex = getRandomInt_1.getRandomInt(0, servers.length - 1);
let randServer = AllServers_1.AllServers[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 instanceof Server_1.Server && !randServer.purchasedByPlayer && randServer.hostname !== SpecialServerIps_1.SpecialServerNames.WorldDaemon) {
break;
}
randIndex = getRandomInt_1.getRandomInt(0, servers.length - 1);
randServer = AllServers_1.AllServers[servers[randIndex]];
}
return randServer;
}
function getRandomFilename(server, reward) {
let contractFn = `contract-${getRandomInt_1.getRandomInt(0, 1e6)}`;
for (let i = 0; i < 1000; ++i) {
if (server.contracts.filter((c) => { return c.fn === contractFn; }).length <= 0) {
break;
}
contractFn = `contract-${getRandomInt_1.getRandomInt(0, 1e6)}`;
}
if (reward.name) {
contractFn += `-${reward.name.replace(/\s/g, "")}`;
}
return contractFn;
}
/***/ }),
/* 177 */
/*!************************************!*\
!*** ./src/Hacknet/HashManager.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: HashManager */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashManager = void 0;
/**
* This is a central class for storing and managing the player's hashes,
* which are generated by Hacknet Servers
*
* It is also used to keep track of what upgrades the player has bought with
* his hashes, and contains method for grabbing the data/multipliers from
* those upgrades
*/
const HashUpgrades_1 = __webpack_require__(/*! ./HashUpgrades */ 241);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class HashManager {
constructor() {
// Max number of hashes this can hold. Equal to the sum of capacities of
// all Hacknet Servers
this.capacity = 0;
// Number of hashes currently in storage
this.hashes = 0;
// Map of Hash Upgrade Name -> levels in that upgrade
this.upgrades = {};
for (const name in HashUpgrades_1.HashUpgrades) {
this.upgrades[name] = 0;
}
}
/**
* Generic helper function for getting a multiplier from a HashUpgrade
*/
getMult(upgName) {
const upg = HashUpgrades_1.HashUpgrades[upgName];
const currLevel = this.upgrades[upgName];
if (upg == null || currLevel == null) {
console.error(`Could not find Hash Study upgrade`);
return 1;
}
return 1 + ((upg.value * currLevel) / 100);
}
/**
* One of the Hash upgrades improves studying. This returns that multiplier
*/
getStudyMult() {
const upgName = "Improve Studying";
return this.getMult(upgName);
}
/**
* One of the Hash upgrades improves gym training. This returns that multiplier
*/
getTrainingMult() {
const upgName = "Improve Gym Training";
return this.getMult(upgName);
}
getUpgrade(upgName) {
const upg = HashUpgrades_1.HashUpgrades[upgName];
if (!upg) {
console.error(`Invalid Upgrade Name given to HashManager.getUpgrade(): ${upgName}`);
return null;
}
return upg;
}
/**
* Get the cost (in hashes) of an upgrade
*/
getUpgradeCost(upgName) {
const upg = this.getUpgrade(upgName);
const currLevel = this.upgrades[upgName];
if (upg == null || currLevel == null) {
console.error(`Invalid Upgrade Name given to HashManager.getUpgradeCost(): ${upgName}`);
return Infinity;
}
return upg.getCost(currLevel);
}
prestige() {
for (const name in HashUpgrades_1.HashUpgrades) {
this.upgrades[name] = 0;
}
this.hashes = 0;
// When prestiging, player's hacknet nodes are always reset. So capacity = 0
this.updateCapacity(0);
}
/**
* Reverts an upgrade and refunds the hashes used to buy it
*/
refundUpgrade(upgName) {
const upg = HashUpgrades_1.HashUpgrades[upgName];
// Reduce the level first, so we get the right cost
--this.upgrades[upgName];
const currLevel = this.upgrades[upgName];
if (upg == null || currLevel == null || currLevel < 0) {
console.error(`Invalid Upgrade Name given to HashManager.upgrade(): ${upgName}`);
return;
}
const cost = upg.getCost(currLevel);
this.hashes += cost;
}
storeHashes(numHashes) {
this.hashes += numHashes;
this.hashes = Math.min(this.hashes, this.capacity);
}
updateCapacity(newCap) {
if (newCap < 0) {
this.capacity = 0;
}
this.capacity = Math.max(newCap, 0);
}
/**
* Returns boolean indicating whether or not the upgrade was successfully purchased
* Note that this does NOT actually implement the effect
*/
upgrade(upgName) {
const upg = HashUpgrades_1.HashUpgrades[upgName];
if (upg == null) {
console.error(`Invalid Upgrade Name given to HashManager.upgrade(): ${upgName}`);
return false;
}
const cost = this.getUpgradeCost(upgName);
if (this.hashes < cost) {
return false;
}
this.hashes -= cost;
++this.upgrades[upgName];
return true;
}
//Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("HashManager", this);
}
// Initiatizes a HashManager object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(HashManager, value.data);
}
}
exports.HashManager = HashManager;
JSONReviver_1.Reviver.constructors.HashManager = HashManager;
/***/ }),
/* 178 */
/*!********************************************!*\
!*** ./src/PersonObjects/Sleeve/Sleeve.ts ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sleeve = void 0;
/**
* Sleeves are bodies that contain the player's cloned consciousness.
* The player can use these bodies to perform different tasks synchronously.
*
* Each sleeve is its own individual, meaning it has its own stats/exp
*
* Sleeves are unlocked in BitNode-10.
*/
const SleeveTaskTypesEnum_1 = __webpack_require__(/*! ./SleeveTaskTypesEnum */ 242);
const Person_1 = __webpack_require__(/*! ../Person */ 683);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
const Crime_1 = __webpack_require__(/*! ../../Crime/Crime */ 682);
const Crimes_1 = __webpack_require__(/*! ../../Crime/Crimes */ 169);
const Companies_1 = __webpack_require__(/*! ../../Company/Companies */ 33);
const Company_1 = __webpack_require__(/*! ../../Company/Company */ 138);
const CompanyPositions_1 = __webpack_require__(/*! ../../Company/CompanyPositions */ 52);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const Faction_1 = __webpack_require__(/*! ../../Faction/Faction */ 125);
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
const FactionWorkTypeEnum_1 = __webpack_require__(/*! ../../Faction/FactionWorkTypeEnum */ 410);
const CityNames_1 = __webpack_require__(/*! ../../Locations/data/CityNames */ 42);
const LocationNames_1 = __webpack_require__(/*! ../../Locations/data/LocationNames */ 40);
const JSONReviver_1 = __webpack_require__(/*! ../../../utils/JSONReviver */ 29);
class Sleeve extends Person_1.Person {
constructor(p = null) {
super();
/**
* Stores the name of the class that the player is currently taking
*/
this.className = "";
/**
* Stores the type of crime the sleeve is currently attempting
* Must match the name of a Crime object
*/
this.crimeType = "";
/**
* Enum value for current task
*/
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Idle;
/**
* Contains details about the sleeve's current task. The info stored
* in this depends on the task type
*
* Faction/Company Work: Name of Faction/Company
* Crime: Money earned if successful
* Class/Gym: Name of university/gym
*/
this.currentTaskLocation = "";
/**
* Maximum amount of time (in milliseconds) that can be spent on current task.
*/
this.currentTaskMaxTime = 0;
/**
* Milliseconds spent on current task
*/
this.currentTaskTime = 0;
/**
* Keeps track of experience earned for other sleeves
*/
this.earningsForSleeves = Person_1.createTaskTracker();
/**
* Keeps track of experience + money earned for player
*/
this.earningsForPlayer = Person_1.createTaskTracker();
/**
* Keeps track of experienced earned in the current task/action
*/
this.earningsForTask = Person_1.createTaskTracker();
/**
* Keeps track of what type of work sleeve is doing for faction, if applicable
*/
this.factionWorkType = FactionWorkTypeEnum_1.FactionWorkType.None;
/**
* Records experience gain rate for the current task
*/
this.gainRatesForTask = Person_1.createTaskTracker();
/**
* String that stores what stat the sleeve is training at the gym
*/
this.gymStatType = "";
/**
* Keeps track of events/notifications for this sleeve
*/
this.logs = [];
/**
* Clone retains 'memory' synchronization (and maybe exp?) upon prestige/installing Augs
*/
this.memory = 1;
/**
* Sleeve shock. Number between 0 and 100
* Trauma/shock that comes with being in a sleeve. Experience earned
* is multipled by shock%. This gets applied before synchronization
*
* Reputation earned is also multiplied by shock%
*/
this.shock = 1;
/**
* Stored number of game "loop" cycles
*/
this.storedCycles = 0;
/**
* Synchronization. Number between 0 and 100
* When experience is earned by sleeve, both the player and the sleeve get
* sync% of the experience earned. Other sleeves get sync^2% of exp
*/
this.sync = 1;
if (p != null) {
this.shockRecovery(p);
}
}
/**
* Commit crimes
*/
commitCrime(p, crimeKey) {
const crime = Crimes_1.Crimes[crimeKey];
if (!(crime instanceof Crime_1.Crime)) {
return false;
}
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
this.gainRatesForTask.hack = crime.hacking_exp * this.hacking_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.str = crime.strength_exp * this.strength_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.def = crime.defense_exp * this.defense_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.dex = crime.dexterity_exp * this.dexterity_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.agi = crime.agility_exp * this.agility_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.cha = crime.charisma_exp * this.charisma_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeExpGain;
this.gainRatesForTask.money = crime.money * this.crime_money_mult * BitNodeMultipliers_1.BitNodeMultipliers.CrimeMoney;
this.currentTaskLocation = String(this.gainRatesForTask.money);
this.crimeType = crimeKey;
this.currentTaskMaxTime = crime.time;
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Crime;
return true;
}
/**
* Called to stop the current task
*/
finishTask(p) {
let retValue = Person_1.createTaskTracker(); // Amount of exp to be gained by other sleeves
if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Crime) {
// For crimes, all experience and money is gained at the end
if (this.currentTaskTime >= this.currentTaskMaxTime) {
const crime = Crimes_1.Crimes[this.crimeType];
if (!(crime instanceof Crime_1.Crime)) {
console.error(`Invalid data stored in sleeve.crimeType: ${this.crimeType}`);
this.resetTaskStatus();
return retValue;
}
if (Math.random() < crime.successRate(this)) {
// Success
const successGainRates = Person_1.createTaskTracker();
const keysForIteration = Object.keys(successGainRates);
for (let i = 0; i < keysForIteration.length; ++i) {
const key = keysForIteration[i];
successGainRates[key] = this.gainRatesForTask[key] * 2;
}
retValue = this.gainExperience(p, successGainRates);
this.gainMoney(p, this.gainRatesForTask);
p.karma -= crime.karma * (this.sync / 100);
}
else {
retValue = this.gainExperience(p, this.gainRatesForTask);
}
// Do not reset task to IDLE
this.currentTaskTime = 0;
return retValue;
}
}
else {
// For other crimes... I dont think anything else needs to be done
}
this.resetTaskStatus();
return retValue;
}
/**
* Earn experience for any stats (supports multiple)
* This function also handles experience propogating to Player and other sleeves
*/
gainExperience(p, exp, numCycles = 1, fromOtherSleeve = false) {
// If the experience is coming from another sleeve, it is not multiplied by anything.
// Also the player does not earn anything
if (fromOtherSleeve) {
if (exp.hack > 0) {
this.hacking_exp += exp.hack;
}
if (exp.str > 0) {
this.strength_exp += exp.str;
}
if (exp.def > 0) {
this.defense_exp += exp.def;
}
if (exp.dex > 0) {
this.dexterity_exp += exp.dex;
}
if (exp.agi > 0) {
this.agility_exp += exp.agi;
}
if (exp.cha > 0) {
this.charisma_exp += exp.cha;
}
return Person_1.createTaskTracker();
}
// Experience is first multiplied by shock. Then 'synchronization'
// is accounted for
const multFac = (this.shock / 100) * (this.sync / 100) * numCycles;
const pHackExp = exp.hack * multFac;
const pStrExp = exp.str * multFac;
const pDefExp = exp.def * multFac;
const pDexExp = exp.dex * multFac;
const pAgiExp = exp.agi * multFac;
const pChaExp = exp.cha * multFac;
// Experience is gained by both this sleeve and player
if (pHackExp > 0) {
this.hacking_exp += pHackExp;
p.gainHackingExp(pHackExp);
this.earningsForPlayer.hack += pHackExp;
this.earningsForTask.hack += pHackExp;
}
if (pStrExp > 0) {
this.strength_exp += pStrExp;
p.gainStrengthExp(pStrExp);
this.earningsForPlayer.str += pStrExp;
this.earningsForTask.str += pStrExp;
}
if (pDefExp > 0) {
this.defense_exp += pDefExp;
p.gainDefenseExp(pDefExp);
this.earningsForPlayer.def += pDefExp;
this.earningsForTask.def += pDefExp;
}
if (pDexExp > 0) {
this.dexterity_exp += pDexExp;
p.gainDexterityExp(pDexExp);
this.earningsForPlayer.dex += pDexExp;
this.earningsForTask.dex += pDexExp;
}
if (pAgiExp > 0) {
this.agility_exp += pAgiExp;
p.gainAgilityExp(pAgiExp);
this.earningsForPlayer.agi += pAgiExp;
this.earningsForTask.agi += pAgiExp;
}
if (pChaExp > 0) {
this.charisma_exp += pChaExp;
p.gainCharismaExp(pChaExp);
this.earningsForPlayer.cha += pChaExp;
this.earningsForTask.cha += pChaExp;
}
// Record earnings for other sleeves
this.earningsForSleeves.hack += (pHackExp * (this.sync / 100));
this.earningsForSleeves.str += (pStrExp * (this.sync / 100));
this.earningsForSleeves.def += (pDefExp * (this.sync / 100));
this.earningsForSleeves.dex += (pDexExp * (this.sync / 100));
this.earningsForSleeves.agi += (pAgiExp * (this.sync / 100));
this.earningsForSleeves.cha += (pChaExp * (this.sync / 100));
// Return the experience to be gained by other sleeves
return {
hack: pHackExp * (this.sync / 100),
str: pStrExp * (this.sync / 100),
def: pDefExp * (this.sync / 100),
dex: pDexExp * (this.sync / 100),
agi: pAgiExp * (this.sync / 100),
cha: pChaExp * (this.sync / 100),
money: 0,
};
}
/**
* Earn money for player
*/
gainMoney(p, task, numCycles = 1) {
const gain = (task.money * numCycles);
this.earningsForTask.money += gain;
this.earningsForPlayer.money += gain;
p.gainMoney(gain);
p.recordMoneySource(gain, 'sleeves');
}
/**
* Returns the cost of upgrading this sleeve's memory by a certain amount
*/
getMemoryUpgradeCost(n) {
const amt = Math.round(n);
if (amt < 0) {
return 0;
}
if (this.memory + amt > 100) {
return this.getMemoryUpgradeCost(100 - this.memory);
}
const mult = 1.02;
const baseCost = 1e12;
let currCost = 0;
let currMemory = this.memory - 1;
for (let i = 0; i < n; ++i) {
currCost += (Math.pow(mult, currMemory));
++currMemory;
}
return currCost * baseCost;
}
/**
* Gets reputation gain for the current task
* Only applicable when working for company or faction
*/
getRepGain(p) {
if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Faction) {
let favorMult = 1;
const fac = Factions_1.Factions[this.currentTaskLocation];
if (fac != null) {
favorMult = 1 + (fac.favor / 100);
}
switch (this.factionWorkType) {
case FactionWorkTypeEnum_1.FactionWorkType.Hacking:
return this.getFactionHackingWorkRepGain() * (this.shock / 100) * favorMult;
case FactionWorkTypeEnum_1.FactionWorkType.Field:
return this.getFactionFieldWorkRepGain() * (this.shock / 100) * favorMult;
case FactionWorkTypeEnum_1.FactionWorkType.Security:
return this.getFactionSecurityWorkRepGain() * (this.shock / 100) * favorMult;
default:
console.warn(`Invalid Sleeve.factionWorkType property in Sleeve.getRepGain(): ${this.factionWorkType}`);
return 0;
}
}
else if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Company) {
const companyName = this.currentTaskLocation;
const company = Companies_1.Companies[companyName];
if (company == null) {
console.error(`Invalid company found when trying to calculate rep gain: ${companyName}`);
return 0;
}
const companyPosition = CompanyPositions_1.CompanyPositions[p.jobs[companyName]];
if (companyPosition == null) {
console.error(`Invalid company position name found when trying to calculate rep gain: ${p.jobs[companyName]}`);
return 0;
}
const jobPerformance = companyPosition.calculateJobPerformance(this.hacking_skill, this.strength, this.defense, this.dexterity, this.agility, this.charisma);
const favorMult = 1 + (company.favor / 100);
return jobPerformance * this.company_rep_mult * favorMult;
}
else {
console.warn(`Sleeve.getRepGain() called for invalid task type: ${this.currentTask}`);
return 0;
}
}
installAugmentation(aug) {
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.applyAugmentation(aug);
this.augmentations.push({ name: aug.name, level: 1 });
this.updateStatLevels();
}
log(entry) {
const MaxLogSize = 50;
this.logs.push(entry);
if (this.logs.length > MaxLogSize) {
this.logs.shift();
}
}
/**
* Called on every sleeve for a Source File prestige
*/
prestige(p) {
// Reset exp
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
// Reset task-related stuff
this.resetTaskStatus();
this.earningsForSleeves = Person_1.createTaskTracker();
this.earningsForPlayer = Person_1.createTaskTracker();
this.shockRecovery(p);
// Reset augs and multipliers
this.augmentations = [];
this.resetMultipliers();
// Reset sleeve-related stats
this.shock = 1;
this.storedCycles = 0;
this.sync = Math.max(this.memory, 1);
this.logs = [];
}
/**
* Process loop
* Returns an object containing the amount of experience that should be
* transferred to all other sleeves
*/
process(p, numCycles = 1) {
// Only process once every second (5 cycles)
const CyclesPerSecond = 1000 / Constants_1.CONSTANTS.MilliPerCycle;
this.storedCycles += numCycles;
if (this.storedCycles < CyclesPerSecond) {
return null;
}
let time = this.storedCycles * Constants_1.CONSTANTS.MilliPerCycle;
let cyclesUsed = this.storedCycles;
if (this.currentTaskMaxTime !== 0 && this.currentTaskTime + time > this.currentTaskMaxTime) {
time = this.currentTaskMaxTime - this.currentTaskTime;
cyclesUsed = Math.floor(time / Constants_1.CONSTANTS.MilliPerCycle);
if (time < 0 || cyclesUsed < 0) {
console.warn(`Sleeve.process() calculated negative cycle usage`);
time = 0;
cyclesUsed = 0;
}
}
this.currentTaskTime += time;
// Shock gradually goes towards 100
this.shock = Math.min(100, this.shock + (0.0001 * this.storedCycles));
let retValue = Person_1.createTaskTracker();
switch (this.currentTask) {
case SleeveTaskTypesEnum_1.SleeveTaskType.Idle:
break;
case SleeveTaskTypesEnum_1.SleeveTaskType.Class:
case SleeveTaskTypesEnum_1.SleeveTaskType.Gym:
this.updateTaskGainRates(p);
retValue = this.gainExperience(p, this.gainRatesForTask, cyclesUsed);
this.gainMoney(p, this.gainRatesForTask, cyclesUsed);
break;
case SleeveTaskTypesEnum_1.SleeveTaskType.Faction: {
retValue = this.gainExperience(p, this.gainRatesForTask, cyclesUsed);
this.gainMoney(p, this.gainRatesForTask, cyclesUsed);
// Gain faction reputation
const fac = Factions_1.Factions[this.currentTaskLocation];
if (!(fac instanceof Faction_1.Faction)) {
console.error(`Invalid faction for Sleeve task: ${this.currentTaskLocation}`);
break;
}
fac.playerReputation += (this.getRepGain(p) * cyclesUsed);
break;
}
case SleeveTaskTypesEnum_1.SleeveTaskType.Company: {
retValue = this.gainExperience(p, this.gainRatesForTask, cyclesUsed);
this.gainMoney(p, this.gainRatesForTask, cyclesUsed);
const company = Companies_1.Companies[this.currentTaskLocation];
if (!(company instanceof Company_1.Company)) {
console.error(`Invalid company for Sleeve task: ${this.currentTaskLocation}`);
break;
}
company.playerReputation += (this.getRepGain(p) * cyclesUsed);
break;
}
case SleeveTaskTypesEnum_1.SleeveTaskType.Recovery:
this.shock = Math.min(100, this.shock + (0.0002 * cyclesUsed));
break;
case SleeveTaskTypesEnum_1.SleeveTaskType.Synchro:
this.sync = Math.min(100, this.sync + (p.getIntelligenceBonus(0.5) * 0.0002 * cyclesUsed));
break;
default:
break;
}
if (this.currentTaskMaxTime !== 0 && this.currentTaskTime >= this.currentTaskMaxTime) {
if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Crime) {
retValue = this.finishTask(p);
}
else {
this.finishTask(p);
}
}
this.updateStatLevels();
this.storedCycles -= cyclesUsed;
return retValue;
}
/**
* Resets all parameters used to keep information about the current task
*/
resetTaskStatus() {
this.earningsForTask = Person_1.createTaskTracker();
this.gainRatesForTask = Person_1.createTaskTracker();
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Idle;
this.currentTaskTime = 0;
this.currentTaskMaxTime = 0;
this.factionWorkType = FactionWorkTypeEnum_1.FactionWorkType.None;
this.crimeType = "";
this.currentTaskLocation = "";
this.gymStatType = "";
this.className = "";
}
shockRecovery(p) {
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Recovery;
return true;
}
synchronize(p) {
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Synchro;
return true;
}
/**
* Take a course at a university
*/
takeUniversityCourse(p, universityName, className) {
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
// Set exp/money multipliers based on which university.
// Also check that the sleeve is in the right city
let costMult = 1;
switch (universityName.toLowerCase()) {
case LocationNames_1.LocationName.AevumSummitUniversity.toLowerCase():
if (this.city !== CityNames_1.CityName.Aevum) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.AevumSummitUniversity;
costMult = 4;
break;
case LocationNames_1.LocationName.Sector12RothmanUniversity.toLowerCase():
if (this.city !== CityNames_1.CityName.Sector12) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.Sector12RothmanUniversity;
costMult = 3;
break;
case LocationNames_1.LocationName.VolhavenZBInstituteOfTechnology.toLowerCase():
if (this.city !== CityNames_1.CityName.Volhaven) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.VolhavenZBInstituteOfTechnology;
costMult = 5;
break;
default:
return false;
}
// Set experience/money gains based on class
switch (className.toLowerCase()) {
case "study computer science":
break;
case "data structures":
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassDataStructuresBaseCost * costMult);
break;
case "networks":
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassNetworksBaseCost * costMult);
break;
case "algorithms":
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassAlgorithmsBaseCost * costMult);
break;
case "management":
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassManagementBaseCost * costMult);
break;
case "leadership":
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassLeadershipBaseCost * costMult);
break;
default:
return false;
}
this.className = className;
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Class;
return true;
}
/**
* Travel to another City. Costs money from player
*/
travel(p, newCity) {
p.loseMoney(Constants_1.CONSTANTS.TravelCost);
this.city = newCity;
return true;
}
tryBuyAugmentation(p, aug) {
if (!p.canAfford(aug.startingCost)) {
return false;
}
// Verify that this sleeve does not already have that augmentation.
if (this.augmentations.some(a => a.name === aug.name)) {
return false;
}
p.loseMoney(aug.startingCost);
this.installAugmentation(aug);
return true;
}
updateTaskGainRates(p) {
if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Class) {
let expMult = 1;
switch (this.currentTaskLocation.toLowerCase()) {
case LocationNames_1.LocationName.AevumSummitUniversity.toLowerCase():
expMult = 3;
break;
case LocationNames_1.LocationName.Sector12RothmanUniversity.toLowerCase():
expMult = 2;
break;
case LocationNames_1.LocationName.VolhavenZBInstituteOfTechnology.toLowerCase():
expMult = 4;
break;
default:
return;
}
const totalExpMult = expMult * p.hashManager.getStudyMult();
switch (this.className.toLowerCase()) {
case "study computer science":
this.gainRatesForTask.hack = (Constants_1.CONSTANTS.ClassStudyComputerScienceBaseExp * totalExpMult * this.hacking_exp_mult);
break;
case "data structures":
this.gainRatesForTask.hack = (Constants_1.CONSTANTS.ClassDataStructuresBaseExp * totalExpMult * this.hacking_exp_mult);
break;
case "networks":
this.gainRatesForTask.hack = (Constants_1.CONSTANTS.ClassNetworksBaseExp * totalExpMult * this.hacking_exp_mult);
break;
case "algorithms":
this.gainRatesForTask.hack = (Constants_1.CONSTANTS.ClassAlgorithmsBaseExp * totalExpMult * this.hacking_exp_mult);
break;
case "management":
this.gainRatesForTask.cha = (Constants_1.CONSTANTS.ClassManagementBaseExp * totalExpMult * this.charisma_exp_mult);
break;
case "leadership":
this.gainRatesForTask.cha = (Constants_1.CONSTANTS.ClassLeadershipBaseExp * totalExpMult * this.charisma_exp_mult);
break;
default:
break;
}
return;
}
if (this.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Gym) {
// Get gym exp multiplier
let expMult = 1;
switch (this.currentTaskLocation.toLowerCase()) {
case LocationNames_1.LocationName.AevumCrushFitnessGym.toLowerCase():
expMult = 2;
break;
case LocationNames_1.LocationName.AevumSnapFitnessGym.toLowerCase():
expMult = 5;
break;
case LocationNames_1.LocationName.Sector12IronGym.toLowerCase():
expMult = 1;
break;
case LocationNames_1.LocationName.Sector12PowerhouseGym.toLowerCase():
expMult = 10;
break;
case LocationNames_1.LocationName.VolhavenMilleniumFitnessGym:
expMult = 4;
break;
default:
return;
}
// Set stat gain rate
const baseGymExp = 1;
const totalExpMultiplier = p.hashManager.getTrainingMult() * expMult;
const sanitizedStat = this.gymStatType.toLowerCase();
if (sanitizedStat.includes("str")) {
this.gainRatesForTask.str = (baseGymExp * totalExpMultiplier * this.strength_exp_mult);
}
else if (sanitizedStat.includes("def")) {
this.gainRatesForTask.def = (baseGymExp * totalExpMultiplier * this.defense_exp_mult);
}
else if (sanitizedStat.includes("dex")) {
this.gainRatesForTask.dex = (baseGymExp * totalExpMultiplier * this.dexterity_exp_mult);
}
else if (sanitizedStat.includes("agi")) {
this.gainRatesForTask.agi = (baseGymExp * totalExpMultiplier * this.agility_exp_mult);
}
return;
}
console.warn(`Sleeve.updateTaskGainRates() called for unexpected task type ${this.currentTask}`);
}
upgradeMemory(n) {
if (n < 0) {
console.warn(`Sleeve.upgradeMemory() called with negative value: ${n}`);
return;
}
this.memory = Math.min(100, Math.round(this.memory + n));
}
/**
* Start work for one of the player's companies
* Returns boolean indicating success
*/
workForCompany(p, companyName) {
if (!(Companies_1.Companies[companyName] instanceof Company_1.Company) || p.jobs[companyName] == null) {
return false;
}
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
const company = Companies_1.Companies[companyName];
const companyPosition = CompanyPositions_1.CompanyPositions[p.jobs[companyName]];
if (company == null) {
return false;
}
if (companyPosition == null) {
return false;
}
this.gainRatesForTask.money = companyPosition.baseSalary *
company.salaryMultiplier *
this.work_money_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkMoney;
this.gainRatesForTask.hack = companyPosition.hackingExpGain *
company.expMultiplier *
this.hacking_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.gainRatesForTask.str = companyPosition.strengthExpGain *
company.expMultiplier *
this.strength_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.gainRatesForTask.def = companyPosition.defenseExpGain *
company.expMultiplier *
this.defense_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.gainRatesForTask.dex = companyPosition.dexterityExpGain *
company.expMultiplier *
this.dexterity_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.gainRatesForTask.agi = companyPosition.agilityExpGain *
company.expMultiplier *
this.agility_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.gainRatesForTask.cha = companyPosition.charismaExpGain *
company.expMultiplier *
this.charisma_exp_mult *
BitNodeMultipliers_1.BitNodeMultipliers.CompanyWorkExpGain;
this.currentTaskLocation = companyName;
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Company;
this.currentTaskMaxTime = Constants_1.CONSTANTS.MillisecondsPer8Hours;
return true;
}
/**
* Start work for one of the player's factions
* Returns boolean indicating success
*/
workForFaction(p, factionName, workType) {
if (factionName === "") {
return false;
}
if (!(Factions_1.Factions[factionName] instanceof Faction_1.Faction) || !p.factions.includes(factionName)) {
return false;
}
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
const factionInfo = Factions_1.Factions[factionName].getInfo();
// Set type of work (hacking/field/security), and the experience gains
const sanitizedWorkType = workType.toLowerCase();
if (sanitizedWorkType.includes("hack")) {
if (!factionInfo.offerHackingWork) {
return false;
}
this.factionWorkType = FactionWorkTypeEnum_1.FactionWorkType.Hacking;
this.gainRatesForTask.hack = .15 * this.hacking_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
}
else if (sanitizedWorkType.includes("field")) {
if (!factionInfo.offerFieldWork) {
return false;
}
this.factionWorkType = FactionWorkTypeEnum_1.FactionWorkType.Field;
this.gainRatesForTask.hack = .1 * this.hacking_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.str = .1 * this.strength_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.def = .1 * this.defense_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.dex = .1 * this.dexterity_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.agi = .1 * this.agility_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.cha = .1 * this.charisma_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
}
else if (sanitizedWorkType.includes("security")) {
if (!factionInfo.offerSecurityWork) {
return false;
}
this.factionWorkType = FactionWorkTypeEnum_1.FactionWorkType.Security;
this.gainRatesForTask.hack = .1 * this.hacking_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.str = .15 * this.strength_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.def = .15 * this.defense_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.dex = .15 * this.dexterity_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
this.gainRatesForTask.agi = .15 * this.agility_exp_mult * BitNodeMultipliers_1.BitNodeMultipliers.FactionWorkExpGain;
}
else {
return false;
}
this.currentTaskLocation = factionName;
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Faction;
this.currentTaskMaxTime = Constants_1.CONSTANTS.MillisecondsPer20Hours;
return true;
}
/**
* Begin a gym workout task
*/
workoutAtGym(p, gymName, stat) {
if (this.currentTask !== SleeveTaskTypesEnum_1.SleeveTaskType.Idle) {
this.finishTask(p);
}
else {
this.resetTaskStatus();
}
// Set exp/money multipliers based on which university.
// Also check that the sleeve is in the right city
let costMult = 1;
switch (gymName.toLowerCase()) {
case LocationNames_1.LocationName.AevumCrushFitnessGym.toLowerCase():
if (this.city != CityNames_1.CityName.Aevum) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.AevumCrushFitnessGym;
costMult = 3;
break;
case LocationNames_1.LocationName.AevumSnapFitnessGym.toLowerCase():
if (this.city != CityNames_1.CityName.Aevum) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.AevumSnapFitnessGym;
costMult = 10;
break;
case LocationNames_1.LocationName.Sector12IronGym.toLowerCase():
if (this.city != CityNames_1.CityName.Sector12) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.Sector12IronGym;
costMult = 1;
break;
case LocationNames_1.LocationName.Sector12PowerhouseGym.toLowerCase():
if (this.city != CityNames_1.CityName.Sector12) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.Sector12PowerhouseGym;
costMult = 20;
break;
case LocationNames_1.LocationName.VolhavenMilleniumFitnessGym.toLowerCase():
if (this.city != CityNames_1.CityName.Volhaven) {
return false;
}
this.currentTaskLocation = LocationNames_1.LocationName.VolhavenMilleniumFitnessGym;
costMult = 7;
break;
default:
return false;
}
// Set experience/money gains based on class
const sanitizedStat = stat.toLowerCase();
// Set cost
this.gainRatesForTask.money = -1 * (Constants_1.CONSTANTS.ClassGymBaseCost * costMult);
// Validate "stat" argument
if (!sanitizedStat.includes("str")
&& !sanitizedStat.includes("def")
&& !sanitizedStat.includes("dex")
&& !sanitizedStat.includes("agi")) {
return false;
}
this.gymStatType = stat;
this.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Gym;
return true;
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Sleeve", this);
}
/**
* Initiatizes a Sleeve object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Sleeve, value.data);
}
}
exports.Sleeve = Sleeve;
JSONReviver_1.Reviver.constructors.Sleeve = Sleeve;
/***/ }),
/* 179 */
/*!*****************************************!*\
!*** ./src/utils/MoneySourceTracker.ts ***!
\*****************************************/
/*! no static exports found */
/*! exports used: MoneySourceTracker */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoneySourceTracker = void 0;
/**
* This is an object that is used to keep track of where all of the player's
* money is coming from (or going to)
*/
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class MoneySourceTracker {
constructor() {
this.bladeburner = 0;
this.casino = 0;
this.class = 0;
this.codingcontract = 0;
this.corporation = 0;
this.crime = 0;
this.gang = 0;
this.hacking = 0;
this.hacknetnode = 0;
this.hospitalization = 0;
this.infiltration = 0;
this.sleeves = 0;
this.stock = 0;
this.total = 0;
this.work = 0;
}
// Record money earned
record(amt, source) {
const sanitizedSource = source.toLowerCase();
if (typeof this[sanitizedSource] !== "number") {
console.warn(`MoneySourceTracker.record() called with invalid source: ${source}`);
return;
}
this[sanitizedSource] += amt;
this.total += amt;
}
// Reset the money tracker by setting all stats to 0
reset() {
for (const prop in this) {
if (typeof this[prop] === "number") {
this[prop] = 0;
}
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("MoneySourceTracker", this);
}
// Initiatizes a MoneySourceTracker object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(MoneySourceTracker, value.data);
}
}
exports.MoneySourceTracker = MoneySourceTracker;
JSONReviver_1.Reviver.constructors.MoneySourceTracker = MoneySourceTracker;
/***/ }),
/* 180 */,
/* 181 */,
/* 182 */,
/* 183 */,
/* 184 */,
/* 185 */,
/* 186 */,
/* 187 */,
/* 188 */,
/* 189 */
/*!************************************************!*\
!*** ./utils/helpers/createProgressBarText.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createProgressBarText = void 0;
/**
* 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;
/***/ }),
/* 190 */
/*!*******************************************!*\
!*** ./utils/uiHelpers/getElementById.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getElementById = void 0;
/**
* 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;
/***/ }),
/* 191 */
/*!**********************************!*\
!*** ./src/StockMarket/Stock.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stock = exports.StockForecastInfluenceLimit = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
exports.StockForecastInfluenceLimit = 5;
const defaultConstructorParams = {
b: true,
initPrice: 10e3,
marketCap: 1e12,
mv: 1,
name: "",
otlkMag: 0,
spreadPerc: 0,
shareTxForMovement: 1e6,
symbol: "",
};
// Helper function that convert a IMinMaxRange to a number
function toNumber(n) {
let value;
switch (typeof n) {
case "number": {
return n;
}
case "object": {
const range = n;
value = getRandomInt_1.getRandomInt(range.min, range.max);
break;
}
default:
throw Error(`Do not know how to convert the type '${typeof n}' to a number`);
}
if (typeof n === "object" && typeof n.divisor === "number") {
return value / n.divisor;
}
return value;
}
/**
* Represents the valuation of a company in the World Stock Exchange.
*/
class Stock {
constructor(p = defaultConstructorParams) {
this.name = p.name;
this.symbol = p.symbol;
this.price = toNumber(p.initPrice);
this.lastPrice = this.price;
this.playerShares = 0;
this.playerAvgPx = 0;
this.playerShortShares = 0;
this.playerAvgShortPx = 0;
this.mv = toNumber(p.mv);
this.b = p.b;
this.otlkMag = p.otlkMag;
this.otlkMagForecast = this.getAbsoluteForecast();
this.cap = getRandomInt_1.getRandomInt(this.price * 1e3, this.price * 25e3);
this.spreadPerc = toNumber(p.spreadPerc);
this.shareTxForMovement = toNumber(p.shareTxForMovement);
this.shareTxUntilMovement = this.shareTxForMovement;
// Total shares is determined by market cap, and is rounded to nearest 100k
const totalSharesUnrounded = (p.marketCap / this.price);
this.totalShares = Math.round(totalSharesUnrounded / 1e5) * 1e5;
// Max Shares (Outstanding shares) is a percentage of total shares
const outstandingSharePercentage = 0.2;
this.maxShares = Math.round((this.totalShares * outstandingSharePercentage) / 1e5) * 1e5;
}
/**
* Safely set the stock's second-order forecast to a new value
*/
changeForecastForecast(newff) {
this.otlkMagForecast = newff;
if (this.otlkMagForecast > 100) {
this.otlkMagForecast = 100;
}
else if (this.otlkMagForecast < 0) {
this.otlkMagForecast = 0;
}
}
/**
* Set the stock to a new price. Also updates the stock's previous price tracker
*/
changePrice(newPrice) {
this.lastPrice = this.price;
this.price = newPrice;
}
/**
* Change the stock's forecast during a stock market 'tick'.
* The way a stock's forecast changes depends on various internal properties,
* but is ultimately determined by RNG
*/
cycleForecast(changeAmt = 0.1) {
const increaseChance = this.getForecastIncreaseChance();
if (Math.random() < increaseChance) {
// Forecast increases
if (this.b) {
this.otlkMag += changeAmt;
}
else {
this.otlkMag -= changeAmt;
}
}
else {
// Forecast decreases
if (this.b) {
this.otlkMag -= changeAmt;
}
else {
this.otlkMag += changeAmt;
}
}
this.otlkMag = Math.min(this.otlkMag, 50);
if (this.otlkMag < 0) {
this.otlkMag *= -1;
this.b = !this.b;
}
}
/**
* Change's the stock's second-order forecast during a stock market 'tick'.
* The change for the second-order forecast to increase is 50/50
*/
cycleForecastForecast(changeAmt = 0.1) {
if (Math.random() < 0.5) {
this.changeForecastForecast(this.otlkMagForecast + changeAmt);
}
else {
this.changeForecastForecast(this.otlkMagForecast - changeAmt);
}
}
/**
* "Flip" the stock's second-order forecast. This can occur during a
* stock market "cycle" (determined by RNG). It is used to simulate
* RL stock market cycles and introduce volatility
*/
flipForecastForecast() {
const diff = this.otlkMagForecast - 50;
this.otlkMagForecast = 50 + (-1 * diff);
}
/**
* Returns the stock's absolute forecast, which is a number between 0-100
*/
getAbsoluteForecast() {
return this.b ? 50 + this.otlkMag : 50 - this.otlkMag;
}
/**
* Return the price at which YOUR stock is bought (market ask price). Accounts for spread
*/
getAskPrice() {
return this.price * (1 + (this.spreadPerc / 100));
}
/**
* Return the price at which YOUR stock is sold (market bid price). Accounts for spread
*/
getBidPrice() {
return this.price * (1 - (this.spreadPerc / 100));
}
/**
* Returns the chance (0-1 decimal) that a stock has of having its forecast increase
*/
getForecastIncreaseChance() {
const diff = this.otlkMagForecast - this.getAbsoluteForecast();
return (50 + Math.min(Math.max(diff, -45), 45)) / 100;
}
/**
* Changes a stock's forecast. This is used when the stock is influenced
* by a transaction. The stock's forecast always goes towards 50, but the
* movement is capped by a certain threshold/limit
*/
influenceForecast(change) {
if (this.otlkMag > exports.StockForecastInfluenceLimit) {
this.otlkMag = Math.max(exports.StockForecastInfluenceLimit, this.otlkMag - change);
}
}
/**
* Changes a stock's second-order forecast. This is used when the stock is
* influenced by a transaction. The stock's second-order forecast always
* goes towards 50.
*/
influenceForecastForecast(change) {
if (this.otlkMagForecast > 50) {
this.otlkMagForecast -= change;
this.otlkMagForecast = Math.max(50, this.otlkMagForecast);
}
else if (this.otlkMagForecast < 50) {
this.otlkMagForecast += change;
this.otlkMagForecast = Math.min(50, this.otlkMagForecast);
}
}
/**
* Serialize the Stock to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Stock", this);
}
/**
* Initializes a Stock from a JSON save state
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Stock, value.data);
}
}
exports.Stock = Stock;
JSONReviver_1.Reviver.constructors.Stock = Stock;
/***/ }),
/* 192 */
/*!*********************************!*\
!*** ./src/Locations/Cities.ts ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cities = void 0;
exports.Cities = {};
/***/ }),
/* 193 */
/*!****************************!*\
!*** ./src/Fconf/Fconf.js ***!
\****************************/
/*! exports provided: FconfSettings, createFconf, parseFconfSettings, loadFconf */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createFconf", function() { return createFconf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFconfSettings", function() { return parseFconfSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFconf", function() { return loadFconf; });
/* harmony import */ var _FconfSettings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FconfSettings */ 39);
/* harmony import */ var _FconfSettings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FconfSettings", function() { return _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"]; });
/* harmony import */ var acorn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! acorn */ 104);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__);
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(acorn__WEBPACK_IMPORTED_MODULE_1__[/* parse */ "b"])(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 acorn__WEBPACK_IMPORTED_MODULE_1__[/* Node */ "a"]) {
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 acorn__WEBPACK_IMPORTED_MODULE_1__[/* Node */ "a"]) {
queue.push(exp[prop]);
}
}
}
}
setTheme();
setMainMenuStyle();
}
function parseFconfSetting(setting, value) {
setting = String(setting);
value = String(value);
if (setting == null || value == null || _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] == null) {
console.warn(`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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] = value;
break;
case "MAIN_MENU_STYLE":
var value = sanitizeString(value);
if (MainMenuStyleOptions.includes(value)) {
_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] = value;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] = value;
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"]) {
if (_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] === true) {
value = "1";
} else if (_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] === false) {
value = "0";
} else {
value = '"' + String(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"][setting] = tempFconfSettings[setting];
}
}
// Initialize themes/styles after loading
setTheme();
setMainMenuStyle();
}
function setTheme() {
if (_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_HIGHLIGHT_COLOR == null ||
_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_FONT_COLOR == null ||
_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_BACKGROUND_COLOR == null ||
_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_PROMPT_COLOR == null) {
console.error("Cannot find Theme Settings");
return;
}
if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_HIGHLIGHT_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_FONT_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_BACKGROUND_COLOR) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_PROMPT_COLOR)) {
document.body.style.setProperty('--my-highlight-color', _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_HIGHLIGHT_COLOR);
document.body.style.setProperty('--my-font-color', _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_FONT_COLOR);
document.body.style.setProperty('--my-background-color', _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"].THEME_BACKGROUND_COLOR);
document.body.style.setProperty('--my-prompt-color', _FconfSettings__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"]["MAIN_MENU_STYLE"] === "default") {
removeAllAccordionHeaderClasses();
mainMenu.classList.remove("classic");
mainMenu.classList.remove("compact");
addClassToAllAccordionHeaders("mainmenu-accordion-header");
} else if (_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["FconfSettings"]["MAIN_MENU_STYLE"] === "classic") {
removeAllAccordionHeaderClasses();
mainMenu.classList.remove("compact");
mainMenu.classList.add("classic");
addClassToAllAccordionHeaders("mainmenu-accordion-header-classic");
} else if (_FconfSettings__WEBPACK_IMPORTED_MODULE_0__["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();
}
/***/ }),
/* 194 */
/*!*************************************!*\
!*** ./src/Script/RunningScript.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RunningScript = void 0;
const FconfSettings_1 = __webpack_require__(/*! ../Fconf/FconfSettings */ 39);
const Settings_1 = __webpack_require__(/*! ../Settings/Settings */ 24);
const postToTerminal_1 = __webpack_require__(/*! ../ui/postToTerminal */ 8);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const getTimestamp_1 = __webpack_require__(/*! ../../utils/helpers/getTimestamp */ 409);
class RunningScript {
constructor(script = null, args = []) {
// Script arguments
this.args = [];
// Map of [key: server ip] -> Hacking data. Used for offline progress calculations.
// Hacking data format: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = {};
// Script filename
this.filename = "";
// This script's logs. An array of log entries
this.logs = [];
// Flag indicating whether the logs have been updated since
// the last time the UI was updated
this.logUpd = false;
// Total amount of hacking experience earned from this script when offline
this.offlineExpGained = 0;
// Total amount of money made by this script when offline
this.offlineMoneyMade = 0;
// Number of seconds that the script has been running offline
this.offlineRunningTime = 0.01;
// Total amount of hacking experience earned from this script when online
this.onlineExpGained = 0;
// Total amount of money made by this script when online
this.onlineMoneyMade = 0;
// Number of seconds that this script has been running online
this.onlineRunningTime = 0.01;
// Process ID. Must be an integer and equals the PID of corresponding WorkerScript
this.pid = -1;
// How much RAM this script uses for ONE thread
this.ramUsage = 0;
// IP of the server on which this script is running
this.server = "";
// Number of threads that this script is running with
this.threads = 1;
if (script == null) {
return;
}
this.filename = script.filename;
this.args = args;
this.server = script.server;
this.ramUsage = script.ramUsage;
}
log(txt) {
if (this.logs.length > Settings_1.Settings.MaxLogCapacity) {
this.logs.shift();
}
let logEntry = txt;
if (FconfSettings_1.FconfSettings.ENABLE_TIMESTAMPS) {
logEntry = "[" + getTimestamp_1.getTimestamp() + "] " + logEntry;
}
this.logs.push(logEntry);
this.logUpd = true;
}
displayLog() {
for (let i = 0; i < this.logs.length; ++i) {
postToTerminal_1.post(this.logs[i]);
}
}
clearLog() {
this.logs.length = 0;
}
// Update the moneyStolen and numTimesHack maps when hacking
recordHack(serverIp, moneyGained, n = 1) {
if (this.dataMap[serverIp] == null || this.dataMap[serverIp].constructor !== Array) {
this.dataMap[serverIp] = [0, 0, 0, 0];
}
this.dataMap[serverIp][0] += moneyGained;
this.dataMap[serverIp][1] += n;
}
// Update the grow map when calling grow()
recordGrow(serverIp, n = 1) {
if (this.dataMap[serverIp] == null || this.dataMap[serverIp].constructor !== Array) {
this.dataMap[serverIp] = [0, 0, 0, 0];
}
this.dataMap[serverIp][2] += n;
}
// Update the weaken map when calling weaken() {
recordWeaken(serverIp, n = 1) {
if (this.dataMap[serverIp] == null || this.dataMap[serverIp].constructor !== Array) {
this.dataMap[serverIp] = [0, 0, 0, 0];
}
this.dataMap[serverIp][3] += n;
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("RunningScript", this);
}
// Initializes a RunningScript Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(RunningScript, value.data);
}
}
exports.RunningScript = RunningScript;
JSONReviver_1.Reviver.constructors.RunningScript = RunningScript;
/***/ }),
/* 195 */
/*!****************************************!*\
!*** ./utils/helpers/compareArrays.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareArrays = void 0;
/**
* 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 (Array.isArray(a1[i])) {
// If the other element is not an array, then these cannot be equal
if (!Array.isArray(a2[i])) {
return false;
}
const elem1 = a1[i];
const elem2 = a2[i];
if (!compareArrays(elem1, elem2)) {
return false;
}
}
else if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
exports.compareArrays = compareArrays;
/***/ }),
/* 196 */
/*!*****************************************************!*\
!*** ./src/Augmentation/PlayerOwnedAugmentation.ts ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayerOwnedAugmentation = void 0;
class PlayerOwnedAugmentation {
constructor(name = "") {
this.level = 1;
this.name = "";
this.name = name;
}
}
exports.PlayerOwnedAugmentation = PlayerOwnedAugmentation;
/***/ }),
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */,
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */
/*!***********************************!*\
!*** ./src/Infiltration/utils.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getArrow = exports.random = void 0;
function random(min, max) {
return Math.random() * (max - min) + min;
}
exports.random = random;
function getArrow(event) {
switch (event.keyCode) {
case 38:
case 87:
return "↑";
case 65:
case 37:
return "←";
case 40:
case 83:
return "↓";
case 39:
case 68:
return "→";
}
return '';
}
exports.getArrow = getArrow;
/***/ }),
/* 217 */,
/* 218 */,
/* 219 */,
/* 220 */,
/* 221 */,
/* 222 */
/*!**************************************!*\
!*** ./src/Settings/SettingEnums.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Enums that defined allowed values for setting configuration
Object.defineProperty(exports, "__esModule", { value: true });
exports.OwnedAugmentationsOrderSetting = exports.PurchaseAugmentationsOrderSetting = exports.EditorSetting = exports.CodeMirrorThemeSetting = exports.CodeMirrorKeybindingSetting = exports.AceKeybindingSetting = void 0;
/**
* Allowed values for 'Keybinding/Keymap' setting in Ace editor
*/
var AceKeybindingSetting;
(function (AceKeybindingSetting) {
AceKeybindingSetting["Ace"] = "ace";
AceKeybindingSetting["Emacs"] = "emacs";
AceKeybindingSetting["Vim"] = "vim";
})(AceKeybindingSetting = exports.AceKeybindingSetting || (exports.AceKeybindingSetting = {}));
/**
* Allowed values for 'Keybinding/Keymap' setting in Code Mirror editor
*/
var CodeMirrorKeybindingSetting;
(function (CodeMirrorKeybindingSetting) {
CodeMirrorKeybindingSetting["Default"] = "default";
CodeMirrorKeybindingSetting["Emacs"] = "emacs";
CodeMirrorKeybindingSetting["Sublime"] = "sublime";
CodeMirrorKeybindingSetting["Vim"] = "vim";
})(CodeMirrorKeybindingSetting = exports.CodeMirrorKeybindingSetting || (exports.CodeMirrorKeybindingSetting = {}));
/**
* Allowed values for 'Theme' setting in Code Mirror editor
*/
var CodeMirrorThemeSetting;
(function (CodeMirrorThemeSetting) {
CodeMirrorThemeSetting["Monokai"] = "monokai";
CodeMirrorThemeSetting["Day_3024"] = "3024-day";
CodeMirrorThemeSetting["Night_3024"] = "3024-night";
CodeMirrorThemeSetting["abcdef"] = "abcdef";
CodeMirrorThemeSetting["Ambiance_mobile"] = "ambiance-mobile";
CodeMirrorThemeSetting["Ambiance"] = "ambiance";
CodeMirrorThemeSetting["Base16_dark"] = "base16-dark";
CodeMirrorThemeSetting["Base16_light"] = "base16-light";
CodeMirrorThemeSetting["Bespin"] = "bespin";
CodeMirrorThemeSetting["Blackboard"] = "blackboard";
CodeMirrorThemeSetting["Cobalt"] = "cobalt";
CodeMirrorThemeSetting["Colorforth"] = "colorforth";
CodeMirrorThemeSetting["Darcula"] = "darcula";
CodeMirrorThemeSetting["Dracula"] = "dracula";
CodeMirrorThemeSetting["Duotone_dark"] = "duotone-dark";
CodeMirrorThemeSetting["Duotone_light"] = "duotone-light";
CodeMirrorThemeSetting["Eclipse"] = "eclipse";
CodeMirrorThemeSetting["Elegant"] = "elegant";
CodeMirrorThemeSetting["Erlang_dark"] = "erlang-dark";
CodeMirrorThemeSetting["Gruvbox_dark"] = "gruvbox-dark";
CodeMirrorThemeSetting["Hopscotch"] = "hopscotch";
CodeMirrorThemeSetting["Icecoder"] = "icecoder";
CodeMirrorThemeSetting["Idea"] = "idea";
CodeMirrorThemeSetting["Isotope"] = "isotope";
CodeMirrorThemeSetting["Lesser_dark"] = "lesser-dark";
CodeMirrorThemeSetting["Liquibyte"] = "liquibyte";
CodeMirrorThemeSetting["Lucario"] = "lucario";
CodeMirrorThemeSetting["Material"] = "material";
CodeMirrorThemeSetting["Mbo"] = "mbo";
CodeMirrorThemeSetting["Mdn_like"] = "mdn-like";
CodeMirrorThemeSetting["Midnight"] = "midnight";
CodeMirrorThemeSetting["Neat"] = "neat";
CodeMirrorThemeSetting["Neo"] = "neo";
CodeMirrorThemeSetting["Night"] = "night";
CodeMirrorThemeSetting["Oceanic_next"] = "oceanic-next";
CodeMirrorThemeSetting["Panda_syntax"] = "panda-syntax";
CodeMirrorThemeSetting["Paraiso_dark"] = "paraiso-dark";
CodeMirrorThemeSetting["Paraiso_light"] = "paraiso-light";
CodeMirrorThemeSetting["Pastel_on_dark"] = "pastel-on-dark";
CodeMirrorThemeSetting["Railscasts"] = "railscasts";
CodeMirrorThemeSetting["Rubyblue"] = "rubyblue";
CodeMirrorThemeSetting["Seti"] = "seti";
CodeMirrorThemeSetting["Shadowfox"] = "shadowfox";
CodeMirrorThemeSetting["Solarized"] = "solarized";
CodeMirrorThemeSetting["SolarizedDark"] = "solarized dark";
CodeMirrorThemeSetting["ssms"] = "ssms";
CodeMirrorThemeSetting["The_matrix"] = "the-matrix";
CodeMirrorThemeSetting["Tomorrow_night_bright"] = "tomorrow-night-bright";
CodeMirrorThemeSetting["Tomorrow_night_eighties"] = "tomorrow-night-eighties";
CodeMirrorThemeSetting["Ttcn"] = "ttcn";
CodeMirrorThemeSetting["Twilight"] = "twilight";
CodeMirrorThemeSetting["Vibrant_ink"] = "vibrant-ink";
CodeMirrorThemeSetting["xq_dark"] = "xq-dark";
CodeMirrorThemeSetting["xq_light"] = "xq-light";
CodeMirrorThemeSetting["Yeti"] = "yeti";
CodeMirrorThemeSetting["Zenburn"] = "zenburn";
})(CodeMirrorThemeSetting = exports.CodeMirrorThemeSetting || (exports.CodeMirrorThemeSetting = {}));
/**
* Allowed values for the "Editor" setting
*/
var EditorSetting;
(function (EditorSetting) {
EditorSetting["Ace"] = "Ace";
EditorSetting["CodeMirror"] = "CodeMirror";
})(EditorSetting = exports.EditorSetting || (exports.EditorSetting = {}));
/**
* Allowed values for the 'OwnedAugmentationsOrder' setting
*/
var PurchaseAugmentationsOrderSetting;
(function (PurchaseAugmentationsOrderSetting) {
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Cost"] = 0] = "Cost";
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Default"] = 1] = "Default";
PurchaseAugmentationsOrderSetting[PurchaseAugmentationsOrderSetting["Reputation"] = 2] = "Reputation";
})(PurchaseAugmentationsOrderSetting = exports.PurchaseAugmentationsOrderSetting || (exports.PurchaseAugmentationsOrderSetting = {}));
/**
* Allowed values for the 'OwnedAugmentationsOrder' setting
*/
var OwnedAugmentationsOrderSetting;
(function (OwnedAugmentationsOrderSetting) {
OwnedAugmentationsOrderSetting[OwnedAugmentationsOrderSetting["Alphabetically"] = 0] = "Alphabetically";
OwnedAugmentationsOrderSetting[OwnedAugmentationsOrderSetting["AcquirementTime"] = 1] = "AcquirementTime";
})(OwnedAugmentationsOrderSetting = exports.OwnedAugmentationsOrderSetting || (exports.OwnedAugmentationsOrderSetting = {}));
/***/ }),
/* 223 */
/*!****************************************!*\
!*** ./src/Corporation/OfficeSpace.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OfficeSpace = void 0;
const EmployeePositions_1 = __webpack_require__(/*! ./EmployeePositions */ 282);
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 107);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 23);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const YesNoBox_1 = __webpack_require__(/*! ../../utils/YesNoBox */ 61);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../utils/uiHelpers/createPopup */ 129);
const removeElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/removeElementById */ 90);
const createElement_1 = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const Employee_1 = __webpack_require__(/*! ./Employee */ 1123);
class OfficeSpace {
constructor(params = {}) {
this.tier = "Basic";
this.minEne = 0;
this.maxEne = 100;
this.minHap = 0;
this.maxHap = 100;
this.maxMor = 100;
this.employees = [];
this.employeeProd = {
[EmployeePositions_1.EmployeePositions.Operations]: 0,
[EmployeePositions_1.EmployeePositions.Engineer]: 0,
[EmployeePositions_1.EmployeePositions.Business]: 0,
[EmployeePositions_1.EmployeePositions.Management]: 0,
[EmployeePositions_1.EmployeePositions.RandD]: 0,
total: 0,
};
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;
}
atCapacity() {
return (this.employees.length) >= this.size;
}
process(marketCycles = 1, parentRefs) {
const industry = parentRefs.industry;
// HRBuddy AutoRecruitment and training
if (industry.hasResearch("HRBuddy-Recruitment") && !this.atCapacity()) {
const emp = this.hireRandomEmployee();
if (industry.hasResearch("HRBuddy-Training") && emp !== undefined) {
emp.pos = EmployeePositions_1.EmployeePositions.Training;
}
}
// Process Office properties
this.maxEne = 100;
this.maxHap = 100;
this.maxMor = 100;
if (industry.hasResearch("Go-Juice")) {
this.maxEne += 10;
}
if (industry.hasResearch("JoyWire")) {
this.maxHap += 10;
}
if (industry.hasResearch("Sti.mu")) {
this.maxMor += 10;
}
// Calculate changes in Morale/Happiness/Energy for Employees
let perfMult = 1; //Multiplier for employee morale/happiness/energy based on company performance
if (parentRefs.corporation.funds < 0 && industry.lastCycleRevenue < 0) {
perfMult = Math.pow(0.99, marketCycles);
}
else if (parentRefs.corporation.funds > 0 && industry.lastCycleRevenue > 0) {
perfMult = Math.pow(1.01, marketCycles);
}
const hasAutobrew = industry.hasResearch("AutoBrew");
const hasAutoparty = industry.hasResearch("AutoPartyManager");
let salaryPaid = 0;
for (let i = 0; i < this.employees.length; ++i) {
const emp = this.employees[i];
if (hasAutoparty) {
emp.mor = this.maxMor;
emp.hap = this.maxHap;
}
else {
emp.mor *= perfMult;
emp.hap *= perfMult;
emp.mor = Math.min(emp.mor, this.maxMor);
emp.hap = Math.min(emp.hap, this.maxHap);
}
if (hasAutobrew) {
emp.ene = this.maxEne;
}
else {
emp.ene *= perfMult;
emp.ene = Math.min(emp.ene, this.maxEne);
}
const salary = emp.process(marketCycles, this);
salaryPaid += salary;
}
this.calculateEmployeeProductivity(parentRefs);
return salaryPaid;
}
calculateEmployeeProductivity(parentRefs) {
const company = parentRefs.corporation, industry = parentRefs.industry;
//Reset
for (const name in this.employeeProd) {
this.employeeProd[name] = 0;
}
let total = 0;
for (let i = 0; i < this.employees.length; ++i) {
const employee = this.employees[i];
const prod = employee.calculateProductivity(company, industry);
this.employeeProd[employee.pos] += prod;
total += prod;
}
this.employeeProd.total = total;
}
//Takes care of UI as well
findEmployees(player, parentRefs) {
if (this.atCapacity()) {
return;
}
if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null) {
return;
}
//Generate three random employees (meh, decent, amazing)
const mult1 = getRandomInt_1.getRandomInt(25, 50) / 100, mult2 = getRandomInt_1.getRandomInt(51, 75) / 100, mult3 = getRandomInt_1.getRandomInt(76, 100) / 100;
const int = getRandomInt_1.getRandomInt(50, 100), cha = getRandomInt_1.getRandomInt(50, 100), exp = getRandomInt_1.getRandomInt(50, 100), cre = getRandomInt_1.getRandomInt(50, 100), eff = getRandomInt_1.getRandomInt(50, 100), sal = Constants_1.CorporationConstants.EmployeeSalaryMultiplier * (int + cha + exp + cre + eff);
const emp1 = new Employee_1.Employee({
intelligence: int * mult1,
charisma: cha * mult1,
experience: exp * mult1,
creativity: cre * mult1,
efficiency: eff * mult1,
salary: sal * mult1,
});
const emp2 = new Employee_1.Employee({
intelligence: int * mult2,
charisma: cha * mult2,
experience: exp * mult2,
creativity: cre * mult2,
efficiency: eff * mult2,
salary: sal * mult2,
});
const emp3 = new Employee_1.Employee({
intelligence: int * mult3,
charisma: cha * mult3,
experience: exp * mult3,
creativity: cre * mult3,
efficiency: eff * mult3,
salary: sal * mult3,
});
const text = createElement_1.createElement("h1", {
innerHTML: "Select one of the following candidates for hire:",
});
function createEmpDiv(employee, office) {
const div = createElement_1.createElement("div", {
class: "cmpy-mgmt-find-employee-option",
innerHTML: "Intelligence: " + StringHelperFunctions_1.formatNumber(employee.int, 1) + " " +
"Charisma: " + StringHelperFunctions_1.formatNumber(employee.cha, 1) + " " +
"Experience: " + StringHelperFunctions_1.formatNumber(employee.exp, 1) + " " +
"Creativity: " + StringHelperFunctions_1.formatNumber(employee.cre, 1) + " " +
"Efficiency: " + StringHelperFunctions_1.formatNumber(employee.eff, 1) + " " +
"Salary: " + numeralFormat_1.numeralWrapper.format(employee.sal, '$0.000a') + " \ s ",
clickListener: () => {
office.hireEmployee(player, employee, parentRefs);
removeElementById_1.removeElementById("cmpy-mgmt-hire-employee-popup");
return false;
},
});
return div;
}
const cancelBtn = createElement_1.createElement("a", {
class: "a-link-button",
innerText: "Cancel",
float: "right",
clickListener: () => {
removeElementById_1.removeElementById("cmpy-mgmt-hire-employee-popup");
return false;
},
});
const elems = [text,
createEmpDiv(emp1, this),
createEmpDiv(emp2, this),
createEmpDiv(emp3, this),
cancelBtn];
createPopup_1.createPopup("cmpy-mgmt-hire-employee-popup", elems);
}
hireEmployee(player, employee, parentRefs) {
const corporation = parentRefs.corporation;
const yesBtn = YesNoBox_1.yesNoTxtInpBoxGetYesButton(), noBtn = YesNoBox_1.yesNoTxtInpBoxGetNoButton();
yesBtn.innerHTML = "Hire";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", () => {
const name = YesNoBox_1.yesNoTxtInpBoxGetInput();
for (let i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
DialogBox_1.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);
corporation.rerender(player);
return YesNoBox_1.yesNoTxtInpBoxClose();
});
noBtn.addEventListener("click", () => {
return YesNoBox_1.yesNoTxtInpBoxClose();
});
YesNoBox_1.yesNoTxtInpBoxCreate("Give your employee a nickname!");
}
hireRandomEmployee() {
if (this.atCapacity())
return;
if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null)
return;
//Generate three random employees (meh, decent, amazing)
const mult = getRandomInt_1.getRandomInt(76, 100) / 100;
const int = getRandomInt_1.getRandomInt(50, 100), cha = getRandomInt_1.getRandomInt(50, 100), exp = getRandomInt_1.getRandomInt(50, 100), cre = getRandomInt_1.getRandomInt(50, 100), eff = getRandomInt_1.getRandomInt(50, 100), sal = Constants_1.CorporationConstants.EmployeeSalaryMultiplier * (int + cha + exp + cre + eff);
const emp = new Employee_1.Employee({
intelligence: int * mult,
charisma: cha * mult,
experience: exp * mult,
creativity: cre * mult,
efficiency: eff * mult,
salary: sal * mult,
});
const name = StringHelperFunctions_1.generateRandomString(7);
for (let i = 0; i < this.employees.length; ++i) {
if (this.employees[i].name === name) {
return this.hireRandomEmployee();
}
}
emp.name = name;
this.employees.push(emp);
return emp;
}
//Finds the first unassigned employee and assigns its to the specified job
assignEmployeeToJob(job) {
for (let i = 0; i < this.employees.length; ++i) {
if (this.employees[i].pos === EmployeePositions_1.EmployeePositions.Unassigned) {
this.employees[i].pos = job;
return true;
}
}
return false;
}
//Finds the first employee with the given job and unassigns it
unassignEmployeeFromJob(job) {
for (let i = 0; i < this.employees.length; ++i) {
if (this.employees[i].pos === job) {
this.employees[i].pos = EmployeePositions_1.EmployeePositions.Unassigned;
return true;
}
}
return false;
}
toJSON() {
return JSONReviver_1.Generic_toJSON("OfficeSpace", this);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(OfficeSpace, value.data);
}
}
exports.OfficeSpace = OfficeSpace;
JSONReviver_1.Reviver.constructors.OfficeSpace = OfficeSpace;
/***/ }),
/* 224 */
/*!******************************************!*\
!*** ./utils/uiHelpers/removeElement.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeElement = void 0;
/**
* 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;
/***/ }),
/* 225 */,
/* 226 */,
/* 227 */
/*!***************************************!*\
!*** ./src/SourceFile/SourceFiles.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceFiles = void 0;
const SourceFile_1 = __webpack_require__(/*! ./SourceFile */ 967);
exports.SourceFiles = {};
exports.SourceFiles["SourceFile1"] = new SourceFile_1.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:
" +
"Level 1: 16% " +
"Level 2: 24% " +
"Level 3: 28%");
exports.SourceFiles["SourceFile2"] = new SourceFile_1.SourceFile(2, "This Source-File allows you to form gangs in other BitNodes " +
"once your karma decreases to a certain value. It also increases the player's " +
"crime success rate, crime money, and charisma multipliers by:
" +
"Level 1: 24% " +
"Level 2: 36% " +
"Level 3: 42%");
exports.SourceFiles["SourceFile3"] = new SourceFile_1.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: " +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.SourceFiles["SourceFile4"] = new SourceFile_1.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.");
exports.SourceFiles["SourceFile5"] = new SourceFile_1.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() " +
"and getServer() Netscript functions, as well as the formulas API, and will raise all of your " +
"hacking-related multipliers by:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.SourceFiles["SourceFile6"] = new SourceFile_1.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:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.SourceFiles["SourceFile7"] = new SourceFile_1.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:
" +
"Level 1: 8% " +
"Level 2: 12% " +
"Level 3: 14%");
exports.SourceFiles["SourceFile8"] = new SourceFile_1.SourceFile(8, "This Source-File grants the following benefits:
" +
"Level 1: Permanent access to WSE and TIX API " +
"Level 2: Ability to short stocks in other BitNodes " +
"Level 3: Ability to use limit/stop orders in other BitNodes
" +
"This Source-File also increases your hacking growth multipliers by: " +
" Level 1: 12% Level 2: 18% Level 3: 21%");
exports.SourceFiles["SourceFile9"] = new SourceFile_1.SourceFile(9, "This Source-File grants the following benefits:
" +
"Level 1: Permanently unlocks the Hacknet Server in other BitNodes " +
"Level 2: You start with 128GB of RAM on your home computer when entering a new BitNode " +
"Level 3: Grants a highly-upgraded Hacknet Server when entering a new BitNode
" +
"(Note that the Level 3 effect of this Source-File only applies when entering a new BitNode, NOT " +
"when installing Augmentations)");
exports.SourceFiles["SourceFile10"] = new SourceFile_1.SourceFile(10, "This Source-File unlocks Sleeve technology in other BitNodes. Each level of this " +
"Source-File also grants you a Duplicate Sleeve");
exports.SourceFiles["SourceFile11"] = new SourceFile_1.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:
" +
"It also reduces the price increase for every aug bought by:
" +
"Level 1: 4% " +
"Level 2: 6% " +
"Level 3: 7%");
exports.SourceFiles["SourceFile12"] = new SourceFile_1.SourceFile(12, "This Source-File lets the player start with Neuroflux Governor equal to the level of this Source-File.");
/***/ }),
/* 228 */
/*!******************************!*\
!*** ./src/Script/Script.ts ***!
\******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Script = void 0;
/**
* Class representing a script file.
*
* This does NOT represent a script that is actively running and
* being evaluated. See RunningScript for that
*/
const RamCalculations_1 = __webpack_require__(/*! ./RamCalculations */ 489);
const navigationTracking_1 = __webpack_require__(/*! ../ui/navigationTracking */ 18);
const SetTimeoutRef_1 = __webpack_require__(/*! ../utils/SetTimeoutRef */ 76);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const roundToTwo_1 = __webpack_require__(/*! ../../utils/helpers/roundToTwo */ 290);
let globalModuleSequenceNumber = 0;
class Script {
constructor(fn = "", code = "", server = "", otherScripts = []) {
// Code for this script
this.code = "";
// Filename for the script file
this.filename = "";
// url of the script if any, only for NS2.
this.url = "";
// The dynamic module generated for this script when it is run.
// This is only applicable for NetscriptJS
this.module = "";
// Only used with NS2 scripts; the list of dependency script filenames. This is constructed
// whenever the script is first evaluated, and therefore may be out of date if the script
// has been updated since it was last run.
this.dependencies = [];
// Amount of RAM this Script requres to run
this.ramUsage = 0;
// IP of server that this script is on.
this.server = "";
this.filename = fn;
this.code = code;
this.ramUsage = 0;
this.server = server; // IP of server this script is on
this.module = "";
this.moduleSequenceNumber = ++globalModuleSequenceNumber;
if (this.code !== "") {
this.updateRamUsage(otherScripts);
}
}
/**
* Download the script as a file
*/
download() {
const filename = this.filename + ".js";
const file = new Blob([this.code], { type: 'text/plain' });
if (window.navigator.msSaveOrOpenBlob) { // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
}
else { // Others
const a = document.createElement("a"), url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
SetTimeoutRef_1.setTimeoutRef(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
/**
* Marks this script as having been updated. It will be recompiled next time something tries
* to exec it.
*/
markUpdated() {
this.module = "";
this.moduleSequenceNumber = ++globalModuleSequenceNumber;
}
/**
* Save a script from the script editor
* @param {string} code - The new contents of the script
* @param {Script[]} otherScripts - Other scripts on the server. Used to process imports
*/
saveScript(code, serverIp, otherScripts) {
if (navigationTracking_1.routing.isOn(navigationTracking_1.Page.ScriptEditor)) {
// Update code and filename
this.code = code.replace(/^\s+|\s+$/g, '');
const filenameElem = document.getElementById("script-editor-filename");
if (filenameElem == null) {
console.error(`Failed to get Script filename DOM element`);
return;
}
this.filename = filenameElem.value;
this.server = serverIp;
this.updateRamUsage(otherScripts);
this.markUpdated();
}
}
/**
* Calculates and updates the script's RAM usage based on its code
* @param {Script[]} otherScripts - Other scripts on the server. Used to process imports
*/
updateRamUsage(otherScripts) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield RamCalculations_1.calculateRamUsage(this.code, otherScripts);
if (res > 0) {
this.ramUsage = roundToTwo_1.roundToTwo(res);
}
});
}
// Serialize the current object to a JSON save state
toJSON() {
return JSONReviver_1.Generic_toJSON("Script", this);
}
// Initializes a Script Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Script, value.data);
}
}
exports.Script = Script;
JSONReviver_1.Reviver.constructors.Script = Script;
/***/ }),
/* 229 */
/*!************************************!*\
!*** ./utils/helpers/addOffset.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addOffset = void 0;
/**
* 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;
/***/ }),
/* 230 */,
/* 231 */,
/* 232 */,
/* 233 */,
/* 234 */,
/* 235 */,
/* 236 */,
/* 237 */,
/* 238 */,
/* 239 */,
/* 240 */,
/* 241 */
/*!*************************************!*\
!*** ./src/Hacknet/HashUpgrades.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashUpgrades = void 0;
/**
* Map of all Hash Upgrades
* Key = Hash name, Value = HashUpgrade object
*/
const HashUpgrade_1 = __webpack_require__(/*! ./HashUpgrade */ 1063);
const HashUpgradesMetadata_1 = __webpack_require__(/*! ./data/HashUpgradesMetadata */ 1062);
exports.HashUpgrades = {};
function createHashUpgrade(p) {
exports.HashUpgrades[p.name] = new HashUpgrade_1.HashUpgrade(p);
}
for (const metadata of HashUpgradesMetadata_1.HashUpgradesMetadata) {
createHashUpgrade(metadata);
}
/***/ }),
/* 242 */
/*!*********************************************************!*\
!*** ./src/PersonObjects/Sleeve/SleeveTaskTypesEnum.ts ***!
\*********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SleeveTaskType = void 0;
/**
* Enum for different types of tasks that a Sleeve can perform
*/
var SleeveTaskType;
(function (SleeveTaskType) {
// Same Order as selectable order in UI
SleeveTaskType[SleeveTaskType["Idle"] = 0] = "Idle";
SleeveTaskType[SleeveTaskType["Company"] = 1] = "Company";
SleeveTaskType[SleeveTaskType["Faction"] = 2] = "Faction";
SleeveTaskType[SleeveTaskType["Crime"] = 3] = "Crime";
SleeveTaskType[SleeveTaskType["Class"] = 4] = "Class";
SleeveTaskType[SleeveTaskType["Gym"] = 5] = "Gym";
SleeveTaskType[SleeveTaskType["Recovery"] = 6] = "Recovery";
SleeveTaskType[SleeveTaskType["Synchro"] = 7] = "Synchro";
})(SleeveTaskType = exports.SleeveTaskType || (exports.SleeveTaskType = {}));
/***/ }),
/* 243 */,
/* 244 */,
/* 245 */
/*!*********************************************!*\
!*** ./src/StockMarket/StockMarketCosts.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStockMarket4STixApiCost = exports.getStockMarket4SDataCost = exports.getStockMarketTixApiCost = exports.getStockMarketAccountCost = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
function getStockMarketAccountCost() {
return Constants_1.CONSTANTS.WSEAccountCost;
}
exports.getStockMarketAccountCost = getStockMarketAccountCost;
function getStockMarketTixApiCost() {
return Constants_1.CONSTANTS.TIXAPICost;
}
exports.getStockMarketTixApiCost = getStockMarketTixApiCost;
function getStockMarket4SDataCost() {
return Constants_1.CONSTANTS.MarketData4SCost * BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataCost;
}
exports.getStockMarket4SDataCost = getStockMarket4SDataCost;
function getStockMarket4STixApiCost() {
return Constants_1.CONSTANTS.MarketDataTixApi4SCost * BitNodeMultipliers_1.BitNodeMultipliers.FourSigmaMarketDataApiCost;
}
exports.getStockMarket4STixApiCost = getStockMarket4STixApiCost;
/***/ }),
/* 246 */
/*!***********************************!*\
!*** ./src/Crime/CrimeHelpers.ts ***!
\***********************************/
/*! no static exports found */
/*! exports used: determineCrimeSuccess, findCrime */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findCrime = exports.determineCrimeSuccess = void 0;
const Crimes_1 = __webpack_require__(/*! ./Crimes */ 169);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
function determineCrimeSuccess(p, type) {
let chance = 0;
let found = false;
for (const i in Crimes_1.Crimes) {
const crime = Crimes_1.Crimes[i];
if (crime.type == type) {
chance = crime.successRate(p);
found = true;
break;
}
}
if (!found) {
DialogBox_1.dialogBoxCreate(`ERR: Unrecognized crime type: ${type} This is probably a bug please contact the developer`, false);
return false;
}
if (Math.random() <= chance) {
//Success
return true;
}
else {
//Failure
return false;
}
}
exports.determineCrimeSuccess = determineCrimeSuccess;
function findCrime(roughName) {
if (roughName.includes("shoplift")) {
return Crimes_1.Crimes.Shoplift;
}
else if (roughName.includes("rob") && roughName.includes("store")) {
return Crimes_1.Crimes.RobStore;
}
else if (roughName.includes("mug")) {
return Crimes_1.Crimes.Mug;
}
else if (roughName.includes("larceny")) {
return Crimes_1.Crimes.Larceny;
}
else if (roughName.includes("drugs")) {
return Crimes_1.Crimes.DealDrugs;
}
else if (roughName.includes("bond") && roughName.includes("forge")) {
return Crimes_1.Crimes.BondForgery;
}
else if (roughName.includes("traffick") && roughName.includes("arms")) {
return Crimes_1.Crimes.TraffickArms;
}
else if (roughName.includes("homicide")) {
return Crimes_1.Crimes.Homicide;
}
else if (roughName.includes("grand") && roughName.includes("auto")) {
return Crimes_1.Crimes.GrandTheftAuto;
}
else if (roughName.includes("kidnap")) {
return Crimes_1.Crimes.Kidnap;
}
else if (roughName.includes("assassinate")) {
return Crimes_1.Crimes.Assassination;
}
else if (roughName.includes("heist")) {
return Crimes_1.Crimes.Heist;
}
return null;
}
exports.findCrime = findCrime;
/***/ }),
/* 247 */
/*!***************************************!*\
!*** ./src/Netscript/WorkerScript.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkerScript = void 0;
/**
* The worker agent for running a script instance. Each running script instance
* has its own underlying WorkerScript object.
*
* Note that these objects are not saved and re-loaded when the game is refreshed.
* Instead, whenever the game is opened, WorkerScripts are re-created from
* RunningScript objects
*/
const Environment_1 = __webpack_require__(/*! ./Environment */ 1058);
const RamCostGenerator_1 = __webpack_require__(/*! ./RamCostGenerator */ 10);
const AllServers_1 = __webpack_require__(/*! ../Server/AllServers */ 20);
class WorkerScript {
constructor(runningScriptObj, pid, nsFuncsGenerator) {
/**
* Copy of the script's code
*/
this.code = "";
/**
* Holds the timeoutID (numeric value) for whenever this script is blocked by a
* timed Netscript function. i.e. Holds the return value of setTimeout()
*/
this.delay = null;
/**
* Stores names of all functions that have logging disabled
*/
this.disableLogs = {};
/**
* Used for dynamic RAM calculation. Stores names of all functions that have
* already been checked by this script.
* TODO: Could probably just combine this with loadedFns?
*/
this.dynamicLoadedFns = {};
/**
* Tracks dynamic RAM usage
*/
this.dynamicRamUsage = RamCostGenerator_1.RamCostConstants.ScriptBaseRamCost;
/**
* Status message in case of script error. Currently unused I think
*/
this.errorMessage = "";
/**
* Used for static RAM calculation. Stores names of all functions that have
* already been checked by this script
*/
this.loadedFns = {};
/**
* Script's output/return value. Currently not used or implemented
*/
this.output = "";
/**
* Script's Static RAM usage. Equivalent to underlying script's RAM usage
*/
this.ramUsage = 0;
/**
* Whether or not this workerScript is currently running
*/
this.running = false;
this.name = runningScriptObj.filename;
this.serverIp = runningScriptObj.server;
const sanitizedPid = Math.round(pid);
if (typeof sanitizedPid !== "number" || isNaN(sanitizedPid)) {
throw new Error(`Invalid PID when constructing WorkerScript: ${pid}`);
}
this.pid = sanitizedPid;
runningScriptObj.pid = sanitizedPid;
// Get the underlying script's code
const server = AllServers_1.AllServers[this.serverIp];
if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${this.serverIp}`);
}
let found = false;
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === this.name) {
found = true;
this.code = server.scripts[i].code;
}
}
if (!found) {
throw new Error(`WorkerScript constructed with invalid script filename: ${this.name}`);
}
this.env = new Environment_1.Environment(null);
if (typeof nsFuncsGenerator === "function") {
this.env.vars = nsFuncsGenerator(this);
}
this.env.set("args", runningScriptObj.args.slice());
this.scriptRef = runningScriptObj;
this.args = runningScriptObj.args.slice();
}
/**
* Returns the Server on which this script is running
*/
getServer() {
const server = AllServers_1.AllServers[this.serverIp];
if (server == null)
throw new Error(`Script ${this.name} pid ${this.pid} is running on non-existent server?`);
return server;
}
/**
* Returns the Script object for the underlying script.
* Returns null if it cannot be found (which would be a bug)
*/
getScript() {
const server = this.getServer();
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === this.name) {
return server.scripts[i];
}
}
console.error("Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong");
return null;
}
/**
* Returns the script with the specified filename on the specified server,
* or null if it cannot be found
*/
getScriptOnServer(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;
}
shouldLog(fn) {
return (this.disableLogs.ALL == null && this.disableLogs[fn] == null);
}
log(func, txt) {
if (this.shouldLog(func)) {
if (func && txt) {
this.scriptRef.log(`${func}: ${txt}`);
}
else if (func) {
this.scriptRef.log(func);
}
else {
this.scriptRef.log(txt);
}
}
}
print(txt) {
this.scriptRef.log(txt);
}
}
exports.WorkerScript = WorkerScript;
/***/ }),
/* 248 */,
/* 249 */,
/* 250 */,
/* 251 */,
/* 252 */,
/* 253 */,
/* 254 */,
/* 255 */,
/* 256 */,
/* 257 */,
/* 258 */,
/* 259 */,
/* 260 */,
/* 261 */,
/* 262 */,
/* 263 */,
/* 264 */,
/* 265 */,
/* 266 */,
/* 267 */,
/* 268 */,
/* 269 */,
/* 270 */,
/* 271 */,
/* 272 */,
/* 273 */,
/* 274 */,
/* 275 */
/*!*************************************!*\
!*** ./src/ui/React/StatsTable.tsx ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatsTable = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
function StatsTable(rows, title) {
let titleElem = React.createElement(React.Fragment, null);
if (title) {
titleElem = React.createElement(React.Fragment, null,
React.createElement("h2", null,
React.createElement("u", null, title)),
React.createElement("br", null));
}
return (React.createElement(React.Fragment, null,
titleElem,
React.createElement("table", null,
React.createElement("tbody", null, rows.map((row) => {
return React.createElement("tr", { key: row[0] }, row.map((elem, i) => {
let style = {};
if (i !== 0)
style = { textAlign: 'right', paddingLeft: '.25em' };
return React.createElement("td", { key: i, style: style }, elem);
}));
})))));
}
exports.StatsTable = StatsTable;
/***/ }),
/* 276 */,
/* 277 */,
/* 278 */,
/* 279 */,
/* 280 */,
/* 281 */
/*!*********************************************!*\
!*** ./src/Bladeburner/data/ActionTypes.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionTypes = void 0;
// Action Identifier enum
exports.ActionTypes = {
"Idle": 1,
"Contract": 2,
"Operation": 3,
"BlackOp": 4,
"BlackOperation": 4,
"Training": 5,
"Recruitment": 6,
"FieldAnalysis": 7,
"Field Analysis": 7,
"Diplomacy": 8,
"Hyperbolic Regeneration Chamber": 9,
};
/***/ }),
/* 282 */
/*!**********************************************!*\
!*** ./src/Corporation/EmployeePositions.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmployeePositions = void 0;
exports.EmployeePositions = {
Operations: "Operations",
Engineer: "Engineer",
Business: "Business",
Management: "Management",
RandD: "Research & Development",
Training: "Training",
Unassigned: "Unassigned",
};
/***/ }),
/* 283 */
/*!***************************!*\
!*** ./src/Casino/RNG.ts ***!
\***************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WHRNG = exports.BadRNG = void 0;
/*
* very bad RNG, meant to be used as introduction to RNG manipulation. It has a
* period of 1024.
*/
class RNG0 {
constructor() {
this.m = 1024;
this.a = 341;
this.c = 1;
this.x = 0;
this.reset();
}
step() {
this.x = (this.a * this.x + this.c) % this.m;
}
random() {
this.step();
return this.x / this.m;
}
reset() {
this.x = (new Date()).getTime() % this.m;
}
}
exports.BadRNG = new RNG0();
/*
* Wichmann–Hill PRNG
* The period is 6e12.
*/
class WHRNG {
constructor(totalPlaytime) {
this.s1 = 0;
this.s2 = 0;
this.s3 = 0;
// This one is seeded by the players total play time.
const v = (totalPlaytime / 1000) % 30000;
this.s1 = v;
this.s2 = v;
this.s3 = v;
}
step() {
this.s1 = (171 * this.s1) % 30269;
this.s2 = (172 * this.s2) % 30307;
this.s3 = (170 * this.s3) % 30323;
}
random() {
this.step();
return (this.s1 / 30269.0 + this.s2 / 30307.0 + this.s3 / 30323.0) % 1.0;
}
}
exports.WHRNG = WHRNG;
/***/ }),
/* 284 */
/*!**********************************************!*\
!*** ./src/StockMarket/data/StockSymbols.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockSymbols = void 0;
const LocationNames_1 = __webpack_require__(/*! ../../Locations/data/LocationNames */ 40);
exports.StockSymbols = {};
// Stocks for companies at which you can work
exports.StockSymbols[LocationNames_1.LocationName.AevumECorp] = "ECP";
exports.StockSymbols[LocationNames_1.LocationName.Sector12MegaCorp] = "MGCP";
exports.StockSymbols[LocationNames_1.LocationName.Sector12BladeIndustries] = "BLD";
exports.StockSymbols[LocationNames_1.LocationName.AevumClarkeIncorporated] = "CLRK";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenOmniTekIncorporated] = "OMTK";
exports.StockSymbols[LocationNames_1.LocationName.Sector12FourSigma] = "FSIG";
exports.StockSymbols[LocationNames_1.LocationName.ChongqingKuaiGongInternational] = "KGI";
exports.StockSymbols[LocationNames_1.LocationName.AevumFulcrumTechnologies] = "FLCM";
exports.StockSymbols[LocationNames_1.LocationName.IshimaStormTechnologies] = "STM";
exports.StockSymbols[LocationNames_1.LocationName.NewTokyoDefComm] = "DCOMM";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenHeliosLabs] = "HLS";
exports.StockSymbols[LocationNames_1.LocationName.NewTokyoVitaLife] = "VITA";
exports.StockSymbols[LocationNames_1.LocationName.Sector12IcarusMicrosystems] = "ICRS";
exports.StockSymbols[LocationNames_1.LocationName.Sector12UniversalEnergy] = "UNV";
exports.StockSymbols[LocationNames_1.LocationName.AevumAeroCorp] = "AERO";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenOmniaCybersystems] = "OMN";
exports.StockSymbols[LocationNames_1.LocationName.ChongqingSolarisSpaceSystems] = "SLRS";
exports.StockSymbols[LocationNames_1.LocationName.NewTokyoGlobalPharmaceuticals] = "GPH";
exports.StockSymbols[LocationNames_1.LocationName.IshimaNovaMedical] = "NVMD";
exports.StockSymbols[LocationNames_1.LocationName.AevumWatchdogSecurity] = "WDS";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenLexoCorp] = "LXO";
exports.StockSymbols[LocationNames_1.LocationName.AevumRhoConstruction] = "RHOC";
exports.StockSymbols[LocationNames_1.LocationName.Sector12AlphaEnterprises] = "APHE";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenSysCoreSecurities] = "SYSC";
exports.StockSymbols[LocationNames_1.LocationName.VolhavenCompuTek] = "CTK";
exports.StockSymbols[LocationNames_1.LocationName.AevumNetLinkTechnologies] = "NTLK";
exports.StockSymbols[LocationNames_1.LocationName.IshimaOmegaSoftware] = "OMGA";
exports.StockSymbols[LocationNames_1.LocationName.Sector12FoodNStuff] = "FNS";
// Stocks for other companies
exports.StockSymbols["Sigma Cosmetics"] = "SGC";
exports.StockSymbols["Joes Guns"] = "JGN";
exports.StockSymbols["Catalyst Ventures"] = "CTYS";
exports.StockSymbols["Microdyne Technologies"] = "MDYN";
exports.StockSymbols["Titan Laboratories"] = "TITN";
/***/ }),
/* 285 */
/*!*************************************!*\
!*** ./src/Gang/GangMemberTasks.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberTasks = void 0;
const tasks_1 = __webpack_require__(/*! ./data/tasks */ 1055);
const GangMemberTask_1 = __webpack_require__(/*! ./GangMemberTask */ 677);
exports.GangMemberTasks = {};
(function () {
tasks_1.gangMemberTasksMetadata.forEach((e) => {
exports.GangMemberTasks[e.name] = new GangMemberTask_1.GangMemberTask(e.name, e.desc, e.isHacking, e.isCombat, e.params);
});
})();
/***/ }),
/* 286 */
/*!****************************************!*\
!*** ./src/Company/CompanyPosition.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompanyPosition = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const names = __importStar(__webpack_require__(/*! ./data/companypositionnames */ 58));
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;
/***/ }),
/* 287 */,
/* 288 */
/*!***********************************************!*\
!*** ./src/StockMarket/StockMarketHelpers.ts ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateBuyMaxAmount = exports.processTransactionForecastMovement = exports.getSellTransactionGain = exports.getBuyTransactionCost = exports.forecastChangePerPriceMovement = void 0;
/**
* Stock Market Helper Functions
*/
const Stock_1 = __webpack_require__(/*! ./Stock */ 191);
const PositionTypes_1 = __webpack_require__(/*! ./data/PositionTypes */ 98);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
// Amount by which a stock's forecast changes during each price movement
exports.forecastChangePerPriceMovement = 0.006;
/**
* Calculate the total cost of a "buy" transaction. This accounts for spread and commission.
* @param {Stock} stock - Stock being purchased
* @param {number} shares - Number of shares being transacted
* @param {PositionTypes} posType - Long or short position
* @returns {number | null} Total transaction cost. Returns null for an invalid transaction
*/
function getBuyTransactionCost(stock, shares, posType) {
if (isNaN(shares) || shares <= 0 || !(stock instanceof Stock_1.Stock)) {
return null;
}
// Cap the 'shares' arg at the stock's maximum shares. This'll prevent
// hanging in the case when a really big number is passed in
shares = Math.min(shares, stock.maxShares);
const isLong = (posType === PositionTypes_1.PositionTypes.Long);
// If the number of shares doesn't trigger a price movement, its a simple calculation
if (isLong) {
return (shares * stock.getAskPrice()) + Constants_1.CONSTANTS.StockMarketCommission;
}
else {
return (shares * stock.getBidPrice()) + Constants_1.CONSTANTS.StockMarketCommission;
}
}
exports.getBuyTransactionCost = getBuyTransactionCost;
/**
* Calculate the TOTAL amount of money gained from a sale (NOT net profit). This accounts
* for spread and commission.
* @param {Stock} stock - Stock being sold
* @param {number} shares - Number of sharse being transacted
* @param {PositionTypes} posType - Long or short position
* @returns {number | null} Amount of money gained from transaction. Returns null for an invalid transaction
*/
function getSellTransactionGain(stock, shares, posType) {
if (isNaN(shares) || shares <= 0 || !(stock instanceof Stock_1.Stock)) {
return null;
}
// Cap the 'shares' arg at the stock's maximum shares. This'll prevent
// hanging in the case when a really big number is passed in
shares = Math.min(shares, stock.maxShares);
const isLong = (posType === PositionTypes_1.PositionTypes.Long);
if (isLong) {
return (shares * stock.getBidPrice()) - Constants_1.CONSTANTS.StockMarketCommission;
}
else {
// Calculating gains for a short position requires calculating the profit made
const origCost = shares * stock.playerAvgShortPx;
const profit = ((stock.playerAvgShortPx - stock.getAskPrice()) * shares) - Constants_1.CONSTANTS.StockMarketCommission;
return origCost + profit;
}
}
exports.getSellTransactionGain = getSellTransactionGain;
/**
* Processes a stock's change in forecast & second-order forecast
* whenever it is transacted
* @param {Stock} stock - Stock being sold
* @param {number} shares - Number of sharse being transacted
* @param {PositionTypes} posType - Long or short position
*/
function processTransactionForecastMovement(stock, shares) {
if (isNaN(shares) || shares <= 0 || !(stock instanceof Stock_1.Stock)) {
return;
}
// Cap the 'shares' arg at the stock's maximum shares. This'll prevent
// hanging in the case when a really big number is passed in
shares = Math.min(shares, stock.maxShares);
// If there's only going to be one iteration at most
const firstShares = stock.shareTxUntilMovement;
if (shares <= firstShares) {
stock.shareTxUntilMovement -= shares;
if (stock.shareTxUntilMovement <= 0) {
stock.shareTxUntilMovement = stock.shareTxForMovement;
stock.influenceForecast(exports.forecastChangePerPriceMovement);
stock.influenceForecastForecast(exports.forecastChangePerPriceMovement * (stock.mv / 100));
}
return;
}
// Calculate how many iterations of price changes we need to account for
const remainingShares = shares - firstShares;
let numIterations = 1 + Math.ceil(remainingShares / stock.shareTxForMovement);
// If on the offchance we end up perfectly at the next price movement
stock.shareTxUntilMovement = stock.shareTxForMovement - ((shares - stock.shareTxUntilMovement) % stock.shareTxForMovement);
if (stock.shareTxUntilMovement === stock.shareTxForMovement || stock.shareTxUntilMovement <= 0) {
++numIterations;
stock.shareTxUntilMovement = stock.shareTxForMovement;
}
// Forecast always decreases in magnitude
const forecastChange = exports.forecastChangePerPriceMovement * (numIterations - 1);
const forecastForecastChange = forecastChange * (stock.mv / 100);
stock.influenceForecast(forecastChange);
stock.influenceForecastForecast(forecastForecastChange);
}
exports.processTransactionForecastMovement = processTransactionForecastMovement;
/**
* Calculate the maximum number of shares of a stock that can be purchased.
* Handles mid-transaction price movements, both L and S positions, etc.
* Used for the "Buy Max" button in the UI
* @param {Stock} stock - Stock being purchased
* @param {PositionTypes} posType - Long or short position
* @param {number} money - Amount of money player has
* @returns maximum number of shares that the player can purchase
*/
function calculateBuyMaxAmount(stock, posType, money) {
if (!(stock instanceof Stock_1.Stock)) {
return 0;
}
const isLong = (posType === PositionTypes_1.PositionTypes.Long);
const remainingMoney = money - Constants_1.CONSTANTS.StockMarketCommission;
const currPrice = isLong ? stock.getAskPrice() : stock.getBidPrice();
return Math.floor(remainingMoney / currPrice);
}
exports.calculateBuyMaxAmount = calculateBuyMaxAmount;
/***/ }),
/* 289 */
/*!*************************************!*\
!*** ./src/DarkWeb/DarkWebItems.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DarkWebItems = void 0;
const DarkWebItem_1 = __webpack_require__(/*! ./DarkWebItem */ 1056);
const Programs_1 = __webpack_require__(/*! ../Programs/Programs */ 30);
exports.DarkWebItems = {
BruteSSHProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.BruteSSHProgram.name, 500e3, "Opens up SSH Ports"),
FTPCrackProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.FTPCrackProgram.name, 1500e3, "Opens up FTP Ports"),
RelaySMTPProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.RelaySMTPProgram.name, 5e6, "Opens up SMTP Ports"),
HTTPWormProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.HTTPWormProgram.name, 30e6, "Opens up HTTP Ports"),
SQLInjectProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.SQLInjectProgram.name, 250e6, "Opens up SQL Ports"),
DeepscanV1: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.DeepscanV1.name, 500000, "Enables 'scan-analyze' with a depth up to 5"),
DeepscanV2: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.DeepscanV2.name, 25e6, "Enables 'scan-analyze' with a depth up to 10"),
AutolinkProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.AutoLink.name, 1e6, "Enables direct connect via 'scan-analyze'"),
ServerProfilerProgram: new DarkWebItem_1.DarkWebItem(Programs_1.Programs.ServerProfiler.name, 1e6, "Displays hacking and Netscript-related information about a server"),
};
/***/ }),
/* 290 */
/*!*************************************!*\
!*** ./utils/helpers/roundToTwo.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.roundToTwo = void 0;
/**
* 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;
/***/ }),
/* 291 */,
/* 292 */,
/* 293 */,
/* 294 */,
/* 295 */,
/* 296 */,
/* 297 */,
/* 298 */,
/* 299 */,
/* 300 */
/*!**********************************************!*\
!*** ./src/StockMarket/PlayerInfluencing.ts ***!
\**********************************************/
/*! no static exports found */
/*! exports used: influenceStockThroughCompanyWork, influenceStockThroughServerGrow, influenceStockThroughServerHack */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.influenceStockThroughCompanyWork = exports.influenceStockThroughServerGrow = exports.influenceStockThroughServerHack = exports.forecastForecastChangeFromCompanyWork = exports.forecastForecastChangeFromHack = void 0;
/**
* Implementation of the mechanisms that allow the player to affect the
* Stock Market
*/
const Stock_1 = __webpack_require__(/*! ./Stock */ 191);
const StockMarket_1 = __webpack_require__(/*! ./StockMarket */ 47);
// Change in second-order forecast due to hacks/grows
exports.forecastForecastChangeFromHack = 0.1;
// Change in second-order forecast due to company work
exports.forecastForecastChangeFromCompanyWork = 0.001;
/**
* Potentially decreases a stock's second-order forecast when its corresponding
* server is hacked. The chance of the hack decreasing the stock's second-order
* forecast is dependent on what percentage of the server's money is hacked
* @param {Server} server - Server being hack()ed
* @param {number} moneyHacked - Amount of money stolen from the server
*/
function influenceStockThroughServerHack(server, moneyHacked) {
const orgName = server.organizationName;
let stock = null;
if (typeof orgName === "string" && orgName !== "") {
stock = StockMarket_1.StockMarket[orgName];
}
if (!(stock instanceof Stock_1.Stock)) {
return;
}
const percTotalMoneyHacked = moneyHacked / server.moneyMax;
if (Math.random() < percTotalMoneyHacked) {
stock.changeForecastForecast(stock.otlkMagForecast - exports.forecastForecastChangeFromHack);
}
}
exports.influenceStockThroughServerHack = influenceStockThroughServerHack;
/**
* Potentially increases a stock's second-order forecast when its corresponding
* server is grown (grow()). The chance of the grow() to increase the stock's
* second-order forecast is dependent on how much money is added to the server
* @param {Server} server - Server being grow()n
* @param {number} moneyHacked - Amount of money added to the server
*/
function influenceStockThroughServerGrow(server, moneyGrown) {
const orgName = server.organizationName;
let stock = null;
if (typeof orgName === "string" && orgName !== "") {
stock = StockMarket_1.StockMarket[orgName];
}
if (!(stock instanceof Stock_1.Stock)) {
return;
}
const percTotalMoneyGrown = moneyGrown / server.moneyMax;
if (Math.random() < percTotalMoneyGrown) {
stock.changeForecastForecast(stock.otlkMagForecast + exports.forecastForecastChangeFromHack);
}
}
exports.influenceStockThroughServerGrow = influenceStockThroughServerGrow;
/**
* Potentially increases a stock's second-order forecast when the player works for
* its corresponding company.
* @param {Company} company - Company being worked for
* @param {number} performanceMult - Effectiveness of player's work. Affects influence
* @param {number} cyclesOfWork - # game cycles of work being processed
*/
function influenceStockThroughCompanyWork(company, performanceMult, cyclesOfWork) {
const compName = company.name;
let stock = null;
if (typeof compName === "string" && compName !== "") {
stock = StockMarket_1.StockMarket[compName];
}
if (!(stock instanceof Stock_1.Stock)) {
return;
}
if (Math.random() < 0.002 * cyclesOfWork) {
const change = exports.forecastForecastChangeFromCompanyWork * performanceMult;
stock.changeForecastForecast(stock.otlkMagForecast + change);
}
}
exports.influenceStockThroughCompanyWork = influenceStockThroughCompanyWork;
/***/ }),
/* 301 */
/*!**************************!*\
!*** ./src/Gang/Gang.ts ***!
\**************************/
/*! no static exports found */
/*! exports used: Gang */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* TODO
* Add police clashes
* balance point to keep them from running out of control
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Gang = void 0;
const Faction_1 = __webpack_require__(/*! ../Faction/Faction */ 125);
const Factions_1 = __webpack_require__(/*! ../Faction/Factions */ 17);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const exceptionAlert_1 = __webpack_require__(/*! ../../utils/helpers/exceptionAlert */ 91);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 678);
const Constants_2 = __webpack_require__(/*! ../Constants */ 11);
const GangMemberTasks_1 = __webpack_require__(/*! ./GangMemberTasks */ 285);
const AllGangs_1 = __webpack_require__(/*! ./AllGangs */ 85);
const GangMember_1 = __webpack_require__(/*! ./GangMember */ 1054);
class Gang {
constructor(facName = "", hacking = false) {
this.facName = facName;
this.members = [];
this.wanted = 1;
this.respect = 1;
this.isHackingGang = hacking;
this.respectGainRate = 0;
this.wantedGainRate = 0;
this.moneyGainRate = 0;
// When processing gains, this stores the number of cycles until some
// limit is reached, and then calculates and applies the gains only at that limit
this.storedCycles = 0;
// Separate variable to keep track of cycles for Territry + Power gang, which
// happens on a slower "clock" than normal processing
this.storedTerritoryAndPowerCycles = 0;
this.territoryClashChance = 0;
this.territoryWarfareEngaged = false;
this.notifyMemberDeath = true;
}
getPower() {
return AllGangs_1.AllGangs[this.facName].power;
}
getTerritory() {
return AllGangs_1.AllGangs[this.facName].territory;
}
process(numCycles = 1, player) {
const CyclesPerSecond = 1000 / Constants_2.CONSTANTS._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) {
console.error(`Exception caught when processing Gang: ${e}`);
}
}
processGains(numCycles = 1, player) {
// Get gains per cycle
let moneyGains = 0;
let respectGains = 0;
let wantedLevelGains = 0;
let justice = 0;
for (let i = 0; i < this.members.length; ++i) {
respectGains += (this.members[i].calculateRespectGain(this));
moneyGains += (this.members[i].calculateMoneyGain(this));
const wantedLevelGain = this.members[i].calculateWantedLevelGain(this);
wantedLevelGains += wantedLevelGain;
if (this.members[i].getTask().baseWanted < 0)
justice++; // this member is lowering wanted.
}
this.respectGainRate = respectGains;
this.wantedGainRate = wantedLevelGains;
this.moneyGainRate = moneyGains;
const gain = respectGains * numCycles;
this.respect += gain;
// Faction reputation gains is respect gain divided by some constant
const fac = Factions_1.Factions[this.facName];
if (!(fac instanceof Faction_1.Faction)) {
DialogBox_1.dialogBoxCreate("ERROR: Could not get Faction associates with your gang. This is a bug, please report to game dev");
throw new Error('Could not find the faction associated with this gang.');
}
const favorMult = 1 + (fac.favor / 100);
fac.playerReputation += ((player.faction_rep_mult * gain * favorMult) / Constants_1.GangConstants.GangRespectToReputationRatio);
// Keep track of respect gained per member
for (let i = 0; i < this.members.length; ++i) {
this.members[i].recordEarnedRespect(numCycles, this);
}
if (!(this.wanted === 1 && wantedLevelGains < 0)) {
const oldWanted = this.wanted;
let newWanted = oldWanted + (wantedLevelGains * numCycles);
newWanted = newWanted * (1 - justice * 0.001); // safeguard
// Prevent overflow
if (wantedLevelGains <= 0 && newWanted > oldWanted)
newWanted = 1;
this.wanted = newWanted;
if (this.wanted < 1)
this.wanted = 1;
}
player.gainMoney(moneyGains * numCycles);
player.recordMoneySource(moneyGains * numCycles, "gang");
}
processTerritoryAndPowerGains(numCycles = 1) {
this.storedTerritoryAndPowerCycles += numCycles;
if (this.storedTerritoryAndPowerCycles < Constants_1.GangConstants.CyclesPerTerritoryAndPowerUpdate)
return;
this.storedTerritoryAndPowerCycles -= Constants_1.GangConstants.CyclesPerTerritoryAndPowerUpdate;
// Process power first
const gangName = this.facName;
for (const name in AllGangs_1.AllGangs) {
if (AllGangs_1.AllGangs.hasOwnProperty(name)) {
if (name == gangName) {
AllGangs_1.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_1.AllGangs[name].power * 0.005;
AllGangs_1.AllGangs[name].power += Math.min(0.85, multiplicativeGain);
}
else {
// Additive gain (50% chance)
const additiveGain = 0.75 * gainRoll * AllGangs_1.AllGangs[name].territory;
AllGangs_1.AllGangs[name].power += (additiveGain);
}
}
}
}
// Determine if territory should be processed
if (this.territoryWarfareEngaged) {
this.territoryClashChance = 1;
}
else if (this.territoryClashChance > 0) {
// Engagement turned off, but still a positive clash chance. So there's
// still a chance of clashing but it slowly goes down over time
this.territoryClashChance = Math.max(0, this.territoryClashChance - 0.01);
}
// Then process territory
for (let i = 0; i < Constants_1.GangConstants.Names.length; ++i) {
const others = Constants_1.GangConstants.Names.filter((e) => {
return e !== Constants_1.GangConstants.Names[i];
});
const other = getRandomInt_1.getRandomInt(0, others.length - 1);
const thisGang = Constants_1.GangConstants.Names[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_1.AllGangs[thisGang].power;
const otherPwr = AllGangs_1.AllGangs[otherGang].power;
const thisChance = thisPwr / (thisPwr + otherPwr);
function calculateTerritoryGain(winGang, loseGang) {
const powerBonus = Math.max(1, 1 + Math.log(AllGangs_1.AllGangs[winGang].power / AllGangs_1.AllGangs[loseGang].power) / Math.log(50));
const gains = Math.min(AllGangs_1.AllGangs[loseGang].territory, powerBonus * 0.0001 * (Math.random() + .5));
return gains;
}
if (Math.random() < thisChance) {
if (AllGangs_1.AllGangs[otherGang].territory <= 0)
return;
const territoryGain = calculateTerritoryGain(thisGang, otherGang);
AllGangs_1.AllGangs[thisGang].territory += territoryGain;
AllGangs_1.AllGangs[otherGang].territory -= territoryGain;
if (thisGang === gangName) {
this.clash(true); // Player won
AllGangs_1.AllGangs[otherGang].power *= (1 / 1.01);
}
else if (otherGang === gangName) {
this.clash(false); // Player lost
}
else {
AllGangs_1.AllGangs[otherGang].power *= (1 / 1.01);
}
}
else {
if (AllGangs_1.AllGangs[thisGang].territory <= 0)
return;
const territoryGain = calculateTerritoryGain(otherGang, thisGang);
AllGangs_1.AllGangs[thisGang].territory -= territoryGain;
AllGangs_1.AllGangs[otherGang].territory += territoryGain;
if (thisGang === gangName) {
this.clash(false); // Player lost
}
else if (otherGang === gangName) {
this.clash(true); // Player won
AllGangs_1.AllGangs[thisGang].power *= (1 / 1.01);
}
else {
AllGangs_1.AllGangs[thisGang].power *= (1 / 1.01);
}
}
}
}
processExperienceGains(numCycles = 1) {
for (let i = 0; i < this.members.length; ++i) {
this.members[i].gainExperience(numCycles);
this.members[i].updateSkillLevels();
}
}
clash(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
else
AllGangs_1.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);
}
}
}
canRecruitMember() {
if (this.members.length >= Constants_1.GangConstants.MaximumGangMembers)
return false;
return (this.respect >= this.getRespectNeededToRecruitMember());
}
getRespectNeededToRecruitMember() {
// 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.pow(5, i);
}
recruitMember(name) {
name = String(name);
if (name === "" || !this.canRecruitMember())
return false;
// Check for already-existing names
const sameNames = this.members.filter((m) => m.name === name);
if (sameNames.length >= 1)
return false;
const member = new GangMember_1.GangMember(name);
this.members.push(member);
return true;
}
// Money and Respect gains multiplied by this number (< 1)
getWantedPenalty() {
return (this.respect) / (this.respect + this.wanted);
}
//Calculates power GAIN, which is added onto the Gang's existing power
calculatePower() {
let memberTotal = 0;
for (let i = 0; i < this.members.length; ++i) {
if (!GangMemberTasks_1.GangMemberTasks.hasOwnProperty(this.members[i].task) ||
this.members[i].task !== "Territory Warfare")
continue;
memberTotal += this.members[i].calculatePower();
}
return (0.015 * Math.max(0.002, this.getTerritory()) * memberTotal);
}
killMember(member) {
// Player loses a percentage of total respect, plus whatever respect that member has earned
const totalRespect = this.respect;
const lostRespect = (0.05 * totalRespect) + member.earnedRespect;
this.respect = Math.max(0, totalRespect - lostRespect);
for (let i = 0; i < this.members.length; ++i) {
if (member.name === this.members[i].name) {
this.members.splice(i, 1);
break;
}
}
// Notify of death
if (this.notifyMemberDeath) {
DialogBox_1.dialogBoxCreate(`${member.name} was killed in a gang clash! You lost ${lostRespect} respect`);
}
}
ascendMember(member, workerScript) {
try {
const res = member.ascend();
this.respect = Math.max(1, this.respect - res.respect);
if (workerScript) {
workerScript.log('ascend', `Ascended Gang member ${member.name}`);
}
return res;
}
catch (e) {
if (workerScript == null) {
exceptionAlert_1.exceptionAlert(e);
}
throw e; // Re-throw, will be caught in the Netscript Function
}
}
// Cost of upgrade gets cheaper as gang increases in respect + power
getDiscount() {
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'
getAllTaskNames() {
return Object.keys(GangMemberTasks_1.GangMemberTasks).filter((taskName) => {
const task = GangMemberTasks_1.GangMemberTasks[taskName];
if (task == null)
return false;
if (task.name === "Unassigned")
return false;
// yes you need both checks
return this.isHackingGang === task.isHacking ||
!this.isHackingGang === task.isCombat;
});
}
getUpgradeCost(upg) {
if (upg == null) {
return Infinity;
}
return upg.cost / this.getDiscount();
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Gang", this);
}
/**
* Initiatizes a Gang object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Gang, value.data);
}
}
exports.Gang = Gang;
JSONReviver_1.Reviver.constructors.Gang = Gang;
/***/ }),
/* 302 */
/*!******************************!*\
!*** ./src/Netscript/Pid.ts ***!
\******************************/
/*! no static exports found */
/*! exports used: generateNextPid, resetPidCounter */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetPidCounter = exports.generateNextPid = void 0;
const WorkerScripts_1 = __webpack_require__(/*! ./WorkerScripts */ 112);
let pidCounter = 1;
/**
* Find and return the next availble PID for a script
*/
function generateNextPid() {
let tempCounter = pidCounter;
// Cap the number of search iterations at some arbitrary value to avoid
// infinite loops. We'll assume that players wont have 1mil+ running scripts
let found = false;
for (let i = 0; i < 1e6;) {
if (!WorkerScripts_1.workerScripts.has(tempCounter + i)) {
found = true;
tempCounter = tempCounter + i;
break;
}
if (i === Number.MAX_SAFE_INTEGER - 1) {
i = 1;
}
else {
++i;
}
}
if (found) {
pidCounter = tempCounter + 1;
if (pidCounter >= Number.MAX_SAFE_INTEGER) {
pidCounter = 1;
}
return tempCounter;
}
else {
return -1;
}
}
exports.generateNextPid = generateNextPid;
function resetPidCounter() {
pidCounter = 1;
}
exports.resetPidCounter = resetPidCounter;
/***/ }),
/* 303 */
/*!******************************!*\
!*** ./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; });
/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Player */ 2);
/* 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";
// special exception for bladeburner popup because it's only visible later.
document.getElementById("settingsSuppressBladeburnerPopup")
.closest('fieldset').style.display =
_src_Player__WEBPACK_IMPORTED_MODULE_0__["Player"].canAccessBladeburner() ? 'block' : 'none';
setTimeout(function() {
gameOptionsOpened = true;
}, 500);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 304 */
/*!****************************************!*\
!*** ./src/Programs/ProgramHelpers.js ***!
\****************************************/
/*! exports provided: displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */
/*! exports used: displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayCreateProgramContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getNumAvailableCreateProgram; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initCreateProgramButtons; });
/* harmony import */ var _Programs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Programs */ 30);
/* harmony import */ var _Programs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Programs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Player */ 2);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__);
// this has the same key as 'Programs', not program names
const aLinks = {};
function displayCreateProgramContent() {
for(const key in aLinks) {
const p = _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key]
aLinks[key].style.display = "none";
if(!_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(p.name) && p.create.req(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"])){
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__WEBPACK_IMPORTED_MODULE_0__["Programs"]) {
// Non-creatable program
if (_Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].create == null) {
continue;
}
// Already has program
if (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(_Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].name)) {
continue;
}
// Does not meet requirements
if (!_Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].create.req(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"])) {
continue;
}
count++;
}
if (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable === false && count > 0) {
_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable = true;
document.getElementById("hacking-menu-header").click();
document.getElementById("hacking-menu-header").click();
}
return count;
}
function initCreateProgramButtons() {
const createProgramList = document.getElementById("create-program-list");
for (const key in _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"]) {
if(_Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].create === null) {
continue;
}
const elem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", {
class: "a-link-button", id: _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].htmlID(), innerText: _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].name,
tooltip: _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key].create.tooltip,
});
aLinks[key] = elem;
createProgramList.appendChild(elem);
}
for (const key in aLinks) {
const p = _Programs__WEBPACK_IMPORTED_MODULE_0__["Programs"][key]
aLinks[key].addEventListener("click", function() {
_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(p.name, p.create.time, p.create.level);
return false;
});
}
}
/***/ }),
/* 305 */,
/* 306 */
/*!*****************************************!*\
!*** ./src/Hacking/netscriptCanHack.ts ***!
\*****************************************/
/*! no static exports found */
/*! exports used: netscriptCanGrow, netscriptCanHack, netscriptCanWeaken */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.netscriptCanWeaken = exports.netscriptCanGrow = exports.netscriptCanHack = void 0;
function baseCheck(server, fnName) {
const hostname = server.hostname;
if (!("requiredHackingSkill" in server)) {
return {
res: false,
msg: `Cannot ${fnName} ${hostname} server because it is a Hacknet Node`,
};
}
if (server.hasAdminRights === false) {
return {
res: false,
msg: `Cannot ${fnName} ${hostname} server because you do not have root access`,
};
}
return { res: true };
}
function netscriptCanHack(server, p) {
const initialCheck = baseCheck(server, "hack");
if (!initialCheck.res) {
return initialCheck;
}
const s = server;
if (s.requiredHackingSkill > p.hacking_skill) {
return {
res: false,
msg: `Cannot hack ${server.hostname} server because your hacking skill is not high enough`,
};
}
return { res: true };
}
exports.netscriptCanHack = netscriptCanHack;
function netscriptCanGrow(server) {
return baseCheck(server, "grow");
}
exports.netscriptCanGrow = netscriptCanGrow;
function netscriptCanWeaken(server) {
return baseCheck(server, "weaken");
}
exports.netscriptCanWeaken = netscriptCanWeaken;
/***/ }),
/* 307 */,
/* 308 */,
/* 309 */,
/* 310 */,
/* 311 */,
/* 312 */,
/* 313 */,
/* 314 */,
/* 315 */,
/* 316 */,
/* 317 */,
/* 318 */,
/* 319 */,
/* 320 */,
/* 321 */,
/* 322 */,
/* 323 */,
/* 324 */,
/* 325 */,
/* 326 */,
/* 327 */,
/* 328 */,
/* 329 */,
/* 330 */,
/* 331 */,
/* 332 */,
/* 333 */,
/* 334 */,
/* 335 */,
/* 336 */,
/* 337 */,
/* 338 */,
/* 339 */,
/* 340 */,
/* 341 */,
/* 342 */,
/* 343 */,
/* 344 */,
/* 345 */,
/* 346 */,
/* 347 */,
/* 348 */,
/* 349 */,
/* 350 */,
/* 351 */,
/* 352 */,
/* 353 */,
/* 354 */,
/* 355 */,
/* 356 */,
/* 357 */,
/* 358 */,
/* 359 */,
/* 360 */,
/* 361 */,
/* 362 */,
/* 363 */,
/* 364 */,
/* 365 */,
/* 366 */,
/* 367 */,
/* 368 */,
/* 369 */,
/* 370 */,
/* 371 */,
/* 372 */,
/* 373 */,
/* 374 */,
/* 375 */,
/* 376 */,
/* 377 */,
/* 378 */,
/* 379 */,
/* 380 */,
/* 381 */,
/* 382 */,
/* 383 */,
/* 384 */,
/* 385 */,
/* 386 */,
/* 387 */,
/* 388 */
/*!*****************************!*\
!*** ./src/Casino/Game.tsx ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Game = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const gainLimit = 10e9;
class Game extends React.Component {
win(p, n) {
p.gainMoney(n);
p.recordMoneySource(n, "casino");
}
reachedLimit(p) {
const reached = p.getCasinoWinnings() > gainLimit;
if (reached) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null, "Alright cheater get out of here. You're not allowed here anymore."));
}
return reached;
}
}
exports.Game = Game;
/***/ }),
/* 389 */,
/* 390 */,
/* 391 */,
/* 392 */,
/* 393 */
/*!****************************************!*\
!*** ./src/Bladeburner/data/Icons.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.killIcon = exports.stealthIcon = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
exports.stealthIcon = React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16px", height: "16px", viewBox: "0 0 166 132", style: { fill: '#adff2f' } },
React.createElement("g", null,
React.createElement("path", { d: "M132.658-0.18l-24.321,24.321c-7.915-2.71-16.342-4.392-25.087-4.392c-45.84,0-83,46-83,46 s14.1,17.44,35.635,30.844L12.32,120.158l12.021,12.021L144.68,11.841L132.658-0.18z M52.033,80.445 c-2.104-4.458-3.283-9.438-3.283-14.695c0-19.054,15.446-34.5,34.5-34.5c5.258,0,10.237,1.179,14.695,3.284L52.033,80.445z" }),
React.createElement("path", { d: "M134.865,37.656l-18.482,18.482c0.884,3.052,1.367,6.275,1.367,9.612c0,19.055-15.446,34.5-34.5,34.5 c-3.337,0-6.56-0.483-9.611-1.367l-10.124,10.124c6.326,1.725,12.934,2.743,19.735,2.743c45.84,0,83-46,83-46 S153.987,50.575,134.865,37.656z" })));
exports.killIcon = React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16px", height: "16px", viewBox: "-22 0 511 511.99561", style: { fill: '#adff2f' } },
React.createElement("path", { d: "m.496094 466.242188 39.902344-39.902344 45.753906 45.753906-39.898438 39.902344zm0 0" }),
React.createElement("path", { d: "m468.421875 89.832031-1.675781-89.832031-300.265625 300.265625 45.753906 45.753906zm0 0" }),
React.createElement("path", { d: "m95.210938 316.785156 16.84375 16.847656h.003906l83.65625 83.65625 22.753906-22.753906-100.503906-100.503906zm0 0" }),
React.createElement("path", { d: "m101.445312 365.300781-39.902343 39.902344 45.753906 45.753906 39.902344-39.902343-39.90625-39.902344zm0 0" }));
/***/ }),
/* 394 */,
/* 395 */,
/* 396 */,
/* 397 */,
/* 398 */,
/* 399 */
/*!****************************!*\
!*** ./utils/IPAddress.ts ***!
\****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRandomIp = void 0;
const getRandomByte_1 = __webpack_require__(/*! ./helpers/getRandomByte */ 1064);
/**
* Generate a random IP address
* Does not check to see if the IP already exists in the game
*/
function createRandomIp() {
const ip = getRandomByte_1.getRandomByte(99) + '.' +
getRandomByte_1.getRandomByte(9) + '.' +
getRandomByte_1.getRandomByte(9) + '.' +
getRandomByte_1.getRandomByte(9);
return ip;
}
exports.createRandomIp = createRandomIp;
/***/ }),
/* 400 */
/*!******************************************!*\
!*** ./src/Corporation/MaterialSizes.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaterialSizes = void 0;
// Map of material (by name) to their sizes (how much space it takes in warehouse)
exports.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,
"Real Estate": 0,
"AI Cores": 0,
};
/***/ }),
/* 401 */,
/* 402 */,
/* 403 */,
/* 404 */,
/* 405 */,
/* 406 */,
/* 407 */,
/* 408 */
/*!************************************!*\
!*** ./src/Locations/Locations.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Locations = void 0;
/**
* Map of all Locations in the game
* Key = Location name, value = Location object
*/
const City_1 = __webpack_require__(/*! ./City */ 966);
const Cities_1 = __webpack_require__(/*! ./Cities */ 192);
const Location_1 = __webpack_require__(/*! ./Location */ 965);
const CityNames_1 = __webpack_require__(/*! ./data/CityNames */ 42);
const LocationsMetadata_1 = __webpack_require__(/*! ./data/LocationsMetadata */ 964);
exports.Locations = {};
/**
* Here, we'll initialize both Locations and Cities data. These can both
* be initialized from the `LocationsMetadata`
*/
function constructLocation(p) {
if (!p.name) {
throw new Error(`Invalid constructor parameters for Location. No 'name' property`);
}
if (exports.Locations[p.name] instanceof Location_1.Location) {
console.warn(`Property with name ${p.name} already exists and is being overwritten`);
}
exports.Locations[p.name] = new Location_1.Location(p);
return exports.Locations[p.name];
}
// First construct all cities
Cities_1.Cities[CityNames_1.CityName.Aevum] = new City_1.City(CityNames_1.CityName.Aevum);
Cities_1.Cities[CityNames_1.CityName.Chongqing] = new City_1.City(CityNames_1.CityName.Chongqing);
Cities_1.Cities[CityNames_1.CityName.Ishima] = new City_1.City(CityNames_1.CityName.Ishima);
Cities_1.Cities[CityNames_1.CityName.NewTokyo] = new City_1.City(CityNames_1.CityName.NewTokyo);
Cities_1.Cities[CityNames_1.CityName.Sector12] = new City_1.City(CityNames_1.CityName.Sector12);
Cities_1.Cities[CityNames_1.CityName.Volhaven] = new City_1.City(CityNames_1.CityName.Volhaven);
Cities_1.Cities[CityNames_1.CityName.Aevum].asciiArt = `
[aevum police headquarters] 26
o
I \\ [bachman & associates]
\\ 56 B
x \\ [summit university]
\\ \\ 28
\\ [snap fitness gym] x o--L-----------N
K \\ /
\\ \\ Q [casino]
x 58 \\ / [travel agency]
\\ 94 95 o
90 x 59 o------o |
\\ / \\ | 98 102 103
o--------O------x----o 93 96 o-----+------------o o----o
\\ | \\ /
[hospital] \\ 61 [ecorp] x 31 99 o-F-o 101
o |
| o---E-- | [fulcrum tech.]
x 62 / A [aerocorp]
[crush fitness gym] | / |
| / |
o--------D------+--o o
| |\\ [rho construction]
H [netlink tech.] | J
| | \\
| 34 x \\
[clarke inc.] C | \\ [world stock exchange]
| | \\
| | o-M-------R--------o
[galactic cybersystems] G 35 x
| [watchdog security]
|
67 o
[the slums] P `;
Cities_1.Cities[CityNames_1.CityName.Chongqing].asciiArt = `
|
75 o
\\
o 76
7 | |
| + 77
[world stock exchange] F |
\\ o 78 [kuaigong international]
\\ /
38 o----x--x------x------A---------
/ 39 | 41
37 o + 79 o--x--x-C-0
/ | /
/ x-----+-----x-----0 [hospital]
[solaris space system] B |
| + 80
| |
34 o E [travel agency]
|
|
x 82
[the slums] D `;
Cities_1.Cities[CityNames_1.CityName.Ishima].asciiArt = `
o 59
o o |
[storm tech.] | | G [world stock exchange]
| | 28 |
23 o--C------o--------+----x----o |
/ / 25 | 27 \\ x 57
/ / | \\ |
/ / | \\ |
o 22 o | \\| 29/56
| | o
| [hospital] D / \\ 3 2 1
o | / \\ o-------x------o
/ o / \\ /
48 o / 55 x \\ /
\\ / / x
\\ / [nova medical] / 4/30 \\
49 x A \\
/ \\ / \\
/ \\ [travel agency] F o 31
/ \\ 51 /
/ o----B------x-----o
o 50 52
[omega soft.]
[the slums] E `;
Cities_1.Cities[CityNames_1.CityName.NewTokyo].asciiArt = `
o
\\
\\ [defcomm]
\\
o--x---A--x--o [travel agency]
7 8 10 G
[vitalife] o 12 [global pharmaceuticals]
|
o--D-x----x-------x-C-+--------x--x-B-x---x-o
21 22 23 \\ 24 25 26 27
\\
[noodle bar] x 14
\\
\\
[hospital] o 15 [world stock exchange]
|
o--x--E--x-----x-----x---+---x----x--H--x-o
|
|
o 17
F [the slums]
`;
Cities_1.Cities[CityNames_1.CityName.Sector12].asciiArt = `
78 o 97
o [icarus microsystems] /
N [powerhouse gym] o I
1 | | /
o-----+---x----o 4 A [alpha ent.] o-------o /
| 3 \\ | \\ /
| \\ | [iron gym] x 95
(79) x \\ | / \\
| o-E----+----x----J--o 10 / o----T--o
| | 8 \\ 94 x
80 x [city hall] | x 11 / [world stock exchange]
| | \\ /
| C [cia] \\ /
Q [hospital] | F P [universal energy]
| o [deltaone] \\ /
| 35 o---------x 13/92/36
L [megacorp] 33 / / \\
| o------------o 34 / \\
(29) | / [carmichael sec.] D \\
o-----+-----x------o / O [rothman university]
| 31 32 [nsa] M
| /
B [blade industries] H
| / [four sigma]
| [joe's guns] /
| /
85 o--G--------K--------S-------o 88 [the slums] R
[foodnstuff] [travel agency] `;
Cities_1.Cities[CityNames_1.CityName.Volhaven].asciiArt = `
[omnia cybersystems]
17 66 68
o o------G-------o
\\ / \\
\\ o 65 o 69
[syscore sec.] H | |
\\ | | [millenium fitness gym]
\\ | 21 22 23 24 | 26
o----+--x--x----x---x---+-----x-------D-----o
19 | | 28
| F [omnitek inc.]
[hospital] J 63 o
| / 72
3 | 5 6 / 9
o--------+----x-----x----+----------M-------o
/ | |
/ 61 x [helios labs] B [world stock exchange]
[travel agency] L | |
/ | o
/ E [nwo] / 75
/ [computek] | /
/ A-------o------I-----o
1 o | |
| [zb] o 77
[lexocorp] C
|
o
57
[the slums] K `;
// Then construct all locations, and add them to the cities as we go.
for (const metadata of LocationsMetadata_1.LocationsMetadata) {
const loc = constructLocation(metadata);
const cityName = loc.city;
if (cityName === null) {
// Generic location, add to all cities
for (const city in Cities_1.Cities) {
Cities_1.Cities[city].addLocation(loc.name);
}
}
else {
Cities_1.Cities[cityName].addLocation(loc.name);
}
}
/***/ }),
/* 409 */
/*!***************************************!*\
!*** ./utils/helpers/getTimestamp.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTimestamp = void 0;
/**
* 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;
/***/ }),
/* 410 */
/*!********************************************!*\
!*** ./src/Faction/FactionWorkTypeEnum.ts ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FactionWorkType = void 0;
var FactionWorkType;
(function (FactionWorkType) {
FactionWorkType[FactionWorkType["Field"] = 0] = "Field";
FactionWorkType[FactionWorkType["Hacking"] = 1] = "Hacking";
FactionWorkType[FactionWorkType["None"] = 2] = "None";
FactionWorkType[FactionWorkType["Security"] = 3] = "Security";
})(FactionWorkType = exports.FactionWorkType || (exports.FactionWorkType = {}));
/***/ }),
/* 411 */
/*!****************************************************!*\
!*** ./src/PersonObjects/formulas/intelligence.ts ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateIntelligenceBonus = void 0;
function calculateIntelligenceBonus(intelligence, weight = 1) {
return 1 + (weight * Math.pow(intelligence, 0.8) / 600);
}
exports.calculateIntelligenceBonus = calculateIntelligenceBonus;
/***/ }),
/* 412 */
/*!**********************************!*\
!*** ./src/Hospital/Hospital.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateHospitalizationCost = exports.getHospitalizationCost = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
function getHospitalizationCost(p) {
let money;
if (typeof p.money === 'number') {
money = p.money;
}
else {
money = p.money.toNumber();
}
if (money < 0) {
return 0;
}
return Math.min(money * 0.1, (p.max_hp - p.hp) * Constants_1.CONSTANTS.HospitalCostPerHp);
}
exports.getHospitalizationCost = getHospitalizationCost;
function calculateHospitalizationCost(p, damage) {
const oldhp = p.hp;
p.hp -= damage;
const cost = getHospitalizationCost(p);
p.hp = oldhp;
return cost;
}
exports.calculateHospitalizationCost = calculateHospitalizationCost;
/***/ }),
/* 413 */,
/* 414 */,
/* 415 */,
/* 416 */,
/* 417 */,
/* 418 */,
/* 419 */,
/* 420 */,
/* 421 */,
/* 422 */,
/* 423 */,
/* 424 */,
/* 425 */,
/* 426 */,
/* 427 */,
/* 428 */,
/* 429 */,
/* 430 */,
/* 431 */,
/* 432 */,
/* 433 */,
/* 434 */,
/* 435 */,
/* 436 */,
/* 437 */,
/* 438 */,
/* 439 */,
/* 440 */,
/* 441 */
/*!*****************************************!*\
!*** ./src/ui/React/ReputationRate.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReputationRate = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Reputation_1 = __webpack_require__(/*! ../../ui/React/Reputation */ 59);
function ReputationRate(reputation) {
return Reputation_1.Reputation(`${numeralFormat_1.numeralWrapper.formatReputation(reputation)} / sec`);
}
exports.ReputationRate = ReputationRate;
/***/ }),
/* 442 */
/*!**********************************************!*\
!*** ./src/Company/GetJobRequirementText.ts ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJobRequirementText = void 0;
/**
* 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: ";
reqText += (reqHacking.toString() + " hacking ");
reqText += (reqStrength.toString() + " strength ");
reqText += (reqDefense.toString() + " defense ");
reqText += (reqDexterity.toString() + " dexterity ");
reqText += (reqAgility.toString() + " agility ");
reqText += (reqCharisma.toString() + " charisma ");
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;
/***/ }),
/* 443 */
/*!*************************************************!*\
!*** ./src/SourceFile/PlayerOwnedSourceFile.ts ***!
\*************************************************/
/*! no static exports found */
/*! exports used: PlayerOwnedSourceFile */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayerOwnedSourceFile = void 0;
class PlayerOwnedSourceFile {
constructor(n, level) {
// Source-File level
this.lvl = 1;
// Source-File number
this.n = 1;
this.n = n;
this.lvl = level;
}
}
exports.PlayerOwnedSourceFile = PlayerOwnedSourceFile;
/***/ }),
/* 444 */
/*!********************************************!*\
!*** ./src/Script/RunningScriptHelpers.ts ***!
\********************************************/
/*! no static exports found */
/*! exports used: getRamUsageFromRunningScript */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRamUsageFromRunningScript = void 0;
const AllServers_1 = __webpack_require__(/*! ../Server/AllServers */ 20);
function getRamUsageFromRunningScript(script) {
if (script.ramUsage != null && script.ramUsage > 0) {
return script.ramUsage; // Use cached value
}
const server = AllServers_1.AllServers[script.server];
if (server == null) {
return 0;
}
for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename === script.filename) {
// Cache the ram usage for the next call
script.ramUsage = server.scripts[i].ramUsage;
return script.ramUsage;
}
}
return 0;
}
exports.getRamUsageFromRunningScript = getRamUsageFromRunningScript;
/***/ }),
/* 445 */,
/* 446 */
/*!***********************************!*\
!*** ./src/NetscriptFunctions.js ***!
\***********************************/
/*! exports provided: NetscriptFunctions */
/*! 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__, "NetscriptFunctions", function() { return NetscriptFunctions; });
/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sprintf-js */ 459);
/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sprintf_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var arg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! arg */ 445);
/* harmony import */ var arg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(arg__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Netscript/RamCostGenerator */ 10);
/* harmony import */ var _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Netscript/WorkerScriptStartStopEventEmitter */ 147);
/* harmony import */ var _Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Augmentation/AugmentationHelpers */ 79);
/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Prestige */ 173);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Crime/CrimeHelpers */ 246);
/* harmony import */ var _Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Bladeburner/Bladeburner */ 94);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Company/Company */ 138);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Company_Company__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Company/CompanyPosition */ 286);
/* harmony import */ var _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Company/CompanyPositions */ 52);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./DarkWeb/DarkWebItems */ 289);
/* harmony import */ var _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Hacking */ 50);
/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Hacking__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _Server_formulas_grow__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Server/formulas/grow */ 522);
/* harmony import */ var _Server_formulas_grow__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Server_formulas_grow__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Gang_Gang__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Gang/Gang */ 301);
/* harmony import */ var _Gang_Gang__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_Gang_Gang__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Gang/AllGangs */ 85);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _Gang_GangMemberTasks__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Gang/GangMemberTasks */ 285);
/* harmony import */ var _Gang_GangMemberTasks__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_Gang_GangMemberTasks__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Gang/GangMemberUpgrades */ 175);
/* harmony import */ var _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Faction/FactionHelpers */ 71);
/* harmony import */ var _Faction_FactionWorkTypeEnum__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Faction/FactionWorkTypeEnum */ 410);
/* harmony import */ var _Faction_FactionWorkTypeEnum__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_Faction_FactionWorkTypeEnum__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Hacking/netscriptCanHack */ 306);
/* harmony import */ var _Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Hacknet/HacknetHelpers */ 25);
/* harmony import */ var _Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Hacknet/formulas/HacknetNodes */ 153);
/* harmony import */ var _Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Hacknet/formulas/HacknetServers */ 139);
/* harmony import */ var _Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Hacknet/data/Constants */ 34);
/* harmony import */ var _Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Hacknet/HacknetServer */ 78);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Locations/data/CityNames */ 42);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Locations/data/LocationNames */ 40);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./Terminal */ 74);
/* harmony import */ var _PersonObjects_formulas_skill__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./PersonObjects/formulas/skill */ 121);
/* harmony import */ var _PersonObjects_formulas_skill__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_formulas_skill__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Message/Message */ 73);
/* harmony import */ var _Message_Message__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_Message_Message__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./Missions */ 81);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _Script_Script__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./Script/Script */ 228);
/* harmony import */ var _Script_Script__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_Script_Script__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var _Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./Script/ScriptHelpers */ 120);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./Script/ScriptHelpersTS */ 66);
/* harmony import */ var _Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./Script/RunningScript */ 194);
/* harmony import */ var _Script_RunningScript__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(_Script_RunningScript__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var _Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./Server/ServerPurchases */ 136);
/* harmony import */ var _Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./StockMarket/BuyingAndSelling */ 174);
/* harmony import */ var _StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__);
/* harmony import */ var _StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./StockMarket/PlayerInfluencing */ 300);
/* harmony import */ var _StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 47);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__);
/* harmony import */ var _StockMarket_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./StockMarket/StockMarketHelpers */ 288);
/* harmony import */ var _StockMarket_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_52___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_52__);
/* harmony import */ var _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ./StockMarket/data/OrderTypes */ 111);
/* harmony import */ var _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__);
/* harmony import */ var _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ./StockMarket/data/PositionTypes */ 98);
/* harmony import */ var _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__);
/* harmony import */ var _StockMarket_data_StockSymbols__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ./StockMarket/data/StockSymbols */ 284);
/* harmony import */ var _StockMarket_data_StockSymbols__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_data_StockSymbols__WEBPACK_IMPORTED_MODULE_55__);
/* harmony import */ var _StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ./StockMarket/StockMarketCosts */ 245);
/* harmony import */ var _StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ./Terminal/DirectoryHelpers */ 86);
/* harmony import */ var _Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57__);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ./TextFile */ 137);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_58__);
/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ./NetscriptWorker */ 80);
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ./Netscript/killWorkerScript */ 70);
/* harmony import */ var _Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ./Netscript/WorkerScripts */ 112);
/* harmony import */ var _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(_Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_61__);
/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ./NetscriptEvaluator */ 68);
/* harmony import */ var _JSInterpreter__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ./JSInterpreter */ 447);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ./NetscriptPort */ 154);
/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_64___default = /*#__PURE__*/__webpack_require__.n(_NetscriptPort__WEBPACK_IMPORTED_MODULE_64__);
/* harmony import */ var _PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(/*! ./PersonObjects/Sleeve/SleeveTaskTypesEnum */ 242);
/* harmony import */ var _PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65__);
/* harmony import */ var _PersonObjects_Sleeve_SleeveHelpers__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(/*! ./PersonObjects/Sleeve/SleeveHelpers */ 521);
/* harmony import */ var _PersonObjects_Sleeve_SleeveHelpers__WEBPACK_IMPORTED_MODULE_66___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_SleeveHelpers__WEBPACK_IMPORTED_MODULE_66__);
/* harmony import */ var _Exploits_Exploit_ts__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(/*! ./Exploits/Exploit.ts */ 168);
/* harmony import */ var _Exploits_Exploit_ts__WEBPACK_IMPORTED_MODULE_67___default = /*#__PURE__*/__webpack_require__.n(_Exploits_Exploit_ts__WEBPACK_IMPORTED_MODULE_67__);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(/*! ./ui/numeralFormat */ 7);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(/*! ./ui/postToTerminal */ 8);
/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_69___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_69__);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70__);
/* harmony import */ var _utils_helpers_is2DArray__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(/*! ./utils/helpers/is2DArray */ 777);
/* harmony import */ var _utils_helpers_is2DArray__WEBPACK_IMPORTED_MODULE_71___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_is2DArray__WEBPACK_IMPORTED_MODULE_71__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(/*! ../utils/LogBox */ 151);
/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_73___default = /*#__PURE__*/__webpack_require__.n(_utils_LogBox__WEBPACK_IMPORTED_MODULE_73__);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 113);
/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(/*! ../utils/helpers/isString */ 72);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76__);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 129);
/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_77___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_77__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 90);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_78___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_78__);
const defaultInterpreter = new _JSInterpreter__WEBPACK_IMPORTED_MODULE_63__[/* Interpreter */ "a"]('', () => undefined);
// the acorn interpreter has a bug where it doesn't convert arrays correctly.
// so we have to more or less copy it here.
function toNative(pseudoObj) {
if(pseudoObj == null) return null;
if(!pseudoObj.hasOwnProperty('properties') ||
!pseudoObj.hasOwnProperty('getter') ||
!pseudoObj.hasOwnProperty('setter') ||
!pseudoObj.hasOwnProperty('proto')) {
return pseudoObj; // it wasn't a pseudo object anyway.
}
let nativeObj;
if (pseudoObj.hasOwnProperty('class') && pseudoObj.class === 'Array') {
nativeObj = [];
const length = defaultInterpreter.getProperty(pseudoObj, 'length');
for (let i = 0; i < length; i++) {
if (defaultInterpreter.hasProperty(pseudoObj, i)) {
nativeObj[i] =
toNative(defaultInterpreter.getProperty(pseudoObj, i));
}
}
} else { // Object.
nativeObj = {};
for (var key in pseudoObj.properties) {
const val = pseudoObj.properties[key];
nativeObj[key] = toNative(val);
}
}
return nativeObj;
}
function NetscriptFunctions(workerScript) {
const updateDynamicRam = function(fnName, ramCost) {
if (workerScript.dynamicLoadedFns[fnName]) { return; }
workerScript.dynamicLoadedFns[fnName] = true;
let 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_62__[/* makeRuntimeRejectMsg */ "b"])(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.
Please don't do that :(
" +
"Dynamic RAM Usage: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(workerScript.dynamicRamUsage) + " " +
"Static RAM Usage: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(workerScript.ramUsage));
}
};
/**
* Gets the Server for a specific hostname/ip, throwing an error
* if the server doesn't exist.
* @param {string} ip - Hostname or IP of the server
* @param {string} callingFnName - Name of calling function. For logging purposes
* @returns {Server} The specified Server
*/
const safeGetServer = function(ip, callingFnName="") {
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg(callingFnName, `Invalid IP/hostname: ${ip}`);
}
return server;
}
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} ip - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
const getRunningScript = function(fn, ip, callingFnName, scriptArgs) {
if (typeof callingFnName !== "string" || callingFnName === "") {
callingFnName = "getRunningScript";
}
if (!Array.isArray(scriptArgs)) {
throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* makeRuntimeRejectMsg */ "b"])(
workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${callingFnName}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (ip == null) { ip = workerScript.serverIp; }
const server = safeGetServer(ip, callingFnName);
return Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_41__[/* findRunningScript */ "a"])(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return workerScript.scriptRef;
}
const getRunningScriptByPid = function(pid, callingFnName) {
if (typeof callingFnName !== "string" || callingFnName === "") {
callingFnName = "getRunningScriptgetRunningScriptByPid";
}
for(const name of Object.keys(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AllServers"])) {
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AllServers"][name];
const runningScript = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_41__[/* findRunningScriptByPid */ "b"])(pid, server);
if (runningScript) return runningScript;
}
return null;
}
/**
* Helper function for getting the error log message when the user specifies
* a nonexistent running script
* @param {string} fn - Filename of script
* @param {string} ip - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {string} Error message to print to logs
*/
const getCannotFindRunningScriptErrorMessage = function(fn, ip, scriptArgs) {
if (!Array.isArray(scriptArgs)) {
scriptArgs = [];
}
return `Cannot find running script ${fn} on server ${ip} with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__["arrayToString"])(scriptArgs)}`;
}
/**
* Checks if the player has TIX API access. Throws an error if the player does not
*/
const checkTixApiAccess = function(callingFn="") {
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasWseAccount) {
throw makeRuntimeErrorMsg(callingFn, `You don't have WSE Access! Cannot use ${callingFn}()`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasTixApiAccess) {
throw makeRuntimeErrorMsg(callingFn, `You don't have TIX API Access! Cannot use ${callingFn}()`);
}
}
/**
* Gets a stock, given its symbol. Throws an error if the symbol is invalid
* @param {string} symbol - Stock's symbol
* @returns {Stock} stock object
*/
const getStockFromSymbol = function(symbol, callingFn="") {
const stock = _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["SymbolToStockMap"][symbol];
if (stock == null) {
throw makeRuntimeErrorMsg(callingFn, `Invalid stock symbol: '${symbol}'`);
}
return stock;
}
/**
* Used to fail a function if the function's target is a Hacknet Server.
* This is used for functions that should run on normal Servers, but not Hacknet Servers
* @param {Server} server - Target server
* @param {string} callingFn - Name of calling function. For logging purposes
* @returns {boolean} True if the server is a Hacknet Server, false otherwise
*/
const failOnHacknetServer = function(server, callingFn="") {
if (server instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_31__["HacknetServer"]) {
workerScript.log(callingFn, `Does not work on Hacknet Servers`);
return true;
} else {
return false;
}
}
// Utility function to get Hacknet Node object
const getHacknetNode = function(i, callingFn="") {
if (isNaN(i)) {
throw makeRuntimeErrorMsg(callingFn, "Invalid index specified for Hacknet Node: " + i);
}
if (i < 0 || i >= _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknetNodes.length) {
throw makeRuntimeErrorMsg(callingFn, "Index specified for Hacknet Node is out-of-bounds: " + i);
}
if (Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) {
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AllServers"][_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknetNodes[i]];
if (hserver == null) {
throw makeRuntimeErrorMsg(callingFn, `Could not get Hacknet Server for index ${i}. This is probably a bug, please report to game dev`);
}
return hserver;
} else {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknetNodes[i];
}
};
const makeRuntimeErrorMsg = function(caller, msg) {
const stack = (new Error()).stack.split('\n').slice(1);
const scripts = workerScript.getServer().scripts;
const userstack = [];
for(const stackline of stack) {
let filename;
for(const script of scripts) {
if (script.url && stackline.includes(script.url)) {
filename = script.filename;
}
for (const dependency of script.dependencies) {
if (stackline.includes(dependency.url)) {
filename = dependency.filename;
}
}
}
if(!filename) continue
function parseChromeStackline(line) {
const lineRe = /.*:(\d+):\d+.*/;
const funcRe = /.*at (.+) \(.*/;
const lineMatch = line.match(lineRe);
const funcMatch = line.match(funcRe);
if(lineMatch && funcMatch) {
return {line: lineMatch[1], func: funcMatch[1]};
}
return null;
}
let call = {line: "-1", func: "unknown"};
const chromeCall = parseChromeStackline(stackline);
if (chromeCall) {
call = chromeCall;
}
function parseFirefoxStackline(line) {
const lineRe = /.*:(\d+):\d+$/;
const lineMatch = line.match(lineRe);
const lio = line.lastIndexOf("@");
if(lineMatch && lio !== -1) {
return {line: lineMatch[1], func: line.slice(0, lio)};
}
return null;
}
let firefoxCall = parseFirefoxStackline(stackline);
if (firefoxCall) {
call = firefoxCall;
}
userstack.push(`${filename}:L${call.line}@${call.func}`);
}
workerScript.log(caller, msg);
let rejectMsg = `${caller}: ${msg}`
if(userstack.length !== 0) rejectMsg += `
Stack: ${userstack.join(' ')}`;
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* makeRuntimeRejectMsg */ "b"])(workerScript, rejectMsg);
}
const checkFormulasAccess = function(func, n) {
if ((_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][5] < 1 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 5) || (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][n] < 1 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== n)) {
let extra = '';
if (n !== 5) {
extra = ` and Source-File ${n}-1`;
}
throw makeRuntimeErrorMsg(`formulas.${func}`, `Requires Source-File 5-1${extra} to run.`);
}
}
const checkSingularityAccess = function(func, n) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 4) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][4] < n) {
throw makeRuntimeErrorMsg(func, `This singularity function requires Source-File 4-${n} to run.`);
}
}
}
const checkBladeburnerAccess = function(func, skipjoined=false) {
const apiAccess = (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN === 7 || _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sourceFiles.some(a=>{return a.n === 7}));
if (!apiAccess) {
const apiDenied = `You do not currently have access to the Bladeburner API. You must either be in BitNode-7 or have Source-File 7.`;
throw makeRuntimeErrorMsg(`bladeburner.${func}`, apiDenied);
}
if (!skipjoined) {
const bladeburnerAccess = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10__["Bladeburner"];
if(!bladeburnerAccess) {
const bladeburnerDenied = `You must be a member of the Bladeburner division to use this API.`;
throw makeRuntimeErrorMsg(`bladeburner.${func}`, bladeburnerDenied);
}
}
}
const checkBladeburnerCity = function(func, city) {
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.cities.hasOwnProperty(city)) {
throw makeRuntimeErrorMsg(`bladeburner.${func}`, `Invalid city: ${city}`);
}
}
const checkSleeveAPIAccess = function(func) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 10 && !_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][10]) {
throw makeRuntimeErrorMsg(`sleeve.${func}`, "You do not currently have access to the Sleeve API. This is either because you are not in BitNode-10 or because you do not have Source-File 10");
}
}
const checkSleeveNumber = function(func, sleeveNumber) {
if (sleeveNumber >= _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves.length || sleeveNumber < 0) {
const msg = `Invalid sleeve number: ${sleeveNumber}`;
workerScript.log(func, msg);
throw makeRuntimeErrorMsg(`sleeve.${func}`, msg);
}
}
const getCodingContract = function(func, ip, fn) {
const server = safeGetServer(ip, func);
const contract = server.getContract(fn);
if (contract == null) {
throw makeRuntimeErrorMsg(`codingcontract.${func}`, `Cannot find contract '${fn}' on server '${ip}'`)
}
return contract;
}
const checkGangApiAccess = function(func) {
const hasAccess = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang instanceof _Gang_Gang__WEBPACK_IMPORTED_MODULE_19__["Gang"];
if (!hasAccess) {
throw makeRuntimeErrorMsg(`gang.${func}`, `You do not currently have a Gang`);
}
}
const getGangMember = function(func, name) {
for (const member of _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.members)
if (member.name === name)
return member;
throw makeRuntimeErrorMsg(`gang.${func}`, `Invalid gang member: '${name}'`)
}
const getGangTask = function(func, name) {
const task = _Gang_GangMemberTasks__WEBPACK_IMPORTED_MODULE_21__["GangMemberTasks"][name];
if (!task) {
throw makeRuntimeErrorMsg(`gang.${func}`, `Invalid task: '${name}'`);
}
return task;
}
const getBladeburnerActionObject = function(func, type, name) {
const actionId = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getActionIdFromTypeAndName(type, name)
if (!actionId) {
throw makeRuntimeErrorMsg(`bladeburner.${func}`, `Invalid action type='${type}', name='${name}'`);
}
const actionObj = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getActionObject(actionId);
if (!actionObj) {
throw makeRuntimeErrorMsg(`bladeburner.${func}`, `Invalid action type='${type}', name='${name}'`);
}
return actionObj;
}
const getCompany = function(func, name) {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_12__["Companies"][name];
if (company == null || !(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_11__["Company"])) {
throw makeRuntimeErrorMsg(func, `Invalid company name: '${name}'`)
}
return company;
}
const getFaction = function(func, name) {
if (!Object(_Faction_Factions__WEBPACK_IMPORTED_MODULE_23__["factionExists"])(name)) {
throw makeRuntimeErrorMsg(func, `Invalid faction name: '${name}`)
}
return _Faction_Factions__WEBPACK_IMPORTED_MODULE_23__["Factions"][name];
}
const getAugmentation = function(func, name) {
if (!Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_5__[/* augmentationExists */ "b"])(name)) {
throw makeRuntimeErrorMsg(func, `Invalid augmentation: '${name}'`);
}
return _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"][name];
}
const runAfterReset = function(cbScript=null) {
//Run a script after reset
if (cbScript && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(cbScript)) {
const home = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer();
for (const script of home.scripts) {
if (script.filename === cbScript) {
const ramUsage = script.ramUsage;
const ramAvailable = home.maxRam - home.ramUsed;
if (ramUsage > ramAvailable) {
return; // Not enough RAM
}
const runningScriptObj = new _Script_RunningScript__WEBPACK_IMPORTED_MODULE_44__["RunningScript"](script, []); // No args
runningScriptObj.threads = 1; // Only 1 thread
Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* startWorkerScript */ "e"])(runningScriptObj, home);
}
}
}
}
const hack = function(ip, manual, { threads: requestedThreads, stock } = {}) {
if (ip === undefined) {
throw makeRuntimeErrorMsg("hack", "Takes 1 argument.");
}
const threads = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* resolveNetscriptRequestedThreads */ "d"])(workerScript, "hack", requestedThreads);
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("hack", `Invalid IP/hostname: ${ip}.`);
}
// Calculate the hacking time
var hackingTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]); // This is in seconds
// No root access or skill level too low
const canHack = Object(_Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__["netscriptCanHack"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
if (!canHack.res) {
throw makeRuntimeErrorMsg('hack', canHack.msg);
}
workerScript.log("hack", `Executing ${ip} in ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__["convertTimeMsToTimeElapsedString"])(hackingTime*1000, true)} (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)})`);
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* netscriptDelay */ "c"])(hackingTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingChance"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
var rand = Math.random();
var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingExpGain"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]) * threads;
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { // Success!
const percentHacked = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculatePercentMoneyHacked"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
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 moneyDrained = Math.floor(server.moneyAvailable * percentHacked) * threads;
// Over-the-top safety checks
if (moneyDrained <= 0) {
moneyDrained = 0;
expGainedOnSuccess = expGainedOnFailure;
}
if (moneyDrained > server.moneyAvailable) {moneyDrained = server.moneyAvailable;}
server.moneyAvailable -= moneyDrained;
if (server.moneyAvailable < 0) {server.moneyAvailable = 0;}
const moneyGained = moneyDrained * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__["BitNodeMultipliers"].ScriptHackMoneyGain;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainMoney(moneyGained);
workerScript.scriptRef.onlineMoneyMade += moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].scriptProdSinceLastAug += moneyGained;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].recordMoneySource(moneyGained, "hacking");
workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainHackingExp(expGainedOnSuccess);
workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
workerScript.log("hack", `Successfully hacked '${server.hostname}' for ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(moneyGained)} and ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatExp(expGainedOnSuccess)} exp (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)})`);
server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
if (stock) {
Object(_StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_50__["influenceStockThroughServerHack"])(server, moneyGained);
}
if(manual) {
server.backdoorInstalled = true;
}
return Promise.resolve(moneyGained);
} else {
// Player only gains 25% exp for failure?
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainHackingExp(expGainedOnFailure);
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
workerScript.log("hack", `Failed to hack '${server.hostname}'. Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatExp(expGainedOnFailure)} exp (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)})`);
return Promise.resolve(0);
}
});
}
const argsToString = function(args) {
let out = '';
for(let arg of args) {
arg = toNative(arg);
if(typeof arg === 'object') {
out += JSON.stringify(arg);
continue
}
out += `${arg}`;
}
return out;
}
const functions = {
hacknet : {
numNodes : function() {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknetNodes.length;
},
maxNumNodes : function() {
if (Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) {
return _Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30__["HacknetServerConstants"].MaxServers;
}
return Infinity;
},
purchaseNode : function() {
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseHacknet */ "m"])();
},
getPurchaseNodeCost : function() {
if (Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) {
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* getCostOfNextHacknetServer */ "c"])();
} else {
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* getCostOfNextHacknetNode */ "b"])();
}
},
getNodeStats : function(i) {
const node = getHacknetNode(i, "getNodeStats");
const hasUpgraded = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])();
const res = {
name: hasUpgraded ? node.hostname : node.name,
level: node.level,
ram: hasUpgraded ? node.maxRam : node.ram,
cores: node.cores,
production: hasUpgraded ? node.hashRate : node.moneyGainRatePerSecond,
timeOnline: node.onlineTimeSeconds,
totalProduction: hasUpgraded ? node.totalHashesGenerated : node.totalMoneyGenerated,
};
if (hasUpgraded) {
res.cache = node.cache;
res.hashCapacity = node.hashCapacity;
}
return res;
},
upgradeLevel : function(i, n) {
const node = getHacknetNode(i, "upgradeLevel");
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseLevelUpgrade */ "o"])(node, n);
},
upgradeRam : function(i, n) {
const node = getHacknetNode(i, "upgradeRam");
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseRamUpgrade */ "p"])(node, n);
},
upgradeCore : function(i, n) {
const node = getHacknetNode(i, "upgradeCore");
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseCoreUpgrade */ "l"])(node, n);
},
upgradeCache : function(i, n) {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return false; }
const node = getHacknetNode(i, "upgradeCache");
const res = Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseCacheUpgrade */ "k"])(node, n);
if (res) {
Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* updateHashManagerCapacity */ "r"])();
}
return res;
},
getLevelUpgradeCost : function(i, n) {
const node = getHacknetNode(i, "upgradeLevel");
return node.calculateLevelUpgradeCost(n, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_level_cost_mult);
},
getRamUpgradeCost : function(i, n) {
const node = getHacknetNode(i, "upgradeRam");
return node.calculateRamUpgradeCost(n, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_ram_cost_mult);
},
getCoreUpgradeCost : function(i, n) {
const node = getHacknetNode(i, "upgradeCore");
return node.calculateCoreUpgradeCost(n, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_core_cost_mult);
},
getCacheUpgradeCost : function(i, n) {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return Infinity; }
const node = getHacknetNode(i, "upgradeCache");
return node.calculateCacheUpgradeCost(n);
},
numHashes : function() {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return 0; }
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.hashes;
},
hashCapacity: function() {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return 0; }
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.capacity;
},
hashCost : function(upgName) {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return Infinity; }
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.getUpgradeCost(upgName);
},
spendHashes : function(upgName, upgTarget) {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return false; }
return Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* purchaseHashUpgrade */ "n"])(upgName, upgTarget);
},
getHashUpgradeLevel : function(upgName) {
const level = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.upgrades[upgName];
if(level === undefined) {
throw makeRuntimeErrorMsg("hacknet.hashUpgradeLevel", `Invalid Hash Upgrade: ${upgName}`);
}
return level;
},
getStudyMult : function() {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return false; }
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.getStudyMult();
},
getTrainingMult : function() {
if (!Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_27__[/* hasHacknetServers */ "h"])()) { return false; }
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.getTrainingMult();
},
},
sprintf : sprintf_js__WEBPACK_IMPORTED_MODULE_0__["sprintf"],
vsprintf: sprintf_js__WEBPACK_IMPORTED_MODULE_0__["vsprintf"],
scan : function(ip=workerScript.serverIp, hostnames=true) {
updateDynamicRam("scan", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("scan"));
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg('scan', `Invalid IP/hostname: ${ip}.`);
}
var out = [];
for (var i = 0; i < server.serversOnNetwork.length; i++) {
var entry;
if (hostnames) {
entry = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServerOnNetwork"])(server, i).hostname;
} else {
entry = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServerOnNetwork"])(server, i).ip;
}
if (entry == null) {
continue;
}
out.push(entry);
}
workerScript.log("scan", `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
return out;
},
hack : function(ip, { threads: requestedThreads, stock } = {}){
updateDynamicRam("hack", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hack"));
return hack(ip, false, {threads: requestedThreads, stock: stock});
},
hackAnalyzeThreads : function(ip, hackAmount) {
updateDynamicRam("hackAnalyzeThreads", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hackAnalyzeThreads"));
// Check argument validity
const server = safeGetServer(ip, 'hackAnalyzeThreads');
if (isNaN(hackAmount)) {
throw makeRuntimeErrorMsg(workerScript, `Invalid growth argument passed into hackAnalyzeThreads: ${hackAmount}. Must be numeric.`);
}
if (hackAmount < 0 || hackAmount > server.moneyAvailable) {
return -1;
}
const percentHacked = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculatePercentMoneyHacked"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
return hackAmount / Math.floor(server.moneyAvailable * percentHacked);
},
hackAnalyzePercent : function(ip) {
updateDynamicRam("hackAnalyzePercent", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hackAnalyzePercent"));
const server = safeGetServer(ip, 'hackAnalyzePercent');
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculatePercentMoneyHacked"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]) * 100;
},
hackChance : function(ip) {
updateDynamicRam("hackChance", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hackChance"));
const server = safeGetServer(ip, 'hackChance');
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingChance"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
},
sleep : function(time){
if (time === undefined) {
throw makeRuntimeErrorMsg("sleep", "Takes 1 argument.");
}
workerScript.log("sleep", `Sleeping for ${time} milliseconds`);
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* netscriptDelay */ "c"])(time, workerScript).then(function() {
return Promise.resolve(true);
});
},
grow : function(ip, { threads: requestedThreads, stock } = {}){
updateDynamicRam("grow", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("grow"));
const threads = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* resolveNetscriptRequestedThreads */ "d"])(workerScript, "grow", requestedThreads);
if (ip === undefined) {
throw makeRuntimeErrorMsg("grow", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("grow", `Invalid IP/hostname: ${ip}.`);
}
const host = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
// No root access or skill level too low
const canHack = Object(_Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__["netscriptCanGrow"])(server);
if (!canHack.res) {
throw makeRuntimeErrorMsg("grow", canHack.msg);
}
var growTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateGrowTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
workerScript.log("grow", `Executing on '${server.hostname}' in ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__["convertTimeMsToTimeElapsedString"])(growTime*1000, true)} (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)}).`);
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* netscriptDelay */ "c"])(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
Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["processSingleServerGrowth"])(server, threads, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"], host.cpuCores);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.ip, threads);
var expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingExpGain"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]) * threads;
const logGrowPercent = (moneyAfter/moneyBefore) - 1;
workerScript.log("grow", `Available money on '${server.hostname}' grown by ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatPercentage(logGrowPercent, 6)}. Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatExp(expGain)} hacking exp (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)}).`);
workerScript.scriptRef.onlineExpGained += expGain;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainHackingExp(expGain);
if (stock) {
Object(_StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_50__["influenceStockThroughServerGrow"])(server, moneyAfter - moneyBefore);
}
return Promise.resolve(moneyAfter/moneyBefore);
});
},
growthAnalyze : function(ip, growth) {
updateDynamicRam("growthAnalyze", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("growthAnalyze"));
// Check argument validity
const server = safeGetServer(ip, 'growthAnalyze');
if (typeof growth !== "number" || isNaN(growth) || growth < 1 || !isFinite(growth)) {
throw makeRuntimeErrorMsg("growthAnalyze", `Invalid argument: growth must be numeric and >= 1, is ${growth}.`);
}
return Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["numCycleForGrowth"])(server, Number(growth), _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
},
weaken : function(ip, { threads: requestedThreads } = {}) {
updateDynamicRam("weaken", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("weaken"));
var threads = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* resolveNetscriptRequestedThreads */ "d"])(workerScript, "weaken", requestedThreads)
if (ip === undefined) {
throw makeRuntimeErrorMsg("weaken", "Takes 1 argument.");
}
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("weaken", `Invalid IP/hostname: ${ip}`);
}
// No root access or skill level too low
const canHack = Object(_Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__["netscriptCanWeaken"])(server);
if (!canHack.res) {
throw makeRuntimeErrorMsg("weaken", canHack.msg);
}
const weakenTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateWeakenTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
workerScript.log("weaken", `Executing on '${server.hostname}' in ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__["convertTimeMsToTimeElapsedString"])(weakenTime*1000, true)} (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)})`);
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* netscriptDelay */ "c"])(weakenTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) return Promise.reject(workerScript);
const host = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
const coreBonus = 1+(host.cpuCores-1)/16;
server.weaken(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ServerWeakenAmount * threads * coreBonus);
workerScript.scriptRef.recordWeaken(server.ip, threads);
const expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingExpGain"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]) * threads;
workerScript.log("weaken", `'${server.hostname}' security level weakened to ${server.hackDifficulty}. Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatExp(expGain)} hacking exp (t=${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatThreads(threads)})`);
workerScript.scriptRef.onlineExpGained += expGain;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainHackingExp(expGain);
return Promise.resolve(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ServerWeakenAmount * threads);
});
},
print: function(){
if (arguments.length === 0) {
throw makeRuntimeErrorMsg("print", "Takes at least 1 argument.");
}
workerScript.print(argsToString(arguments));
},
tprint: function() {
if (arguments.length === 0) {
throw makeRuntimeErrorMsg("tprint", "Takes at least 1 argument.");
}
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_69__["post"])(`${workerScript.scriptRef.filename}: ${argsToString(arguments)}`);
},
tprintf: function(format, ...args) {
Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_69__["post"])(Object(sprintf_js__WEBPACK_IMPORTED_MODULE_0__["vsprintf"])(format, args));
},
clearLog: function() {
workerScript.scriptRef.clearLog();
},
disableLog: function(fn) {
if (possibleLogs[fn]===undefined) {
throw makeRuntimeErrorMsg("disableLog", `Invalid argument: ${fn}.`);
}
workerScript.disableLogs[fn] = true;
workerScript.log("disableLog", `Disabled logging for ${fn}`);
},
enableLog: function(fn) {
if (possibleLogs[fn]===undefined) {
throw makeRuntimeErrorMsg("enableLog", `Invalid argument: ${fn}.`);
}
delete workerScript.disableLogs[fn];
workerScript.log("enableLog", `Enabled logging for ${fn}`);
},
isLogEnabled : function(fn) {
if (possibleLogs[fn] === undefined) {
throw makeRuntimeErrorMsg("isLogEnabled", `Invalid argument: ${fn}.`);
}
return workerScript.disableLogs[fn] ? false : true;
},
getScriptLogs: function(fn, ip, ...scriptArgs) {
const runningScriptObj = getRunningScript(fn, ip, "getScriptLogs", scriptArgs);
if (runningScriptObj == null) {
workerScript.log("getScriptLogs", getCannotFindRunningScriptErrorMessage(fn, ip, scriptArgs));
return "";
}
return runningScriptObj.logs.slice();
},
tail: function(fn, ip=workerScript.serverIp, ...scriptArgs) {
let runningScriptObj;
if(arguments.length === 0) {
runningScriptObj = workerScript.scriptRef;
} else if(typeof fn === 'number') {
runningScriptObj = getRunningScriptByPid(fn, 'tail');
} else {
runningScriptObj = getRunningScript(fn, ip, "tail", scriptArgs);
}
if (runningScriptObj == null) {
workerScript.log("tail", getCannotFindRunningScriptErrorMessage(fn, ip, scriptArgs));
return;
}
Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_73__["logBoxCreate"])(runningScriptObj);
},
nuke: function(ip){
updateDynamicRam("nuke", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("nuke"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("nuke", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("nuke", `Invalid IP/hostname: ${ip}.`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].NukeProgram.name)) {
throw makeRuntimeErrorMsg("nuke", "You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw makeRuntimeErrorMsg("nuke", "Not enough ports opened to use NUKE.exe virus.");
}
if (server.hasAdminRights) {
workerScript.log("nuke", `Already have root access to '${server.hostname}'.`);
} else {
server.hasAdminRights = true;
workerScript.log("nuke", `Executed NUKE.exe virus on '${server.hostname}' to gain root access.`);
}
return true;
},
brutessh: function(ip){
updateDynamicRam("brutessh", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("brutessh"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("brutessh", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("brutessh", `Invalid IP/hostname: ${ip}.`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].BruteSSHProgram.name)) {
throw makeRuntimeErrorMsg("brutessh", "You do not have the BruteSSH.exe program!");
}
if (!server.sshPortOpen) {
workerScript.log("brutessh", `Executed BruteSSH.exe on '${server.hostname}' to open SSH port (22).`);
server.sshPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("brutessh", `SSH Port (22) already opened on '${server.hostname}'.`);
}
return true;
},
ftpcrack: function(ip) {
updateDynamicRam("ftpcrack", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("ftpcrack"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("ftpcrack", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("ftpcrack", `Invalid IP/hostname: ${ip}.`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].FTPCrackProgram.name)) {
throw makeRuntimeErrorMsg("ftpcrack", "You do not have the FTPCrack.exe program!");
}
if (!server.ftpPortOpen) {
workerScript.log("ftpcrack", `Executed FTPCrack.exe on '${server.hostname}' to open FTP port (21).`);
server.ftpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("ftpcrack", `FTP Port (21) already opened on '${server.hostname}'.`);
}
return true;
},
relaysmtp: function(ip) {
updateDynamicRam("relaysmtp", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("relaysmtp"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("relaysmtp", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("relaysmtp", `Invalid IP/hostname: ${ip}.`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].RelaySMTPProgram.name)) {
throw makeRuntimeErrorMsg("relaysmtp", "You do not have the relaySMTP.exe program!");
}
if (!server.smtpPortOpen) {
workerScript.log("relaysmtp", `Executed relaySMTP.exe on '${server.hostname}' to open SMTP port (25).`);
server.smtpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("relaysmtp", `SMTP Port (25) already opened on '${server.hostname}'.`);
}
return true;
},
httpworm: function(ip) {
updateDynamicRam("httpworm", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("httpworm"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("httpworm", "Takes 1 argument");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("httpworm", `Invalid IP/hostname: ${ip}`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].HTTPWormProgram.name)) {
throw makeRuntimeErrorMsg("httpworm", "You do not have the HTTPWorm.exe program!");
}
if (!server.httpPortOpen) {
workerScript.log("httpworm", `Executed HTTPWorm.exe on '${server.hostname}' to open HTTP port (80).`);
server.httpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("httpworm", `HTTP Port (80) already opened on '${server.hostname}'.`);
}
return true;
},
sqlinject: function(ip) {
updateDynamicRam("sqlinject", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sqlinject"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("sqlinject", "Takes 1 argument.");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("sqlinject", `Invalid IP/hostname: ${ip}`);
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"].SQLInjectProgram.name)) {
throw makeRuntimeErrorMsg("sqlinject", "You do not have the SQLInject.exe program!");
}
if (!server.sqlPortOpen) {
workerScript.log("sqlinject", `Executed SQLInject.exe on '${server.hostname}' to open SQL port (1433).`);
server.sqlPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("sqlinject", `SQL Port (1433) already opened on '${server.hostname}'.`);
}
return true;
},
run: function(scriptname, threads=1) {
updateDynamicRam("run", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("run"));
if (scriptname === undefined) {
throw makeRuntimeErrorMsg("run", "Usage: run(scriptname, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("run", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
var argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var scriptServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw makeRuntimeErrorMsg("run", "Could not find server. This is a bug. Report to dev.");
}
return Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* runScriptFromScript */ "d"])("run", scriptServer, scriptname, argsForNewScript, workerScript, threads);
},
exec: function(scriptname, ip, threads = 1) {
updateDynamicRam("exec", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("exec"));
if (scriptname === undefined || ip === undefined) {
throw makeRuntimeErrorMsg("exec", "Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("exec", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
var argsForNewScript = [];
for (var i = 3; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("exec", `Invalid IP/hostname: ${ip}`);
}
return Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* runScriptFromScript */ "d"])("exec", server, scriptname, argsForNewScript, workerScript, threads);
},
spawn: function(scriptname, threads) {
updateDynamicRam("spawn", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("spawn"));
if (!scriptname || !threads) {
throw makeRuntimeErrorMsg("spawn", "Usage: spawn(scriptname, threads)");
}
const spawnDelay = 10;
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70__["setTimeoutRef"])(() => {
if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("spawn", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
var argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]);
}
var scriptServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw makeRuntimeErrorMsg("spawn", "Could not find server. This is a bug. Report to dev");
}
return Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* runScriptFromScript */ "d"])("spawn", scriptServer, scriptname, argsForNewScript, workerScript, threads);
}, spawnDelay * 1e3);
workerScript.log("spawn", `Will execute '${scriptname}' in ${spawnDelay} seconds`);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(workerScript)) {
workerScript.log("spawn", "Exiting...");
}
},
kill: function(filename, ip, ...scriptArgs) {
updateDynamicRam("kill", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("kill"));
let res;
const killByPid = (typeof filename === "number");
if (killByPid) {
// Kill by pid
res = Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(filename);
} else {
// Kill by filename/ip
if (filename === undefined || ip === undefined) {
throw makeRuntimeErrorMsg("kill", "Usage: kill(scriptname, server, [arg1], [arg2]...)");
}
const server = safeGetServer(ip);
const runningScriptObj = getRunningScript(filename, ip, "kill", scriptArgs);
if (runningScriptObj == null) {
workerScript.log("kill", getCannotFindRunningScriptErrorMessage(filename, ip, scriptArgs));
return false;
}
res = Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(runningScriptObj, server.ip);
}
if (res) {
if (killByPid) {
workerScript.log("kill", `Killing script with PID ${filename}`);
} else {
workerScript.log("kill", `Killing '${filename}' on '${ip}' with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__["arrayToString"])(scriptArgs)}.`);
}
return true;
} else {
if (killByPid) {
workerScript.log("kill", `No script with PID ${filename}`);
} else {
workerScript.log("kill", `No such script '${filename}' on '${ip}' with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__["arrayToString"])(scriptArgs)}`);
}
return false;
}
},
killall: function(ip=workerScript.serverIp) {
updateDynamicRam("killall", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("killall"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("killall", "Takes 1 argument");
}
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("killall", `Invalid IP/hostname: ${ip}`);
}
const scriptsRunning = (server.runningScripts.length > 0);
for (let i = server.runningScripts.length-1; i >= 0; --i) {
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(server.runningScripts[i], server.ip, false);
}
_Netscript_WorkerScriptStartStopEventEmitter__WEBPACK_IMPORTED_MODULE_3__["WorkerScriptStartStopEventEmitter"].emitEvent();
workerScript.log("killall", `Killing all scripts on '${server.hostname}'. May take a few minutes for the scripts to die.`);
return scriptsRunning;
},
exit : function() {
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(workerScript)) {
workerScript.log("exit", "Exiting...");
} else {
workerScript.log("exit", "Failed. This is a bug. Report to dev.");
}
},
scp: function(scriptname, ip1, ip2) {
updateDynamicRam("scp", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("scp"));
if (arguments.length !== 2 && arguments.length !== 3) {
throw makeRuntimeErrorMsg("scp", "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;
}
// Invalid file type
if (!Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57__["isValidFilePath"])(scriptname)) {
throw makeRuntimeErrorMsg("scp", `Invalid filename: '${scriptname}'`);
}
// Invalid file name
if (!scriptname.endsWith(".lit") && !Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__["isScriptFilename"])(scriptname) && !scriptname.endsWith("txt")) {
throw makeRuntimeErrorMsg("scp", "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 makeRuntimeErrorMsg("scp", "Takes 2 or 3 arguments");
}
destServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip2);
if (destServer == null) {
throw makeRuntimeErrorMsg("scp", `Invalid IP/hostname: ${ip2}`);
}
currServ = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip1);
if (currServ == null) {
throw makeRuntimeErrorMsg("scp", `Invalid IP/hostname: ${ip1}`);
}
} else if (ip1 != null) { // 2 Argument version: scriptname, destination
if (scriptname === undefined || ip1 === undefined) {
throw makeRuntimeErrorMsg("scp", "Takes 2 or 3 arguments");
}
destServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip1);
if (destServer == null) {
throw makeRuntimeErrorMsg("scp", `Invalid IP/hostname: ${ip1}`);
}
currServ = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (currServ == null) {
throw makeRuntimeErrorMsg("scp", "Could not find server ip for this script. This is a bug. Report to dev.");
}
} else {
throw makeRuntimeErrorMsg("scp", "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_Message__WEBPACK_IMPORTED_MODULE_36__["Message"]) && currServ.messages[i] == scriptname) {
found = true;
break;
}
}
if (!found) {
workerScript.log("scp", `File '${scriptname}' does not exist.`);
return false;
}
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
return true; // Already exists
}
}
destServer.messages.push(scriptname);
workerScript.log("scp", `File '${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.log("scp", `File '${scriptname}' does not exist.`);
return false;
}
for (var i = 0; i < destServer.textFiles.length; ++i) {
if (destServer.textFiles[i].fn === scriptname) {
// Overwrite
destServer.textFiles[i].text = txtFile.text;
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
return true;
}
}
var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_58__["TextFile"](txtFile.fn, txtFile.text);
destServer.textFiles.push(newFile);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
return true;
}
// Scp for script files
let sourceScript = null;
for (let i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
sourceScript = currServ.scripts[i];
break;
}
}
if (sourceScript == null) {
workerScript.log("scp", `File '${scriptname}' does not exist.`);
return false;
}
// Overwrite script if it already exists
for (let i = 0; i < destServer.scripts.length; ++i) {
if (scriptname == destServer.scripts[i].filename) {
workerScript.log("scp", `WARNING: File '${scriptname}' overwritten on '${destServer.hostname}'`);
const oldScript = destServer.scripts[i];
// If it's the exact same file don't actually perform the
// copy to avoid recompiling uselessly. Players tend to scp
// liberally.
if(oldScript.code === sourceScript.code)
return true;
oldScript.code = sourceScript.code;
oldScript.ramUsage = sourceScript.ramUsage;
oldScript.markUpdated();
return true;
}
}
// Create new script if it does not already exist
const newScript = new _Script_Script__WEBPACK_IMPORTED_MODULE_40__["Script"](scriptname);
newScript.code = sourceScript.code;
newScript.ramUsage = sourceScript.ramUsage;
newScript.server = destServer.ip;
destServer.scripts.push(newScript);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
return true;
},
ls: function(ip, grep) {
updateDynamicRam("ls", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("ls"));
if (ip === undefined) {
throw makeRuntimeErrorMsg("ls", "Usage: ls(ip/hostname, [grep filter])");
}
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("ls", `Invalid IP/hostname: ${ip}`);
}
// Get the grep filter, if one exists
let filter = false;
if (arguments.length >= 2) {
filter = grep.toString();
}
const allFiles = [];
for (let 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 (let 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 (let i = 0; i < server.messages.length; i++) {
if (filter) {
if (server.messages[i] instanceof _Message_Message__WEBPACK_IMPORTED_MODULE_36__["Message"]) {
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_Message__WEBPACK_IMPORTED_MODULE_36__["Message"]) {
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) {
updateDynamicRam("ps", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("ps"));
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null){
throw makeRuntimeErrorMsg("ps", `Invalid IP/hostname: ${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(),
pid: script.pid,
})
}
return processes;
},
hasRootAccess: function(ip) {
updateDynamicRam("hasRootAccess", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hasRootAccess"));
if (ip===undefined){
throw makeRuntimeErrorMsg("hasRootAccess", "Takes 1 argument");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null){
throw makeRuntimeErrorMsg("hasRootAccess", `Invalid IP/hostname: ${ip}`);
}
return server.hasAdminRights;
},
getIp: function() {
updateDynamicRam("getIp", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getIp"));
var scriptServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw makeRuntimeErrorMsg("getIp", "Could not find server. This is a bug. Report to dev.");
}
return scriptServer.ip;
},
getHostname: function() {
updateDynamicRam("getHostname", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getHostname"));
var scriptServer = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw makeRuntimeErrorMsg(workerScript, "Could not find server. This is a bug. Report to dev.");
}
return scriptServer.hostname;
},
getHackingLevel: function() {
updateDynamicRam("getHackingLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getHackingLevel"));
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].updateSkillLevels();
workerScript.log("getHackingLevel", `returned ${_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_skill}`);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_skill;
},
getHackingMultipliers: function() {
updateDynamicRam("getHackingMultipliers", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getHackingMultipliers"));
return {
chance: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_chance_mult,
speed: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_speed_mult,
money: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_money_mult,
growth: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_grow_mult,
};
},
getHacknetMultipliers: function() {
updateDynamicRam("getHacknetMultipliers", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getHacknetMultipliers"));
return {
production: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_money_mult,
purchaseCost: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_purchase_cost_mult,
ramCost: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_ram_cost_mult,
coreCost: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_core_cost_mult,
levelCost: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_level_cost_mult,
};
},
getBitNodeMultipliers: function() {
updateDynamicRam("getBitNodeMultipliers", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getBitNodeMultipliers"));
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][5] <= 0 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 5) {
throw makeRuntimeErrorMsg("getBitNodeMultipliers", "Requires Source-File 5 to run.");
}
let copy = Object.assign({}, _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__["BitNodeMultipliers"]);
return copy;
},
getServer: function(ip) {
updateDynamicRam("getServer", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServer"));
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][5] <= 0 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 5) {
throw makeRuntimeErrorMsg("getServer", "Requires Source-File 5 to run.");
}
const server = safeGetServer(ip, "getServer");
const copy = Object.assign({}, server);
// These fields should be hidden.
copy.contracts = undefined;
copy.messages = undefined;
copy.runningScripts = undefined;
copy.scripts = undefined;
copy.textFiles = undefined;
copy.programs = undefined;
copy.serversOnNetwork = undefined;
return copy;
},
getServerMoneyAvailable: function(ip) {
updateDynamicRam("getServerMoneyAvailable", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerMoneyAvailable"));
const server = safeGetServer(ip, "getServerMoneyAvailable");
if (failOnHacknetServer(server, "getServerMoneyAvailable")) { return 0; }
if (server.hostname == "home") {
// Return player's money
workerScript.log("getServerMoneyAvailable", `returned player's money: ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.toNumber())}`);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.toNumber();
}
workerScript.log("getServerMoneyAvailable", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(server.moneyAvailable)} for '${server.hostname}'`);
return server.moneyAvailable;
},
getServerSecurityLevel: function(ip) {
updateDynamicRam("getServerSecurityLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerSecurityLevel"));
const server = safeGetServer(ip, "getServerSecurityLevel");
if (failOnHacknetServer(server, "getServerSecurityLevel")) { return 1; }
workerScript.log("getServerSecurityLevel", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatServerSecurity(server.hackDifficulty, 3)} for '${server.hostname}'`);
return server.hackDifficulty;
},
getServerBaseSecurityLevel: function(ip) {
updateDynamicRam("getServerBaseSecurityLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerBaseSecurityLevel"));
const server = safeGetServer(ip, "getServerBaseSecurityLevel");
if (failOnHacknetServer(server, "getServerBaseSecurityLevel")) { return 1; }
workerScript.log("getServerBaseSecurityLevel", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatServerSecurity(server.baseDifficulty, 3)} for '${server.hostname}'`);
return server.baseDifficulty;
},
getServerMinSecurityLevel: function(ip) {
updateDynamicRam("getServerMinSecurityLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerMinSecurityLevel"));
const server = safeGetServer(ip, "getServerMinSecurityLevel");
if (failOnHacknetServer(server, "getServerMinSecurityLevel")) { return 1; }
workerScript.log("getServerMinSecurityLevel", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatServerSecurity(server.minDifficulty, 3)} for ${server.hostname}`);
return server.minDifficulty;
},
getServerRequiredHackingLevel: function(ip) {
updateDynamicRam("getServerRequiredHackingLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerRequiredHackingLevel"));
const server = safeGetServer(ip, "getServerRequiredHackingLevel");
if (failOnHacknetServer(server, "getServerRequiredHackingLevel")) { return 1; }
workerScript.log("getServerRequiredHackingLevel", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatSkill(server.requiredHackingSkill, 0)} for '${server.hostname}'`);
return server.requiredHackingSkill;
},
getServerMaxMoney: function(ip) {
updateDynamicRam("getServerMaxMoney", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerMaxMoney"));
const server = safeGetServer(ip, "getServerMaxMoney");
if (failOnHacknetServer(server, "getServerMaxMoney")) { return 0; }
workerScript.log("getServerMaxMoney", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(server.moneyMax)} for '${server.hostname}'`);
return server.moneyMax;
},
getServerGrowth: function(ip) {
updateDynamicRam("getServerGrowth", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerGrowth"));
const server = safeGetServer(ip, "getServerGrowth");
if (failOnHacknetServer(server, "getServerGrowth")) { return 1; }
workerScript.log("getServerGrowth", `returned ${server.serverGrowth} for '${server.hostname}'`);
return server.serverGrowth;
},
getServerNumPortsRequired: function(ip) {
updateDynamicRam("getServerNumPortsRequired", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerNumPortsRequired"));
const server = safeGetServer(ip, "getServerNumPortsRequired");
if (failOnHacknetServer(server, "getServerNumPortsRequired")) { return 5; }
workerScript.log("getServerNumPortsRequired", `returned ${server.numOpenPortsRequired} for '${server.hostname}'`);
return server.numOpenPortsRequired;
},
getServerRam: function(ip) {
updateDynamicRam("getServerRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerRam"));
const server = safeGetServer(ip, "getServerRam");
workerScript.log("getServerRam", `returned [${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(server.maxRam, 2)}, ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(server.ramUsed, 2)}]`);
return [server.maxRam, server.ramUsed];
},
getServerMaxRam: function(ip) {
updateDynamicRam("getServerMaxRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerMaxRam"));
const server = safeGetServer(ip, "getServerMaxRam");
workerScript.log("getServerMaxRam", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(server.maxRam, 2)}`);
return server.maxRam;
},
getServerUsedRam: function(ip) {
updateDynamicRam("getServerUsedRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getServerUsedRam"));
const server = safeGetServer(ip, "getServerUsedRam");
workerScript.log("getServerUsedRam", `returned ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatRAM(server.ramUsed, 2)}`);
return server.ramUsed;
},
serverExists: function(ip) {
updateDynamicRam("serverExists", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("serverExists"));
return (Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip) !== null);
},
fileExists: function(filename,ip=workerScript.serverIp) {
updateDynamicRam("fileExists", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("fileExists"));
if (filename === undefined) {
throw makeRuntimeErrorMsg("fileExists", "Usage: fileExists(scriptname, [server])");
}
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("fileExists", `Invalid IP/hostname: ${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_Message__WEBPACK_IMPORTED_MODULE_36__["Message"]) &&
filename.toLowerCase() === server.messages[i]) {
return true;
}
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_58__["getTextFile"])(filename, server);
if (txtFile != null) {
return true;
}
return false;
},
isRunning: function(fn, ip=workerScript.serverIp, ...scriptArgs) {
updateDynamicRam("isRunning", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("isRunning"));
if (fn === undefined || ip === undefined) {
throw makeRuntimeErrorMsg("isRunning", "Usage: isRunning(scriptname, server, [arg1], [arg2]...)");
}
if(typeof fn === 'number') {
return getRunningScriptByPid(fn, 'isRunning') != null;
} else {
return getRunningScript(fn, ip, "isRunning", scriptArgs) != null;
}
},
getStockSymbols: function() {
updateDynamicRam("getStockSymbols", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockSymbols"));
checkTixApiAccess("getStockSymbols");
return Object.values(_StockMarket_data_StockSymbols__WEBPACK_IMPORTED_MODULE_55__["StockSymbols"]);
},
getStockPrice: function(symbol) {
updateDynamicRam("getStockPrice", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockPrice"));
checkTixApiAccess("getStockPrice");
const stock = getStockFromSymbol(symbol, "getStockPrice");
return stock.price;
},
getStockAskPrice: function(symbol) {
updateDynamicRam("getStockAskPrice", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockAskPrice"));
checkTixApiAccess("getStockAskPrice");
const stock = getStockFromSymbol(symbol, "getStockAskPrice");
return stock.getAskPrice();
},
getStockBidPrice: function(symbol) {
updateDynamicRam("getStockBidPrice", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockBidPrice"));
checkTixApiAccess("getStockBidPrice");
const stock = getStockFromSymbol(symbol, "getStockBidPrice");
return stock.getBidPrice();
},
getStockPosition: function(symbol) {
updateDynamicRam("getStockPosition", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockPosition"));
checkTixApiAccess("getStockPosition");
var stock = _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["SymbolToStockMap"][symbol];
if (stock == null) {
throw makeRuntimeErrorMsg("getStockPosition", `Invalid stock symbol: ${symbol}`);
}
return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx];
},
getStockMaxShares: function(symbol) {
updateDynamicRam("getStockMaxShares", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockMaxShares"));
checkTixApiAccess("getStockMaxShares");
const stock = getStockFromSymbol(symbol, "getStockMaxShares");
return stock.maxShares;
},
getStockPurchaseCost: function(symbol, shares, posType) {
updateDynamicRam("getStockPurchaseCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockPurchaseCost"));
checkTixApiAccess("getStockPurchaseCost");
const stock = getStockFromSymbol(symbol, "getStockPurchaseCost");
shares = Math.round(shares);
let pos;
const sanitizedPosType = posType.toLowerCase();
if (sanitizedPosType.includes("l")) {
pos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Long;
} else if (sanitizedPosType.includes("s")) {
pos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Short;
} else {
return Infinity;
}
const res = Object(_StockMarket_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_52__["getBuyTransactionCost"])(stock, shares, pos);
if (res == null) { return Infinity; }
return res;
},
getStockSaleGain: function(symbol, shares, posType) {
updateDynamicRam("getStockSaleGain", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockSaleGain"));
checkTixApiAccess("getStockSaleGain");
const stock = getStockFromSymbol(symbol, "getStockSaleGain");
shares = Math.round(shares);
let pos;
const sanitizedPosType = posType.toLowerCase();
if (sanitizedPosType.includes("l")) {
pos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Long;
} else if (sanitizedPosType.includes("s")) {
pos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Short;
} else {
return 0;
}
const res = Object(_StockMarket_StockMarketHelpers__WEBPACK_IMPORTED_MODULE_52__["getSellTransactionGain"])(stock, shares, pos);
if (res == null) { return 0; }
return res;
},
buyStock: function(symbol, shares) {
updateDynamicRam("buyStock", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("buyStock"));
checkTixApiAccess("buyStock");
const stock = getStockFromSymbol(symbol, "buyStock");
const res = Object(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__["buyStock"])(stock, shares, workerScript, { rerenderFn: _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"] });
return res ? stock.price : 0;
},
sellStock: function(symbol, shares) {
updateDynamicRam("sellStock", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sellStock"));
checkTixApiAccess("sellStock");
const stock = getStockFromSymbol(symbol, "sellStock");
const res = Object(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__["sellStock"])(stock, shares, workerScript, { rerenderFn: _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"] });
return res ? stock.price : 0;
},
shortStock: function(symbol, shares) {
updateDynamicRam("shortStock", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("shortStock"));
checkTixApiAccess("shortStock");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 8) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][8] <= 1) {
throw makeRuntimeErrorMsg(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__["shortStock"], "You must either be in BitNode-8 or you must have Source-File 8 Level 2.");
}
}
const stock = getStockFromSymbol(symbol, "shortStock");
const res = Object(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__["shortStock"])(stock, shares, workerScript, { rerenderFn: _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"] });
return res ? stock.price : 0;
},
sellShort: function(symbol, shares) {
updateDynamicRam("sellShort", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sellShort"));
checkTixApiAccess("sellShort");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 8) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][8] <= 1) {
throw makeRuntimeErrorMsg("sellShort", "You must either be in BitNode-8 or you must have Source-File 8 Level 2.");
}
}
const stock = getStockFromSymbol(symbol, "sellShort");
const res = Object(_StockMarket_BuyingAndSelling__WEBPACK_IMPORTED_MODULE_49__["sellShort"])(stock, shares, workerScript, { rerenderFn: _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"] });
return res ? stock.price : 0;
},
placeOrder: function(symbol, shares, price, type, pos) {
updateDynamicRam("placeOrder", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("placeOrder"));
checkTixApiAccess("placeOrder");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 8) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][8] <= 2) {
throw makeRuntimeErrorMsg("placeOrder", "You must either be in BitNode-8 or you must have Source-File 8 Level 3.");
}
}
const stock = getStockFromSymbol(symbol, "placeOrder");
let orderType, orderPos;
ltype = type.toLowerCase();
if (ltype.includes("limit") && ltype.includes("buy")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].LimitBuy;
} else if (ltype.includes("limit") && ltype.includes("sell")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].LimitSell;
} else if (ltype.includes("stop") && ltype.includes("buy")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].StopBuy;
} else if (ltype.includes("stop") && ltype.includes("sell")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].StopSell;
} else {
throw makeRuntimeErrorMsg("placeOrder", `Invalid order type: ${type}`);
}
lpos = pos.toLowerCase();
if (lpos.includes("l")) {
orderPos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Long;
} else if (lpos.includes('s')) {
orderPos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Short;
} else {
throw makeRuntimeErrorMsg("placeOrder", `Invalid position type: ${pos}`);
}
return Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["placeOrder"])(stock, shares, price, orderType, orderPos, workerScript);
},
cancelOrder: function(symbol, shares, price, type, pos) {
updateDynamicRam("cancelOrder", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("cancelOrder"));
checkTixApiAccess("cancelOrder");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 8) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][8] <= 2) {
throw makeRuntimeErrorMsg("cancelOrder", "You must either be in BitNode-8 or you must have Source-File 8 Level 3.");
}
}
const stock = getStockFrom(symbol, "cancelOrder");
if (isNaN(shares) || isNaN(price)) {
throw makeRuntimeErrorMsg("cancelOrder", `Invalid shares or price. Must be numeric. shares=${shares}, price=${price}`);
}
var orderType, orderPos;
ltype = type.toLowerCase();
if (ltype.includes("limit") && ltype.includes("buy")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].LimitBuy;
} else if (ltype.includes("limit") && ltype.includes("sell")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].LimitSell;
} else if (ltype.includes("stop") && ltype.includes("buy")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].StopBuy;
} else if (ltype.includes("stop") && ltype.includes("sell")) {
orderType = _StockMarket_data_OrderTypes__WEBPACK_IMPORTED_MODULE_53__["OrderTypes"].StopSell;
} else {
throw makeRuntimeErrorMsg("cancelOrder", `Invalid order type: ${type}`);
}
lpos = pos.toLowerCase();
if (lpos.includes("l")) {
orderPos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Long;
} else if (lpos.includes('s')) {
orderPos = _StockMarket_data_PositionTypes__WEBPACK_IMPORTED_MODULE_54__["PositionTypes"].Short;
} else {
throw makeRuntimeErrorMsg("cancelOrder", `Invalid position type: ${pos}`);
}
var params = {
stock: stock,
shares: shares,
price: price,
type: orderType,
pos: orderPos,
};
return Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["cancelOrder"])(params, workerScript);
},
getOrders: function() {
updateDynamicRam("getOrders", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getOrders"));
checkTixApiAccess("getOrders");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN !== 8) {
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][8] <= 2) {
throw makeRuntimeErrorMsg(workerScript, "You must either be in BitNode-8 or have Source-File 8 Level 3.");
}
}
const orders = {};
const stockMarketOrders = _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["StockMarket"]["Orders"];
for (let symbol in stockMarketOrders) {
const orderBook = stockMarketOrders[symbol];
if (orderBook.constructor === Array && orderBook.length > 0) {
orders[symbol] = [];
for (let i = 0; i < orderBook.length; ++i) {
orders[symbol].push({
shares: orderBook[i].shares,
price: orderBook[i].price,
type: orderBook[i].type,
position: orderBook[i].pos,
});
}
}
}
return orders;
},
getStockVolatility: function(symbol) {
updateDynamicRam("getStockVolatility", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockVolatility"));
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SDataTixApi) {
throw makeRuntimeErrorMsg("getStockVolatility", "You don't have 4S Market Data TIX API Access!");
}
const stock = getStockFromSymbol(symbol, "getStockVolatility");
return stock.mv / 100; // Convert from percentage to decimal
},
getStockForecast: function(symbol) {
updateDynamicRam("getStockForecast", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStockForecast"));
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SDataTixApi) {
throw makeRuntimeErrorMsg("getStockForecast", "You don't have 4S Market Data TIX API Access!");
}
const stock = getStockFromSymbol(symbol, "getStockForecast");
var forecast = 50;
stock.b ? forecast += stock.otlkMag : forecast -= stock.otlkMag;
return forecast / 100; // Convert from percentage to decimal
},
purchase4SMarketData: function() {
updateDynamicRam("purchase4SMarketData", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchase4SMarketData"));
checkTixApiAccess("purchase4SMarketData");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SData) {
workerScript.log("purchase4SMarketData", "Already purchased 4S Market Data.");
return true;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(Object(_StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__["getStockMarket4SDataCost"])())) {
workerScript.log("purchase4SMarketData", "Not enough money to purchase 4S Market Data.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SData = true;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(Object(_StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__["getStockMarket4SDataCost"])());
workerScript.log("purchase4SMarketData", "Purchased 4S Market Data");
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"])();
return true;
},
purchase4SMarketDataTixApi : function() {
updateDynamicRam("purchase4SMarketDataTixApi", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchase4SMarketDataTixApi"));
checkTixApiAccess("purchase4SMarketDataTixApi");
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SDataTixApi) {
workerScript.log("purchase4SMarketDataTixApi", "Already purchased 4S Market Data TIX API");
return true;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(Object(_StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__["getStockMarket4STixApiCost"])())) {
workerScript.log("purchase4SMarketDataTixApi", "Not enough money to purchase 4S Market Data TIX API");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SDataTixApi = true;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(Object(_StockMarket_StockMarketCosts__WEBPACK_IMPORTED_MODULE_56__["getStockMarket4STixApiCost"])());
workerScript.log("purchase4SMarketDataTixApi", "Purchased 4S Market Data TIX API");
Object(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_51__["displayStockMarketContent"])();
return true;
},
getPurchasedServerLimit : function() {
updateDynamicRam("getPurchasedServerLimit", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPurchasedServerLimit"));
return Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerLimit"])();
},
getPurchasedServerMaxRam: function() {
updateDynamicRam("getPurchasedServerMaxRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPurchasedServerMaxRam"));
return Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerMaxRam"])();
},
getPurchasedServerCost: function(ram) {
updateDynamicRam("getPurchasedServerCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPurchasedServerCost"));
const cost = Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerCost"])(ram);
if (cost === Infinity) {
workerScript.log("getPurchasedServerCost", `Invalid argument: ram='${ram}'`);
return Infinity;
}
return cost;
},
purchaseServer: function(hostname, ram) {
updateDynamicRam("purchaseServer", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchaseServer"));
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s+/g, '');
if (hostnameStr == "") {
workerScript.log("purchaseServer", `Invalid argument: hostname='${hostnameStr}'`);
return "";
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].purchasedServers.length >= Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerLimit"])()) {
workerScript.log("purchaseServer", `You have reached the maximum limit of ${Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerLimit"])()} servers. You cannot purchase any more.`);
return "";
}
const cost = Object(_Server_ServerPurchases__WEBPACK_IMPORTED_MODULE_46__["getPurchaseServerCost"])(ram);
if (cost === Infinity) {
workerScript.log("purchaseServer", `Invalid argument: ram='${ram}'`);
return "";
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(cost)) {
workerScript.log("purchaseServer", `Not enough money to purchase server. Need ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(cost)}`);
return "";
}
var newServ = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["safetlyCreateUniqueServer"])({
ip: Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["createUniqueRandomIp"])(),
hostname: hostnameStr,
organizationName: "",
isConnectedTo: false,
adminRights: true,
purchasedByPlayer: true,
maxRam: ram,
});
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AddToAllServers"])(newServ);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].purchasedServers.push(newServ.ip);
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(cost);
workerScript.log("purchaseServer", `Purchased new server with hostname '${newServ.hostname}' for ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(cost)}`);
return newServ.hostname;
},
deleteServer: function(hostname) {
updateDynamicRam("deleteServer", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("deleteServer"));
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s\s+/g, '');
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["GetServerByHostname"])(hostnameStr);
if (server == null) {
workerScript.log("deleteServer", `Invalid argument: hostname='${hostnameStr}'`);
return false;
}
if (!server.purchasedByPlayer || server.hostname === "home") {
workerScript.log("deleteServer", "Cannot delete non-purchased server.");
return false;
}
var ip = server.ip;
// Can't delete server you're currently connected to
if (server.isConnectedTo) {
workerScript.log("deleteServer", "You are currently connected to the server you are trying to delete.");
return false;
}
// A server cannot delete itself
if (ip === workerScript.serverIp) {
workerScript.log("deleteServer", "Cannot delete the server this script is running on.");
return false;
}
// Delete all scripts running on server
if (server.runningScripts.length > 0) {
workerScript.log("deleteServer", `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_38__["Player"].purchasedServers.length; ++i) {
if (ip == _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].purchasedServers[i]) {
found = true;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].purchasedServers.splice(i, 1);
break;
}
}
if (!found) {
workerScript.log("deleteServer", `Could not identify server ${server.hostname} as a purchased server. This is a bug. Report to dev.`);
return false;
}
// Delete from all servers
delete _Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AllServers"][ip];
// Delete from home computer
found = false;
var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer();
for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (ip == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1);
workerScript.log("deleteServer", `Deleted server '${hostnameStr}`);
return true;
}
}
// Wasn't found on home computer
workerScript.log("deleteServer", `Could not find server ${server.hostname} as a purchased server. This is a bug. Report to dev.`);
return false;
},
getPurchasedServers: function(hostname=true) {
updateDynamicRam("getPurchasedServers", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPurchasedServers"));
var res = [];
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].purchasedServers.forEach(function(ip) {
if (hostname) {
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("getPurchasedServers", "Could not find server. This is a bug. Report to dev.");
}
res.push(server.hostname);
} else {
res.push(ip);
}
});
return res;
},
write: function(port, data="", mode="a") {
updateDynamicRam("write", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("write"));
if (!isNaN(port)) { // Write to port
// Port 1-10
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("write", `Trying to write to invalid port: ${port}. Only ports 1-${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts} are valid.`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("write", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port.write(data);
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(port)) { // Write to script or text file
let fn = port;
if (!Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57__["isValidFilePath"])(fn)) {
throw makeRuntimeErrorMsg("write", `Invalid filepath: ${fn}`);
}
if(fn.lastIndexOf("/") === 0) {
fn = Object(_Terminal_DirectoryHelpers__WEBPACK_IMPORTED_MODULE_57__["removeLeadingSlash"])(fn);
}
// Coerce 'data' to be a string
try {
data = String(data);
} catch (e) {
throw makeRuntimeErrorMsg("write", `Invalid data (${e}). Data being written must be convertible to a string`);
}
const server = workerScript.getServer();
if (server == null) {
throw makeRuntimeErrorMsg("write", "Error getting Server. This is a bug. Report to dev.");
}
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__["isScriptFilename"])(fn)) {
// Write to script
let script = workerScript.getScriptOnServer(fn);
if (script == null) {
// Create a new script
script = new _Script_Script__WEBPACK_IMPORTED_MODULE_40__["Script"](fn, data, server.ip, server.scripts);
server.scripts.push(script);
return true;
}
mode === "w" ? script.code = data : script.code += data;
script.updateRamUsage(server.scripts);
script.markUpdated();
} else {
// Write to text file
let txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_58__["getTextFile"])(fn, server);
if (txtFile == null) {
txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_58__["createTextFile"])(fn, data, server);
return true;
}
if (mode === "w") {
txtFile.write(data);
} else {
txtFile.append(data);
}
}
return true;
} else {
throw makeRuntimeErrorMsg("write", `Invalid argument: ${port}`);
}
},
tryWrite: function(port, data="") {
updateDynamicRam("tryWrite", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("tryWrite"));
if (!isNaN(port)) {
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("tryWrite", `Invalid port: ${port}. Only ports 1-${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts} are valid.`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("tryWrite", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port.tryWrite(data);
} else {
throw makeRuntimeErrorMsg("tryWrite", `Invalid argument: ${port}`);
}
},
read: function(port) {
updateDynamicRam("read", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("read"));
if (!isNaN(port)) { // Read from port
// Port 1-10
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("read", `Invalid port: ${port}. Only ports 1-${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts} are valid.`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("read", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port.read();
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(port)) { // Read from script or text file
let fn = port;
let server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (server == null) {
throw makeRuntimeErrorMsg("read", "Error getting Server. This is a bug. Report to dev.");
}
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__["isScriptFilename"])(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_58__["getTextFile"])(fn, server);
if (txtFile !== null) {
return txtFile.text;
} else {
return "";
}
}
} else {
throw makeRuntimeErrorMsg("read", `Invalid argument: ${port}`);
}
},
peek: function(port) {
updateDynamicRam("peek", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("peek"));
if (isNaN(port)) {
throw makeRuntimeErrorMsg("peek", `Invalid argument. Must be a port number between 1 and ${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts}, is ${port}`);
}
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("peek", `Invalid argument. Must be a port number between 1 and ${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts}, is ${port}`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("peek", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port.peek();
},
clear: function(port) {
updateDynamicRam("clear", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("clear"));
if (!isNaN(port)) { // Clear port
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("clear", `Trying to clear invalid port: ${port}. Only ports 1-${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts} are valid`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("clear", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port.clear();
} else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(port)) { // Clear text file
var fn = port;
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(workerScript.serverIp);
if (server == null) {
throw makeRuntimeErrorMsg("clear", "Error getting Server. This is a bug. Report to dev.");
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_58__["getTextFile"])(fn, server);
if (txtFile != null) {
txtFile.write("");
}
} else {
throw makeRuntimeErrorMsg("clear", `Invalid argument: ${port}`);
}
return 0;
},
getPortHandle: function(port) {
updateDynamicRam("getPortHandle", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPortHandle"));
if (isNaN(port)) {
throw makeRuntimeErrorMsg("getPortHandle", `Invalid port: ${port} Must be an integer between 1 and ${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts}.`);
}
port = Math.round(port);
if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts) {
throw makeRuntimeErrorMsg("getPortHandle", `Invalid port: ${port}. Only ports 1-${_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].NumNetscriptPorts} are valid.`);
}
var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_59__[/* NetscriptPorts */ "a"][port-1];
if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_64__["NetscriptPort"])) {
throw makeRuntimeErrorMsg("getPortHandle", `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return port;
},
rm: function(fn, ip) {
updateDynamicRam("rm", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("rm"));
if (ip == null || ip === "") {
ip = workerScript.serverIp;
}
const s = safeGetServer(ip, "rm");
const status = s.removeFile(fn);
if (!status.res) {
workerScript.log("rm", status.msg);
}
return status.res;
},
scriptRunning: function(scriptname, ip) {
updateDynamicRam("scriptRunning", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("scriptRunning"));
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("scriptRunning", `Invalid IP/hostname: ${ip}`);
}
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) {
return true;
}
}
return false;
},
scriptKill: function(scriptname, ip) {
updateDynamicRam("scriptKill", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("scriptKill"));
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("scriptKill", `Invalid IP/hostname: ${ip}`);
}
var suc = false;
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) {
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(server.runningScripts[i], server.ip);
suc = true;
}
}
return suc;
},
getScriptName: function() {
return workerScript.name;
},
getScriptRam: function(scriptname, ip=workerScript.serverIp) {
updateDynamicRam("getScriptRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getScriptRam"));
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("getScriptRam", `Invalid IP/hostname: ${ip}`);
}
for (var i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) {
return server.scripts[i].ramUsage;
}
}
return 0;
},
getRunningScript: function(fn, ip) {
updateDynamicRam("getRunningScript", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getRunningScript"));
let runningScript;
if(arguments.length === 0) {
runningScript = workerScript.scriptRef;
} else if(typeof fn === 'number') {
runningScript = getRunningScriptByPid(fn, 'getRunningScript');
} else {
const scriptArgs = [];
for (var i = 2; i < arguments.length; ++i) {
scriptArgs.push(arguments[i]);
}
runningScript = getRunningScript(fn, ip, 'getRunningScript', scriptArgs);
}
if (runningScript === null) return null;
return {
args: runningScript.args.slice(),
filename: runningScript.filename,
logs: runningScript.logs.slice(),
offlineExpGained: runningScript.offlineExpGained,
offlineMoneyMade: runningScript.offlineMoneyMade,
offlineRunningTime: runningScript.offlineRunningTime,
onlineExpGained: runningScript.onlineExpGained,
onlineMoneyMade: runningScript.onlineMoneyMade,
onlineRunningTime: runningScript.onlineRunningTime,
pid: runningScript.pid,
ramUsage: runningScript.ramUsage,
server: runningScript.server,
threads: runningScript.threads,
};
},
getHackTime: function(ip) {
updateDynamicRam("getHackTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getHackTime"));
const server = safeGetServer(ip, "getHackTime");
if (failOnHacknetServer(server, "getHackTime")) { return Infinity; }
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]); // Returns seconds
},
getGrowTime: function(ip) {
updateDynamicRam("getGrowTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getGrowTime"));
const server = safeGetServer(ip, "getGrowTime");
if (failOnHacknetServer(server, "getGrowTime")) { return Infinity; }
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateGrowTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]); // Returns seconds
},
getWeakenTime: function(ip) {
updateDynamicRam("getWeakenTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getWeakenTime"));
const server = safeGetServer(ip, "getWeakenTime");
if (failOnHacknetServer(server, "getWeakenTime")) { return Infinity; }
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateWeakenTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]); // Returns seconds
},
getScriptIncome: function(scriptname, ip) {
updateDynamicRam("getScriptIncome", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getScriptIncome"));
if (arguments.length === 0) {
var res = [];
// First element is total income of all currently running scripts
let total = 0;
for (const script of _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_61__["workerScripts"].values()) {
total += (script.scriptRef.onlineMoneyMade / script.scriptRef.onlineRunningTime);
}
res.push(total);
// Second element is total income you've earned from scripts since you installed Augs
res.push(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].scriptProdSinceLastAug / (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].playtimeSinceLastAug / 1000));
return res;
} else {
// Get income for a particular script
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("getScriptIncome", `Invalid IP/hostnamed: ${ip}`);
}
var argsForScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]);
}
var runningScriptObj = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_41__[/* findRunningScript */ "a"])(scriptname, argsForScript, server);
if (runningScriptObj == null) {
workerScript.log("getScriptIncome", `No such script '${scriptname}' on '${server.hostname}' with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__["arrayToString"])(argsForScript)}`);
return -1;
}
return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime;
}
},
getScriptExpGain: function(scriptname, ip) {
updateDynamicRam("getScriptExpGain", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getScriptExpGain"));
if (arguments.length === 0) {
var total = 0;
for (const ws of _Netscript_WorkerScripts__WEBPACK_IMPORTED_MODULE_61__["workerScripts"].values()) {
total += (ws.scriptRef.onlineExpGained / ws.scriptRef.onlineRunningTime);
}
return total;
} else {
// Get income for a particular script
var server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(ip);
if (server == null) {
throw makeRuntimeErrorMsg("getScriptExpGain", `Invalid IP/hostnamed: ${ip}`);
}
var argsForScript = [];
for (var i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]);
}
var runningScriptObj = Object(_Script_ScriptHelpers__WEBPACK_IMPORTED_MODULE_41__[/* findRunningScript */ "a"])(scriptname, argsForScript, server);
if (runningScriptObj == null) {
workerScript.log("getScriptExpGain", `No such script '${scriptname}' on '${server.hostname}' with args: ${Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_74__["arrayToString"])(argsForScript)}`);
return -1;
}
return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime;
}
},
nFormat: function(n, format) {
if (isNaN(n) || isNaN(parseFloat(n)) || typeof format !== "string") {
return "";
}
return _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].format(parseFloat(n), format);
},
tFormat: function(milliseconds, milliPrecision=false) {
return Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__["convertTimeMsToTimeElapsedString"])(milliseconds, milliPrecision);
},
getTimeSinceLastAug: function() {
updateDynamicRam("getTimeSinceLastAug", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getTimeSinceLastAug"));
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].playtimeSinceLastAug;
},
prompt : function(txt) {
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(txt)) {txt = JSON.stringify(txt);}
// The id for this popup will consist of the first 20 characters of the prompt string..
// Thats hopefully good enough to be unique
const popupId = `prompt-popup-${txt.slice(0, 20)}`;
const textElement = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76__["createElement"])("p", { innerHTML: txt });
return new Promise(function(resolve) {
const yesBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76__["createElement"])("button", {
class: "popup-box-button",
innerText: "Yes",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_78__["removeElementById"])(popupId);
resolve(true);
},
});
const noBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_76__["createElement"])("button", {
class: "popup-box-button",
innerText: "No",
clickListener: () => {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_78__["removeElementById"])(popupId);
resolve(false);
},
});
Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_77__["createPopup"])(popupId, [textElement, yesBtn, noBtn]);
});
},
wget: async function(url, target, ip=workerScript.serverIp) {
if (!Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__["isScriptFilename"])(target) && !target.endsWith(".txt")) {
workerScript.log("wget", `Invalid target file: '${target}'. Must be a script or text file.`);
return Promise.resolve(false);
}
var s = safeGetServer(ip, "wget");
return new Promise(function(resolve) {
$.get(url, function(data) {
let res;
if (Object(_Script_ScriptHelpersTS__WEBPACK_IMPORTED_MODULE_42__["isScriptFilename"])(target)) {
res = s.writeToScriptFile(target, data);
} else {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
workerScript.log("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("wget", JSON.stringify(e));
return resolve(false)
});
});
},
getFavorToDonate: function() {
updateDynamicRam("getFavorToDonate", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getFavorToDonate"));
return Math.floor(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].BaseFavorToDonate * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__["BitNodeMultipliers"].RepToDonateToFaction);
},
/* Singularity Functions */
universityCourse: function(universityName, className) {
updateDynamicRam("universityCourse", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("universityCourse"));
checkSingularityAccess("universityCourse", 1);
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("universityCourse", "You are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("universityCourse", txt);
}
var costMult, expMult;
switch(universityName.toLowerCase()) {
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumSummitUniversity.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Aevum) {
workerScript.log("universityCourse", "You cannot study at 'Summit University' because you are not in 'Aevum'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gotoLocation(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumSummitUniversity);
costMult = 4;
expMult = 3;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12RothmanUniversity.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Sector12) {
workerScript.log("universityCourse", "You cannot study at 'Rothman University' because you are not in 'Sector-12'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12RothmanUniversity;
costMult = 3;
expMult = 2;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].VolhavenZBInstituteOfTechnology.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Volhaven) {
workerScript.log("universityCourse", "You cannot study at 'ZB Institute of Technology' because you are not in 'Volhaven'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].VolhavenZBInstituteOfTechnology;
costMult = 5;
expMult = 4;
break;
default:
workerScript.log("universityCourse", `Invalid university name: '${universityName}'.`);
return false;
}
var task;
switch(className.toLowerCase()) {
case "Study Computer Science".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassStudyComputerScience;
break;
case "Data Structures".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassDataStructures;
break;
case "Networks".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassNetworks;
break;
case "Algorithms".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassAlgorithms;
break;
case "Management".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassManagement;
break;
case "Leadership".toLowerCase():
task = _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassLeadership;
break;
default:
workerScript.log("universityCourse", `Invalid class name: ${className}.`);
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startClass(costMult, expMult, task);
workerScript.log("universityCourse", `Started ${task} at ${universityName}`);
return true;
},
gymWorkout: function(gymName, stat) {
updateDynamicRam("gymWorkout", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gymWorkout"));
checkSingularityAccess("gymWorkout", 1);
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("gymWorkout", "You are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("gymWorkout", txt);
}
var costMult, expMult;
switch(gymName.toLowerCase()) {
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumCrushFitnessGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Aevum) {
workerScript.log("gymWorkout", "You cannot workout at 'Crush Fitness' because you are not in 'Aevum'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumCrushFitnessGym;
costMult = 3;
expMult = 2;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumSnapFitnessGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Aevum) {
workerScript.log("gymWorkout", "You cannot workout at 'Snap Fitness' because you are not in 'Aevum'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].AevumSnapFitnessGym;
costMult = 10;
expMult = 5;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12IronGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Sector12) {
workerScript.log("gymWorkout", "You cannot workout at 'Iron Gym' because you are not in 'Sector-12'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12IronGym;
costMult = 1;
expMult = 1;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12PowerhouseGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Sector12) {
workerScript.log("gymWorkout", "You cannot workout at 'Powerhouse Gym' because you are not in 'Sector-12'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Sector12PowerhouseGym;
costMult = 20;
expMult = 10;
break;
case _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].VolhavenMilleniumFitnessGym.toLowerCase():
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city != _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Volhaven) {
workerScript.log("gymWorkout", "You cannot workout at 'Millenium Fitness Gym' because you are not in 'Volhaven'.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].VolhavenMilleniumFitnessGym;
costMult = 7;
expMult = 4;
break;
default:
workerScript.log("gymWorkout", `Invalid gym name: ${gymName}. gymWorkout() failed`);
return false;
}
switch(stat.toLowerCase()) {
case "strength".toLowerCase():
case "str".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassGymStrength);
break;
case "defense".toLowerCase():
case "def".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassGymDefense);
break;
case "dexterity".toLowerCase():
case "dex".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassGymDexterity);
break;
case "agility".toLowerCase():
case "agi".toLowerCase():
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].ClassGymAgility);
break;
default:
workerScript.log("gymWorkout", `Invalid stat: ${stat}.`);
return false;
}
workerScript.log("gymWorkout", `Started training ${stat} at ${gymName}`);
return true;
},
travelToCity: function(cityname) {
updateDynamicRam("travelToCity", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("travelToCity"));
checkSingularityAccess("travelToCity", 1);
switch(cityname) {
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Aevum:
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Chongqing:
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Sector12:
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].NewTokyo:
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Ishima:
case _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_32__["CityName"].Volhaven:
if(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].TravelCost)) {
throw makeRuntimeErrorMsg("travelToCity", "Not enough money to travel.");
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].TravelCost);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city = cityname;
workerScript.log("travelToCity", `Traveled to ${cityname}`);
return true;
default:
workerScript.log("travelToCity", `Invalid city name: '${cityname}'.`);
return false;
}
},
purchaseTor: function() {
updateDynamicRam("purchaseTor", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchaseTor"));
checkSingularityAccess("purchaseTor", 1);
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"]["Darkweb Server"] != null) {
workerScript.log("purchaseTor", "You already have a TOR router!");
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].TorRouterCost)) {
workerScript.log("purchaseTor", "You cannot afford to purchase a Tor router.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].TorRouterCost);
var darkweb = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["safetlyCreateUniqueServer"])({
ip: Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["createUniqueRandomIp"])(), hostname:"darkweb", organizationName:"",
isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1,
});
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_43__["AddToAllServers"])(darkweb);
_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer().ip);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
workerScript.log("purchaseTor", "You have purchased a Tor router!");
return true;
},
purchaseProgram: function(programName) {
updateDynamicRam("purchaseProgram", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchaseProgram"));
checkSingularityAccess("purchaseProgram", 1);
if (_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"]["Darkweb Server"] == null) {
workerScript.log("purchaseProgram", "You do not have the TOR router.");
return false;
}
programName = programName.toLowerCase();
let item = null;
for(const key in _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_16__["DarkWebItems"]) {
const i = _DarkWeb_DarkWebItems__WEBPACK_IMPORTED_MODULE_16__["DarkWebItems"][key];
if(i.program.toLowerCase() == programName) {
item = i;
}
}
if(item == null) {
workerScript.log("purchaseProgram", `Invalid program name: '${programName}.`);
return false;
}
if(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(item.price)) {
workerScript.log("purchaseProgram", `Not enough money to purchase '${item.program}'. Need ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(item.price)}`);
return false;
}
if(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(item.program)) {
workerScript.log("purchaseProgram", `You already have the '${item.program}' program`);
return true;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(item.price);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer().programs.push(item.program);
workerScript.log("purchaseProgram", `You have purchased the '${item.program}' program. The new program can be found on your home computer.`);
return true;
},
getCurrentServer: function() {
updateDynamicRam("getCurrentServer", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCurrentServer"));
checkSingularityAccess("getCurrentServer", 1);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer().hostname;
},
connect: function(hostname) {
updateDynamicRam("connect", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("connect"));
checkSingularityAccess("connect", 1);
if (!hostname) {
throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`);
}
let target = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServer"])(hostname);
if (target == null) {
throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`);
return;
}
if(hostname === 'home') {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].currentServer = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer().ip;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer().isConnectedTo = true;
_Terminal__WEBPACK_IMPORTED_MODULE_34__[/* Terminal */ "a"].currDir = "/";
_Terminal__WEBPACK_IMPORTED_MODULE_34__[/* Terminal */ "a"].resetTerminalInput(true);
return true;
}
const server = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer();
for (let i = 0; i < server.serversOnNetwork.length; i++) {
const other = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_45__["getServerOnNetwork"])(server, i);
if (other.ip == hostname || other.hostname == hostname) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer().isConnectedTo = false;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].currentServer = target.ip;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer().isConnectedTo = true;
_Terminal__WEBPACK_IMPORTED_MODULE_34__[/* Terminal */ "a"].currDir = "/";
_Terminal__WEBPACK_IMPORTED_MODULE_34__[/* Terminal */ "a"].resetTerminalInput(true);
return true;
}
}
return false;
},
manualHack: function() {
updateDynamicRam("manualHack", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("manualHack"));
checkSingularityAccess("manualHack", 1);
const server = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer();
return hack(server.hostname, true);
},
installBackdoor: function() {
updateDynamicRam("installBackdoor", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("installBackdoor"));
checkSingularityAccess("installBackdoor", 1);
const server = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getCurrentServer();
const installTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingTime"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]) / 4 * 1000;
// No root access or skill level too low
const canHack = Object(_Hacking_netscriptCanHack__WEBPACK_IMPORTED_MODULE_26__["netscriptCanHack"])(server, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
if (!canHack.res) {
throw makeRuntimeErrorMsg('installBackdoor', canHack.msg);
}
workerScript.log("installBackdoor", `Installing backdoor on '${server.hostname}' in ${Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_72__["convertTimeMsToTimeElapsedString"])(installTime, true)}`);
return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_62__[/* netscriptDelay */ "c"])(installTime, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
workerScript.log("installBackdoor", `Successfully installed backdoor on '${server.hostname}'`);
server.backdoorInstalled = true;
return Promise.resolve();
});
},
getStats: function() {
updateDynamicRam("getStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getStats"));
checkSingularityAccess("getStats", 1);
workerScript.log("getStats", `getStats is deprecated, please use getPlayer`);
return {
hacking: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_skill,
strength: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength,
defense: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense,
dexterity: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity,
agility: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility,
charisma: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma,
intelligence: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].intelligence,
}
},
getCharacterInformation: function() {
updateDynamicRam("getCharacterInformation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCharacterInformation"));
checkSingularityAccess("getCharacterInformation", 1);
workerScript.log("getCharacterInformation", `getCharacterInformation is deprecated, please use getPlayer`);
return {
bitnode: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN,
city: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city,
factions: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factions.slice(),
hp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hp,
jobs: Object.keys(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs),
jobTitles: Object.values(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs),
maxHp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].max_hp,
mult: {
agility: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_mult,
agilityExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_exp_mult,
companyRep: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].company_rep_mult,
crimeMoney: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].crime_money_mult,
crimeSuccess: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].crime_success_mult,
defense: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_mult,
defenseExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_exp_mult,
dexterity: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_mult,
dexterityExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_exp_mult,
factionRep: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].faction_rep_mult,
hacking: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_mult,
hackingExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_exp_mult,
strength: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_mult,
strengthExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_exp_mult,
workMoney: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].work_money_mult,
},
timeWorked: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].timeWorked,
tor: _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"].hasOwnProperty("Darkweb Server"),
workHackExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workHackExpGained,
workStrExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workStrExpGained,
workDefExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDefExpGained,
workDexExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDexExpGained,
workAgiExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workAgiExpGained,
workChaExpGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workChaExpGained,
workRepGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workRepGained,
workMoneyGain: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workMoneyGained,
hackingExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_exp,
strengthExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_exp,
defenseExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_exp,
dexterityExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_exp,
agilityExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_exp,
charismaExp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma_exp,
};
},
getPlayer: function() {
updateDynamicRam("getPlayer", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getPlayer"));
const data = {
hacking_skill: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_skill,
hp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hp,
max_hp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].max_hp,
strength: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength,
defense: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense,
dexterity: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity,
agility: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility,
charisma: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma,
intelligence: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].intelligence,
hacking_chance_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_chance_mult,
hacking_speed_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_speed_mult,
hacking_money_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_money_mult,
hacking_grow_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_grow_mult,
hacking_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_exp,
strength_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_exp,
defense_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_exp,
dexterity_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_exp,
agility_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_exp,
charisma_exp: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma_exp,
hacking_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_mult,
strength_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_mult,
defense_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_mult,
dexterity_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_mult,
agility_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_mult,
charisma_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma_mult,
hacking_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacking_exp_mult,
strength_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength_exp_mult,
defense_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense_exp_mult,
dexterity_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity_exp_mult,
agility_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility_exp_mult,
charisma_exp_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].charisma_exp_mult,
company_rep_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].company_rep_mult,
faction_rep_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].faction_rep_mult,
money: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.toNumber(),
city: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].city,
location: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location,
crime_money_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].crime_money_mult,
crime_success_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].crime_success_mult,
isWorking: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking,
workType: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workType,
currentWorkFactionName: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].currentWorkFactionName,
currentWorkFactionDescription: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].currentWorkFactionDescription,
workHackExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workHackExpGainRate,
workStrExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workStrExpGainRate,
workDefExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDefExpGainRate,
workDexExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDexExpGainRate,
workAgiExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workAgiExpGainRate,
workChaExpGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workChaExpGainRate,
workRepGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workRepGainRate,
workMoneyGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workMoneyGainRate,
workMoneyLossRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workMoneyLossRate,
workHackExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workHackExpGained,
workStrExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workStrExpGained,
workDefExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDefExpGained,
workDexExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workDexExpGained,
workAgiExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workAgiExpGained,
workChaExpGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workChaExpGained,
workRepGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workRepGained,
workMoneyGained: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].workMoneyGained,
createProgramName: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].createProgramName,
createProgramReqLvl: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].createProgramReqLvl,
className: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].className,
crimeType: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].crimeType,
work_money_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].work_money_mult,
hacknet_node_money_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_money_mult,
hacknet_node_purchase_cost_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_purchase_cost_mult,
hacknet_node_ram_cost_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_ram_cost_mult,
hacknet_node_core_cost_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_core_cost_mult,
hacknet_node_level_cost_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hacknet_node_level_cost_mult,
hasWseAccount: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasWseAccount,
hasTixApiAccess: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasTixApiAccess,
has4SData: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SData,
has4SDataTixApi: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].has4SDataTixApi,
bladeburner_max_stamina_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner_max_stamina_mult,
bladeburner_stamina_gain_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner_stamina_gain_mult,
bladeburner_analysis_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner_analysis_mult,
bladeburner_success_chance_mult: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner_success_chance_mult,
bitNodeN: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN,
totalPlaytime: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].totalPlaytime,
playtimeSinceLastAug: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].playtimeSinceLastAug,
playtimeSinceLastBitnode: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].playtimeSinceLastBitnode,
jobs: {},
factions: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factions.slice(),
tor: _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"].hasOwnProperty("Darkweb Server"),
};
Object.assign(data.jobs, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs);
return data;
},
hospitalize: function() {
updateDynamicRam("hospitalize", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("hospitalize"));
checkSingularityAccess("hospitalize", 1);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hospitalize();
},
isBusy: function() {
updateDynamicRam("isBusy", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("isBusy"));
checkSingularityAccess("isBusy", 1);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking || _Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"];
},
stopAction: function() {
updateDynamicRam("stopAction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("stopAction"));
checkSingularityAccess("stopAction", 1);
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("stopAction", txt);
return true;
}
return false;
},
upgradeHomeRam: function() {
updateDynamicRam("upgradeHomeRam", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("upgradeHomeRam"));
checkSingularityAccess("upgradeHomeRam", 2);
// Check if we're at max RAM
const homeComputer = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getHomeComputer();
if (homeComputer.maxRam >= _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].HomeComputerMaxRam) {
workerScript.log("upgradeHomeRam", `Your home computer is at max RAM.`);
return false;
}
const cost = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getUpgradeHomeRamCost();
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(cost)) {
workerScript.log("upgradeHomeRam", `You don't have enough money. Need ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(cost)}`);
return false;
}
homeComputer.maxRam *= 2;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(cost);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
workerScript.log("upgradeHomeRam", `Purchased additional RAM for home computer! It now has ${homeComputer.maxRam}GB of RAM.`);
return true;
},
getUpgradeHomeRamCost: function() {
updateDynamicRam("getUpgradeHomeRamCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getUpgradeHomeRamCost"));
checkSingularityAccess("getUpgradeHomeRamCost", 2);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].getUpgradeHomeRamCost();
},
workForCompany: function(companyName) {
updateDynamicRam("workForCompany", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("workForCompany"));
checkSingularityAccess("workForCompany", 2);
// Sanitize input
if (companyName == null) {
companyName = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].companyName;
}
// Make sure its a valid company
if (companyName == null || companyName === "" || !(_Company_Companies__WEBPACK_IMPORTED_MODULE_12__["Companies"][companyName] instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_11__["Company"])) {
workerScript.log("workForCompany", `Invalid company: '${companyName}'`);
return false;
}
// Make sure player is actually employed at the comapny
if (!Object.keys(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs).includes(companyName)) {
workerScript.log("workForCompany", `You do not have a job at '${companyName}'`);
return false;
}
// Cant work while in a mission
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("workForCompany", "You are in the middle of a mission.");
return false;
}
// Check to make sure company position data is valid
const companyPositionName = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs[companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_14__["CompanyPositions"][companyPositionName];
if (companyPositionName === "" || !(companyPosition instanceof _Company_CompanyPosition__WEBPACK_IMPORTED_MODULE_13__["CompanyPosition"])) {
workerScript.log("workForCompany", "You do not have a job");
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("workForCompany", txt);
}
if (companyPosition.isPartTimeJob()) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startWorkPartTime(companyName);
} else {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startWork(companyName);
}
workerScript.log("workForCompany", `Began working at '${_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].companyName}' as a '${companyPositionName}'`);
return true;
},
applyToCompany: function(companyName, field) {
updateDynamicRam("applyToCompany", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("applyToCompany"));
checkSingularityAccess("applyToCompany", 2);
getCompany("applyToCompany", companyName);
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].location = companyName;
var res;
switch (field.toLowerCase()) {
case "software":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForSoftwareJob(true);
break;
case "software consultant":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForSoftwareConsultantJob(true);
break;
case "it":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForItJob(true);
break;
case "security engineer":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForSecurityEngineerJob(true);
break;
case "network engineer":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForNetworkEngineerJob(true);
break;
case "business":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForBusinessJob(true);
break;
case "business consultant":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForBusinessConsultantJob(true);
break;
case "security":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForSecurityJob(true);
break;
case "agent":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForAgentJob(true);
break;
case "employee":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForEmployeeJob(true);
break;
case "part-time employee":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForPartTimeEmployeeJob(true);
break;
case "waiter":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForWaiterJob(true);
break;
case "part-time waiter":
res = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].applyForPartTimeWaiterJob(true);
break;
default:
workerScript.log("applyToCompany", `Invalid job: '${field}'.`);
return false;
}
// The Player object's applyForJob function can return string with special error messages
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(res)) {
workerScript.log("applyToCompany", res);
return false;
}
if (res) {
workerScript.log("applyToCompany", `You were offered a new job at '${companyName}' as a '${_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs[companyName]}'`);
} else {
workerScript.log("applyToCompany", `You failed to get a new job/promotion at '${companyName}' in the '${field}' field.`);
}
return res;
},
getCompanyRep: function(companyName) {
updateDynamicRam("getCompanyRep", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCompanyRep"));
checkSingularityAccess("getCompanyRep", 2);
const company = getCompany("getCompanyRep", companyName);
return company.playerReputation;
},
getCompanyFavor: function(companyName) {
updateDynamicRam("getCompanyFavor", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCompanyFavor"));
checkSingularityAccess("getCompanyFavor", 2);
const company = getCompany("getCompanyFavor", companyName);
return company.favor;
},
getCompanyFavorGain: function(companyName) {
updateDynamicRam("getCompanyFavorGain", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCompanyFavorGain"));
checkSingularityAccess("getCompanyFavorGain", 2);
const company = getCompany("getCompanyFavorGain", companyName);
return company.getFavorGain()[0];
},
checkFactionInvitations: function() {
updateDynamicRam("checkFactionInvitations", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("checkFactionInvitations"));
checkSingularityAccess("checkFactionInvitations", 2);
// Make a copy of Player.factionInvitations
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations.slice();
},
joinFaction: function(name) {
updateDynamicRam("joinFaction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("joinFaction"));
checkSingularityAccess("joinFaction", 2);
getFaction("joinFaction", name);
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations.includes(name)) {
workerScript.log("joinFaction", `You have not been invited by faction '${name}'`);
return false;
}
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_23__["Factions"][name];
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_24__["joinFaction"])(fac);
// Update Faction Invitation list to account for joined + banned factions
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations.length; ++i) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations[i] == name || _Faction_Factions__WEBPACK_IMPORTED_MODULE_23__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations[i]].isBanned) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factionInvitations.splice(i, 1);
i--;
}
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
workerScript.log("joinFaction", `Joined the '${name}' faction.`);
return true;
},
workForFaction: function(name, type) {
updateDynamicRam("workForFaction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("workForFaction"));
checkSingularityAccess("workForFaction", 2);
getFaction("workForFaction", name);
// if the player is in a gang and the target faction is any of the gang faction, fail
if(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].inGang() && _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"][name] !== undefined) {
workerScript.log("workForFaction", `Faction '${name}' does not offer work at the moment.`);
return;
}
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("workForFaction", "You are in the middle of a mission.");
return;
}
if (!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factions.includes(name)) {
workerScript.log("workForFaction", `You are not a member of '${name}'`);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
const txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("workForFaction", txt);
}
var fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_23__["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.log("workForFaction", `Faction '${fac.name}' do not need help with hacking contracts.`);
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startFactionHackWork(fac);
workerScript.log("workForFaction", `Started carrying out hacking contracts for '${fac.name}'`);
return true;
case "field":
case "fieldwork":
case "field work":
if (!fdWkAvailable.includes(fac.name)) {
workerScript.log("workForFaction", `Faction '${fac.name}' do not need help with field missions.`);
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startFactionFieldWork(fac);
workerScript.log("workForFaction", `Started carrying out field missions for '${fac.name}'`);
return true;
case "security":
case "securitywork":
case "security work":
if (!scWkAvailable.includes(fac.name)) {
workerScript.log("workForFaction", `Faction '${fac.name}' do not need help with security work.`);
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startFactionSecurityWork(fac);
workerScript.log("workForFaction", `Started carrying out security work for '${fac.name}'`);
return true;
default:
workerScript.log("workForFaction", `Invalid work type: '${type}`);
}
return true;
},
getFactionRep: function(name) {
updateDynamicRam("getFactionRep", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getFactionRep"));
checkSingularityAccess("getFactionRep", 2);
const faction = getFaction("getFactionRep", name);
return faction.playerReputation;
},
getFactionFavor: function(name) {
updateDynamicRam("getFactionFavor", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getFactionFavor"));
checkSingularityAccess("getFactionFavor", 2);
const faction = getFaction("getFactionFavor", name);
return faction.favor;
},
getFactionFavorGain: function(name) {
updateDynamicRam("getFactionFavorGain", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getFactionFavorGain"));
checkSingularityAccess("getFactionFavorGain", 2);
const faction = getFaction("getFactionFavorGain", name);
return faction.getFavorGain()[0];
},
donateToFaction: function(name, amt) {
updateDynamicRam("donateToFaction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("donateToFaction"));
checkSingularityAccess("donateToFaction", 3);
const faction = getFaction("donateToFaction", name);
if (typeof amt !== 'number' || amt <= 0) {
workerScript.log("donateToFaction", `Invalid donation amount: '${amt}'.`);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].money.lt(amt)) {
workerScript.log("donateToFaction", `You do not have enough money to donate ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(amt)} to '${name}'`);
return false;
}
const repNeededToDonate = Math.round(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].BaseFavorToDonate * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__["BitNodeMultipliers"].RepToDonateToFaction);
if (faction.favor < repNeededToDonate) {
workerScript.log("donateToFaction", `You do not have enough favor to donate to this faction. Have ${faction.favor}, need ${repNeededToDonate}`);
return false;
}
const repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].faction_rep_mult;
faction.playerReputation += repGain;
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].loseMoney(amt);
workerScript.log("donateToFaction", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatMoney(amt)} donated to '${name}' for ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_68__["numeralWrapper"].formatReputation(repGain)} reputation`);
return true;
},
createProgram: function(name) {
updateDynamicRam("createProgram", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("createProgram"));
checkSingularityAccess("createProgram", 3);
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("createProgram", "You are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
var txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("createProgram", txt);
}
name = name.toLowerCase();
let p = null;
for (const key in _Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"]) {
if(_Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"][key].name.toLowerCase() == name) {
p = _Programs_Programs__WEBPACK_IMPORTED_MODULE_39__["Programs"][key];
}
}
if (p == null) {
workerScript.log("createProgram", `The specified program does not exist: '${name}`);
return false;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasProgram(p.name)) {
workerScript.log("createProgram", `You already have the '${p.name}' program`);
return false;
}
if (!p.create.req(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"])) {
workerScript.log("createProgram", `Hacking level is too low to create '${p.name}' (level ${p.create.level} req)`);
return false
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startCreateProgramWork(p.name, p.create.time, p.create.level);
workerScript.log("createProgram", `Began creating program: '${name}'`);
return true;
},
commitCrime: function(crimeRoughName) {
updateDynamicRam("commitCrime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("commitCrime"));
checkSingularityAccess("commitCrime", 3);
if (_Missions__WEBPACK_IMPORTED_MODULE_37__[/* inMission */ "c"]) {
workerScript.log("commitCrime", "You are in the middle of a mission.");
return;
}
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].isWorking) {
const txt = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].singularityStopWork();
workerScript.log("commitCrime", txt);
}
// Set Location to slums
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gotoLocation(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_33__["LocationName"].Slums);
const crime = Object(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9__["findCrime"])(crimeRoughName.toLowerCase());
if(crime == null) { // couldn't find crime
throw makeRuntimeErrorMsg("commitCrime", `Invalid crime: '${crimeRoughName}'`);
}
workerScript.log("commitCrime", `Attempting to commit ${crime.name}...`);
return crime.commit(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], 1, {workerscript: workerScript});
},
getCrimeChance: function(crimeRoughName) {
updateDynamicRam("getCrimeChance", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCrimeChance"));
checkSingularityAccess("getCrimeChance", 3);
const crime = Object(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9__["findCrime"])(crimeRoughName.toLowerCase());
if(crime == null) {
throw makeRuntimeErrorMsg("getCrimeChance", `Invalid crime: ${crimeRoughName}`);
}
return crime.successRate(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
},
getCrimeStats: function(crimeRoughName) {
updateDynamicRam("getCrimeStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getCrimeStats"));
checkSingularityAccess("getCrimeStats", 3);
const crime = Object(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_9__["findCrime"])(crimeRoughName.toLowerCase());
if(crime == null) {
throw makeRuntimeErrorMsg("getCrimeStats", `Invalid crime: ${crimeRoughName}`);
}
return Object.assign({}, crime);
},
getOwnedAugmentations: function(purchased=false) {
updateDynamicRam("getOwnedAugmentations", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getOwnedAugmentations"));
checkSingularityAccess("getOwnedAugmentations", 3);
var res = [];
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].augmentations.length; ++i) {
res.push(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].augmentations[i].name);
}
if (purchased) {
for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].queuedAugmentations.length; ++i) {
res.push(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].queuedAugmentations[i].name);
}
}
return res;
},
getOwnedSourceFiles: function() {
updateDynamicRam("getOwnedSourceFiles", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getOwnedSourceFiles"));
checkSingularityAccess("getOwnedSourceFiles", 3);
let res = [];
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sourceFiles.length; ++i) {
res.push({n: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sourceFiles[i].n, lvl: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sourceFiles[i].lvl});
}
return res;
},
getAugmentationsFromFaction: function(facname) {
updateDynamicRam("getAugmentationsFromFaction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getAugmentationsFromFaction"));
checkSingularityAccess("getAugmentationsFromFaction", 3);
const faction = getFaction("getAugmentationsFromFaction", facname);
// If player has a gang with this faction, return all augmentations.
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasGangWith(facname)) {
const res = [];
for (const augName in _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"]) {
const aug = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"][augName];
if (!aug.isSpecial) {
res.push(augName);
}
}
return res;
}
return faction.augmentations.slice();
},
getAugmentationPrereq: function(name) {
updateDynamicRam("getAugmentationPrereq", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getAugmentationPrereq"));
checkSingularityAccess("getAugmentationPrereq", 3);
const aug = getAugmentation("getAugmentationPrereq", name);
return aug.prereqs.slice();
},
getAugmentationCost: function(name) {
updateDynamicRam("getAugmentationCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getAugmentationCost"));
checkSingularityAccess("getAugmentationCost", 3);
const aug = getAugmentation("getAugmentationCost", name);
return [aug.baseRepRequirement, aug.baseCost];
},
getAugmentationStats: function(name) {
updateDynamicRam("getAugmentationStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("getAugmentationStats"));
checkSingularityAccess("getAugmentationStats", 3);
const aug = getAugmentation("getAugmentationStats", name);
return Object.assign({}, aug.mults);
},
purchaseAugmentation: function(faction, name) {
updateDynamicRam("purchaseAugmentation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("purchaseAugmentation"));
checkSingularityAccess("purchaseAugmentation", 3);
const fac = getFaction("purchaseAugmentation", faction);
const aug = getAugmentation("purchaseAugmentation", name);
let augs = [];
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hasGangWith(faction)) {
for (const augName in _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"]) {
const tempAug = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"][augName];
if (!tempAug.isSpecial) {
augs.push(augName);
}
}
} else {
augs = fac.augmentations;
}
if (!augs.includes(name)) {
workerScript.log("purchaseAugmentation", `Faction '${faction}' does not have the '${name}' augmentation.`);
return false;
}
const isNeuroflux = (aug.name === _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_7__["AugmentationNames"].NeuroFluxGovernor);
if (!isNeuroflux) {
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].queuedAugmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].queuedAugmentations[j].name === aug.name) {
workerScript.log("purchaseAugmentation", `You already have the '${name}' augmentation.`);
return false;
}
}
for (let j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].augmentations.length; ++j) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].augmentations[j].name === aug.name) {
workerScript.log("purchaseAugmentation", `You already have the '${name}' augmentation.`);
return false;
}
}
}
if (fac.playerReputation < aug.baseRepRequirement) {
workerScript.log("purchaseAugmentation", `You do not have enough reputation with '${fac.name}'.`);
return false;
}
const res = Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_24__["purchaseAugmentation"])(aug, fac, true);
workerScript.log("purchaseAugmentation", res);
if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_75__["isString"])(res) && res.startsWith("You purchased")) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
return true;
} else {
return false;
}
},
softReset: function(cbScript) {
updateDynamicRam("softReset", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("softReset"));
checkSingularityAccess("softReset", 3);
workerScript.log("softReset", "Soft resetting. This will cause this script to be killed");
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70__["setTimeoutRef"])(() => {
Object(_Prestige__WEBPACK_IMPORTED_MODULE_6__[/* prestigeAugmentation */ "a"])();
runAfterReset(cbScript);
}, 0);
// Prevent workerScript from "finishing execution naturally"
workerScript.running = false;
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(workerScript);
},
installAugmentations: function(cbScript) {
updateDynamicRam("installAugmentations", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("installAugmentations"));
checkSingularityAccess("installAugmentations", 3);
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].queuedAugmentations.length === 0) {
workerScript.log("installAugmentations", "You do not have any Augmentations to be installed.");
return false;
}
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_15__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
workerScript.log("installAugmentations", "Installing Augmentations. This will cause this script to be killed");
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_70__["setTimeoutRef"])(() => {
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_5__[/* installAugmentations */ "e"])();
runAfterReset(cbScript);
}, 0);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
Object(_Netscript_killWorkerScript__WEBPACK_IMPORTED_MODULE_60__["killWorkerScript"])(workerScript);
},
// Gang API
gang: {
createGang: function(faction) {
updateDynamicRam("createGang", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "createGang"));
// this list is copied from Faction/ui/Root.tsx
const GangNames = [
"Slum Snakes",
"Tetrads",
"The Syndicate",
"The Dark Army",
"Speakers for the Dead",
"NiteSec",
"The Black Hand",
];
if(!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].canAccessGang() || !GangNames.includes(faction)) return false;
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].inGang()) return false;
if(!_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].factions.includes(faction)) return false;
const isHacking = (faction === "NiteSec" || faction === "The Black Hand");
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].startGang(faction, isHacking);
return true;
},
inGang: function() {
updateDynamicRam("inGang", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "inGang"));
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].inGang();
},
getMemberNames: function() {
updateDynamicRam("getMemberNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getMemberNames"));
checkGangApiAccess("getMemberNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.members.map(member => member.name);
},
getGangInformation: function() {
updateDynamicRam("getGangInformation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getGangInformation"));
checkGangApiAccess("getGangInformation");
return {
faction: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.facName,
isHacking: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.isHackingGang,
moneyGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.moneyGainRate,
power: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.getPower(),
respect: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.respect,
respectGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.respectGainRate,
territory: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.getTerritory(),
territoryClashChance: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.territoryClashChance,
territoryWarfareEngaged: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.territoryWarfareEngaged,
wantedLevel: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.wanted,
wantedLevelGainRate: _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.wantedGainRate,
};
},
getOtherGangInformation: function() {
updateDynamicRam("getOtherGangInformation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getOtherGangInformation"));
checkGangApiAccess("getOtherGangInformation");
const cpy = {};
for (const gang in _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"]) {
cpy[gang] = Object.assign({}, _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"][gang]);
}
return cpy;
},
getMemberInformation: function(name) {
updateDynamicRam("getMemberInformation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getMemberInformation"));
checkGangApiAccess("getMemberInformation");
const member = getGangMember("getMemberInformation", name);
return {
name: member.name,
task: member.task,
earnedRespect: member.earnedRespect,
hack: member.hack,
str: member.str,
def: member.def,
dex: member.dex,
agi: member.agi,
cha: member.cha,
hack_exp: member.hack_exp,
str_exp: member.str_exp,
def_exp: member.def_exp,
dex_exp: member.dex_exp,
agi_exp: member.agi_exp,
cha_exp: member.cha_exp,
hack_mult: member.hack_mult,
str_mult: member.str_mult,
def_mult: member.def_mult,
dex_mult: member.dex_mult,
agi_mult: member.agi_mult,
cha_mult: member.cha_mult,
hack_asc_mult: member.calculateAscensionMult(member.hack_asc_points),
str_asc_mult: member.calculateAscensionMult(member.str_asc_points),
def_asc_mult: member.calculateAscensionMult(member.def_asc_points),
dex_asc_mult: member.calculateAscensionMult(member.dex_asc_points),
agi_asc_mult: member.calculateAscensionMult(member.agi_asc_points),
cha_asc_mult: member.calculateAscensionMult(member.cha_asc_points),
hack_asc_points: member.hack_asc_points,
str_asc_points: member.str_asc_points,
def_asc_points: member.def_asc_points,
dex_asc_points: member.dex_asc_points,
agi_asc_points: member.agi_asc_points,
cha_asc_points: member.cha_asc_points,
upgrades: member.upgrades.slice(),
augmentations: member.augmentations.slice(),
}
},
canRecruitMember: function() {
updateDynamicRam("canRecruitMember", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "canRecruitMember"));
checkGangApiAccess("canRecruitMember");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.canRecruitMember();
},
recruitMember: function(name) {
updateDynamicRam("recruitMember", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "recruitMember"));
checkGangApiAccess("recruitMember");
const recruited = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.recruitMember(name);
if (recruited) {
workerScript.log("recruitMember", `Successfully recruited Gang Member '${name}'`);
} else {
workerScript.log("recruitMember", `Failed to recruit Gang Member '${name}'`);
}
return recruited;
},
getTaskNames: function() {
updateDynamicRam("getTaskNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getTaskNames"));
checkGangApiAccess("getTaskNames");
const tasks = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.getAllTaskNames();
tasks.unshift("Unassigned");
return tasks;
},
setMemberTask: function(memberName, taskName) {
updateDynamicRam("setMemberTask", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "setMemberTask"));
checkGangApiAccess("setMemberTask");
const member = getGangMember("setMemberTask", memberName);
const success = member.assignToTask(taskName);
if (success) {
workerScript.log("setMemberTask", `Successfully assigned Gang Member '${memberName}' to '${taskName}' task`);
} else {
workerScript.log("setMemberTask", `Failed to assign Gang Member '${memberName}' to '${taskName}' task. '${memberName}' is now Unassigned`);
}
return success;
},
getTaskStats: function(taskName) {
updateDynamicRam("getTaskStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getTaskStats"));
checkGangApiAccess("getTaskStats");
const task = getGangTask("getTaskStats", taskName);
const copy = Object.assign({}, task);
copy.territory = Object.assign({}, task.territory)
return copy;
},
getEquipmentNames: function() {
updateDynamicRam("getEquipmentNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getEquipmentNames"));
checkGangApiAccess("getEquipmentNames");
return Object.keys(_Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__["GangMemberUpgrades"]);
},
getEquipmentCost: function(equipName) {
updateDynamicRam("getEquipmentCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getEquipmentCost"));
checkGangApiAccess("getEquipmentCost");
const upg = _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__["GangMemberUpgrades"][equipName];
if(upg === null) return Infinity;
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.getUpgradeCost(upg);
},
getEquipmentType: function(equipName) {
updateDynamicRam("getEquipmentType", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getEquipmentType"));
checkGangApiAccess("getEquipmentType");
const upg = _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__["GangMemberUpgrades"][equipName];
if (upg == null) return "";
return upg.getType();
},
getEquipmentStats: function(equipName) {
updateDynamicRam("getEquipmentStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getEquipmentStats"));
checkGangApiAccess("getEquipmentStats");
const equipment = _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__["GangMemberUpgrades"][equipName];
if (!equipment) {
throw makeRuntimeErrorMsg("getEquipmentStats", `Invalid equipment: ${equipName}`);
}
return Object.assign({}, equipment.mults);
},
purchaseEquipment: function(memberName, equipName) {
updateDynamicRam("purchaseEquipment", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "purchaseEquipment"));
checkGangApiAccess("purchaseEquipment");
const member = getGangMember("purchaseEquipment", memberName);
const equipment = _Gang_GangMemberUpgrades__WEBPACK_IMPORTED_MODULE_22__["GangMemberUpgrades"][equipName];
if(!equipment) return false;
const res = member.buyUpgrade(equipment, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"], _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang);
if (res) {
workerScript.log("purchaseEquipment", `Purchased '${equipName}' for Gang member '${memberName}'`);
} else {
workerScript.log("purchaseEquipment", `Failed to purchase '${equipName}' for Gang member '${memberName}'`);
}
return res;
},
ascendMember: function(name) {
updateDynamicRam("ascendMember", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "ascendMember"));
checkGangApiAccess("ascendMember");
const member = getGangMember("ascendMember", name);
if(!member.canAscend()) return;
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.ascendMember(member, workerScript);
},
setTerritoryWarfare: function(engage) {
updateDynamicRam("setTerritoryWarfare", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "setTerritoryWarfare"));
checkGangApiAccess("setTerritoryWarfare");
if (engage) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.territoryWarfareEngaged = true;
workerScript.log("setTerritoryWarfare", "Engaging in Gang Territory Warfare");
} else {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.territoryWarfareEngaged = false;
workerScript.log("setTerritoryWarfare", "Disengaging in Gang Territory Warfare");
}
},
getChanceToWinClash: function(otherGang) {
updateDynamicRam("getChanceToWinClash", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getChanceToWinClash"));
checkGangApiAccess("getChanceToWinClash");
if (_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"][otherGang] == null) {
throw makeRuntimeErrorMsg(`gang.${getChanceToWinClash}`, `Invalid gang: ${otherGang}`);
}
const playerPower = _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"][_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.facName].power;
const otherPower = _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["AllGangs"][otherGang].power;
return playerPower / (otherPower + playerPower);
},
getBonusTime: function() {
updateDynamicRam("getBonusTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("gang", "getBonusTime"));
checkGangApiAccess("getBonusTime");
return Math.round(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gang.storedCycles / 5);
},
}, // end gang namespace
// Bladeburner API
bladeburner: {
getContractNames: function() {
updateDynamicRam("getContractNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getContractNames"));
checkBladeburnerAccess("getContractNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getContractNamesNetscriptFn();
},
getOperationNames: function() {
updateDynamicRam("getOperationNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getOperationNames"));
checkBladeburnerAccess("getOperationNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getOperationNamesNetscriptFn();
},
getBlackOpNames: function() {
updateDynamicRam("getBlackOpNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getBlackOpNames"));
checkBladeburnerAccess("getBlackOpNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getBlackOpNamesNetscriptFn();
},
getBlackOpRank: function(name="") {
updateDynamicRam("getBlackOpRank", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getBlackOpRank"));
checkBladeburnerAccess("getBlackOpRank");
const action = getBladeburnerActionObject("getBlackOpRank", "blackops", name);
return action.reqdRank;
},
getGeneralActionNames: function() {
updateDynamicRam("getGeneralActionNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getGeneralActionNames"));
checkBladeburnerAccess("getGeneralActionNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getGeneralActionNamesNetscriptFn();
},
getSkillNames: function() {
updateDynamicRam("getSkillNames", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getSkillNames"));
checkBladeburnerAccess("getSkillNames");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getSkillNamesNetscriptFn();
},
startAction: function(type="", name="") {
updateDynamicRam("startAction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "startAction"));
checkBladeburnerAccess("startAction");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.startActionNetscriptFn(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], type, name, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.startAction", e);
}
},
stopBladeburnerAction: function() {
updateDynamicRam("stopBladeburnerAction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "stopBladeburnerAction"));
checkBladeburnerAccess("stopBladeburnerAction");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.resetAction();
},
getCurrentAction: function() {
updateDynamicRam("getCurrentAction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getCurrentAction"));
checkBladeburnerAccess("getCurrentAction");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getTypeAndNameFromActionId(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.action);
},
getActionTime: function(type="", name="") {
updateDynamicRam("getActionTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionTime"));
checkBladeburnerAccess("getActionTime");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getActionTimeNetscriptFn(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], type, name, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getActionTime", e);
}
},
getActionEstimatedSuccessChance: function(type="", name="") {
updateDynamicRam("getActionEstimatedSuccessChance", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionEstimatedSuccessChance"));
checkBladeburnerAccess("getActionEstimatedSuccessChance");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getActionEstimatedSuccessChanceNetscriptFn(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], type, name, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getActionEstimatedSuccessChance", e);
}
},
getActionRepGain: function(type="", name="", level) {
updateDynamicRam("getActionRepGain", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionRepGain"));
checkBladeburnerAccess("getActionRepGain");
const action = getBladeburnerActionObject("getActionRepGain", type, name);
let rewardMultiplier;
if (level == null || isNaN(level)) {
rewardMultiplier = Math.pow(action.rewardFac, action.level - 1);
} else {
rewardMultiplier = Math.pow(action.rewardFac, level - 1);
}
return action.rankGain * rewardMultiplier * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_8__["BitNodeMultipliers"].BladeburnerRank;
},
getActionCountRemaining: function(type="", name="") {
updateDynamicRam("getActionCountRemaining", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionCountRemaining"));
checkBladeburnerAccess("getActionCountRemaining");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getActionCountRemaining", e);
}
},
getActionMaxLevel: function(type="", name="") {
updateDynamicRam("getActionMaxLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionMaxLevel"));
checkBladeburnerAccess("getActionMaxLevel");
const action = getBladeburnerActionObject("getActionMaxLevel", type, name);
return action.maxLevel;
},
getActionCurrentLevel: function(type="", name="") {
updateDynamicRam("getActionCurrentLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionCurrentLevel"));
checkBladeburnerAccess("getActionCurrentLevel");
const action = getBladeburnerActionObject("getActionCurrentLevel", type, name);
return action.level;
},
getActionAutolevel: function(type="", name="") {
updateDynamicRam("getActionAutolevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getActionAutolevel"));
checkBladeburnerAccess("getActionAutolevel");
const action = getBladeburnerActionObject("getActionCurrentLevel", type, name);
return action.autoLevel;
},
setActionAutolevel: function(type="", name="", autoLevel=true) {
updateDynamicRam("setActionAutolevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "setActionAutolevel"));
checkBladeburnerAccess("setActionAutolevel");
const action = getBladeburnerActionObject("setActionAutolevel", type, name);
action.autoLevel = autoLevel;
},
setActionLevel: function(type="", name="", level=1) {
updateDynamicRam("setActionLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "setActionLevel"));
checkBladeburnerAccess("setActionLevel");
const action = getBladeburnerActionObject("setActionLevel", type, name);
if(level < 1 || level > action.maxLevel) {
throw makeRuntimeErrorMsg("bladeburner.setActionLevel", `Level must be between 1 and ${action.maxLevel}, is ${level}`)
}
action.level = level;
},
getRank: function() {
updateDynamicRam("getRank", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getRank"));
checkBladeburnerAccess("getRank");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.rank;
},
getSkillPoints: function() {
updateDynamicRam("getSkillPoints", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getSkillPoints"));
checkBladeburnerAccess("getSkillPoints");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.skillPoints;
},
getSkillLevel: function(skillName="") {
updateDynamicRam("getSkillLevel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getSkillLevel"));
checkBladeburnerAccess("getSkillLevel");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getSkillLevel", e);
}
},
getSkillUpgradeCost: function(skillName="") {
updateDynamicRam("getSkillUpgradeCost", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getSkillUpgradeCost"));
checkBladeburnerAccess("getSkillUpgradeCost");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getSkillUpgradeCostNetscriptFn(skillName, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getSkillUpgradeCost", e);
}
},
upgradeSkill: function(skillName) {
updateDynamicRam("upgradeSkill", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "upgradeSkill"));
checkBladeburnerAccess("upgradeSkill");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.upgradeSkillNetscriptFn(skillName, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.upgradeSkill", e);
}
},
getTeamSize: function(type="", name="") {
updateDynamicRam("getTeamSize", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getTeamSize"));
checkBladeburnerAccess("getTeamSize");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.getTeamSize", e);
}
},
setTeamSize: function(type="", name="", size) {
updateDynamicRam("setTeamSize",Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "setTeamSize"));
checkBladeburnerAccess("setTeamSize");
try {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);
} catch(e) {
throw makeRuntimeErrorMsg("bladeburner.setTeamSize", e);
}
},
getCityEstimatedPopulation: function(cityName) {
updateDynamicRam("getCityEstimatedPopulation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getCityEstimatedPopulation"));
checkBladeburnerAccess("getCityEstimatedPopulation");
checkBladeburnerCity("getCityEstimatedPopulation", cityName);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.cities[cityName].popEst;
},
getCityEstimatedCommunities: function(cityName) {
updateDynamicRam("getCityEstimatedCommunities", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getCityEstimatedCommunities"));
checkBladeburnerAccess("getCityEstimatedCommunities");
checkBladeburnerCity("getCityEstimatedCommunities", cityName);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.cities[cityName].commsEst;
},
getCityChaos: function(cityName) {
updateDynamicRam("getCityChaos", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getCityChaos"));
checkBladeburnerAccess("getCityChaos");
checkBladeburnerCity("getCityChaos", cityName);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.cities[cityName].chaos;
},
getCity: function() {
updateDynamicRam("getCity", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getCity"));
checkBladeburnerAccess("getCityChaos");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.city;
},
switchCity: function(cityName) {
updateDynamicRam("switchCity", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "switchCity"));
checkBladeburnerAccess("switchCity");
checkBladeburnerCity("switchCity", cityName);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.city = cityName;
},
getStamina: function() {
updateDynamicRam("getStamina", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getStamina"));
checkBladeburnerAccess("getStamina");
return [_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.stamina, _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.maxStamina];
},
joinBladeburnerFaction: function() {
updateDynamicRam("joinBladeburnerFaction", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "joinBladeburnerFaction"));
checkBladeburnerAccess("joinBladeburnerFaction", true);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);
},
joinBladeburnerDivision: function() {
updateDynamicRam("joinBladeburnerDivision", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "joinBladeburnerDivision"));
checkBladeburnerAccess("joinBladeburnerDivision", true);
if ((_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN === 7 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_48__["SourceFileFlags"][7] > 0)) {
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bitNodeN === 8) { return false; }
if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10__["Bladeburner"]) {
return true; // Already member
} else if (_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].defense >= 100 &&
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].agility >= 100) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner = new _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_10__["Bladeburner"](_Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
workerScript.log("joinBladeburnerDivision", "You have been accepted into the Bladeburner division");
const worldHeader = document.getElementById("world-menu-header");
if (worldHeader instanceof HTMLElement) {
worldHeader.click(); worldHeader.click();
}
return true;
} else {
workerScript.log("joinBladeburnerDivision", "You do not meet the requirements for joining the Bladeburner division");
return false;
}
}
},
getBonusTime: function() {
updateDynamicRam("getBonusTime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("bladeburner", "getBonusTime"));
checkBladeburnerAccess("getBonusTime");
return Math.round(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].bladeburner.storedCycles / 5);
},
}, // End Bladeburner
// Coding Contract API
codingcontract: {
attempt: function(answer, fn, ip=workerScript.serverIp, { returnReward } = {}) {
updateDynamicRam("attempt", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("codingcontract", "attempt"));
const contract = getCodingContract("attempt", ip, fn);
// Convert answer to string. If the answer is a 2D array, then we have to
// manually add brackets for the inner arrays
if (Object(_utils_helpers_is2DArray__WEBPACK_IMPORTED_MODULE_71__["is2DArray"])(answer)) {
let answerComponents = [];
for (let i = 0; i < answer.length; ++i) {
answerComponents.push(["[", answer[i].toString(), "]"].join(""));
}
answer = answerComponents.join(",");
} else {
answer = String(answer);
}
const serv = safeGetServer(ip, "codingcontract.attempt");
if (contract.isSolution(answer)) {
const reward = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].gainCodingContractReward(contract.reward, contract.getDifficulty());
workerScript.log("attempt", `Successfully completed Coding Contract '${fn}'. Reward: ${reward}`);
serv.removeContract(fn);
return returnReward ? reward : true;
} else {
++contract.tries;
if (contract.tries >= contract.getMaxNumTries()) {
workerScript.log("attempt", `Coding Contract attempt '${fn}' failed. Contract is now self-destructing`);
serv.removeContract(fn);
} else {
workerScript.log("attempt", `Coding Contract attempt '${fn}' failed. ${contract.getMaxNumTries() - contract.tries} attempts remaining.`);
}
return returnReward ? "" : false;
}
},
getContractType: function(fn, ip=workerScript.serverIp) {
updateDynamicRam("getContractType", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("codingcontract", "getContractType"));
const contract = getCodingContract("getContractType", ip, fn);
return contract.getType();
},
getData: function(fn, ip=workerScript.serverIp) {
updateDynamicRam("getData", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("codingcontract", "getData"));
const contract = getCodingContract("getData", ip, fn);
const data = contract.getData();
if (data.constructor === Array) {
// For two dimensional arrays, we have to copy the internal arrays using
// slice() as well. As of right now, no contract has arrays that have
// more than two dimensions
const copy = data.slice();
for (let i = 0; i < copy.length; ++i) {
if (data[i].constructor === Array) {
copy[i] = data[i].slice();
}
}
return copy;
} else {
return data;
}
},
getDescription: function(fn, ip=workerScript.serverIp) {
updateDynamicRam("getDescription", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("codingcontract", "getDescription"));
const contract = getCodingContract("getDescription", ip, fn);
return contract.getDescription();
},
getNumTriesRemaining: function(fn, ip=workerScript.serverIp) {
updateDynamicRam("getNumTriesRemaining", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("codingcontract", "getNumTriesRemaining"));
const contract = getCodingContract("getNumTriesRemaining", ip, fn);
return contract.getMaxNumTries() - contract.tries;
},
}, // End coding contracts
// Duplicate Sleeve API
sleeve: {
getNumSleeves: function() {
updateDynamicRam("getNumSleeves", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getNumSleeves"));
checkSleeveAPIAccess("getNumSleeves");
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves.length;
},
setToShockRecovery: function(sleeveNumber=0) {
updateDynamicRam("setToShockRecovery", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToShockRecovery"));
checkSleeveAPIAccess("setToShockRecovery");
checkSleeveNumber("setToShockRecovery", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].shockRecovery(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
},
setToSynchronize: function(sleeveNumber=0) {
updateDynamicRam("setToSynchronize", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToSynchronize"));
checkSleeveAPIAccess("setToSynchronize");
checkSleeveNumber("setToSynchronize", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].synchronize(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
},
setToCommitCrime: function(sleeveNumber=0, crimeName="") {
updateDynamicRam("setToCommitCrime", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToCommitCrime"));
checkSleeveAPIAccess("setToCommitCrime");
checkSleeveNumber("setToCommitCrime", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].commitCrime(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], crimeName);
},
setToUniversityCourse: function(sleeveNumber=0, universityName="", className="") {
updateDynamicRam("setToUniversityCourse", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToUniversityCourse"));
checkSleeveAPIAccess("setToUniversityCourse");
checkSleeveNumber("setToUniversityCourse", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].takeUniversityCourse(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], universityName, className);
},
travel: function(sleeveNumber=0, cityName="") {
updateDynamicRam("travel", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "travel"));
checkSleeveAPIAccess("travel");
checkSleeveNumber("travel", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].travel(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], cityName);
},
setToCompanyWork: function(sleeveNumber=0, companyName="") {
updateDynamicRam("setToCompanyWork", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToCompanyWork"));
checkSleeveAPIAccess("setToCompanyWork");
checkSleeveNumber("setToCompanyWork", sleeveNumber);
// Cannot work at the same company that another sleeve is working at
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves.length; ++i) {
if (i === sleeveNumber) { continue; }
const other = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[i];
if (other.currentTask === _PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65__["SleeveTaskType"].Company && other.currentTaskLocation === companyName) {
throw makeRuntimeErrorMsg("sleeve.setToFactionWork", `Sleeve ${sleeveNumber} cannot work for company ${companyName} because Sleeve ${i} is already working for them.`)
}
}
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].workForCompany(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], companyName);
},
setToFactionWork: function(sleeveNumber=0, factionName="", workType="") {
updateDynamicRam("setToFactionWork", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToFactionWork"));
checkSleeveAPIAccess("setToFactionWork");
checkSleeveNumber("setToFactionWork", sleeveNumber);
// Cannot work at the same faction that another sleeve is working at
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves.length; ++i) {
if (i === sleeveNumber) { continue; }
const other = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[i];
if (other.currentTask === _PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65__["SleeveTaskType"].Faction && other.currentTaskLocation === factionName) {
throw makeRuntimeErrorMsg("sleeve.setToFactionWork", `Sleeve ${sleeveNumber} cannot work for faction ${factionName} because Sleeve ${i} is already working for them.`)
}
}
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].workForFaction(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], factionName, workType);
},
setToGymWorkout: function(sleeveNumber=0, gymName="", stat="") {
updateDynamicRam("setToGymWorkout", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "setToGymWorkout"));
checkSleeveAPIAccess("setToGymWorkout");
checkSleeveNumber("setToGymWorkout", sleeveNumber);
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].workoutAtGym(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], gymName, stat);
},
getSleeveStats: function(sleeveNumber=0) {
updateDynamicRam("getSleeveStats", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getSleeveStats"));
checkSleeveAPIAccess("getSleeveStats");
checkSleeveNumber("getSleeveStats", sleeveNumber);
const sl = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber];
return {
shock: 100 - sl.shock,
sync: sl.sync,
hacking_skill: sl.hacking_skill,
strength: sl.strength,
defense: sl.defense,
dexterity: sl.dexterity,
agility: sl.agility,
charisma: sl.charisma,
};
},
getTask: function(sleeveNumber=0) {
updateDynamicRam("getTask", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getTask"));
checkSleeveAPIAccess("getTask");
checkSleeveNumber("getTask", sleeveNumber);
const sl = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber];
return {
task: _PersonObjects_Sleeve_SleeveTaskTypesEnum__WEBPACK_IMPORTED_MODULE_65__["SleeveTaskType"][sl.currentTask],
crime: sl.crimeType,
location: sl.currentTaskLocation,
gymStatType: sl.gymStatType,
factionWorkType: _Faction_FactionWorkTypeEnum__WEBPACK_IMPORTED_MODULE_25__["FactionWorkType"][sl.factionWorkType],
};
},
getInformation: function(sleeveNumber=0) {
updateDynamicRam("getInformation", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getInformation"));
checkSleeveAPIAccess("getInformation");
checkSleeveNumber("getInformation", sleeveNumber);
const sl = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber];
return {
city: sl.city,
hp: sl.hp,
jobs: Object.keys(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs), // technically sleeves have the same jobs as the player.
jobTitle: Object.values(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].jobs),
maxHp: sl.max_hp,
tor: _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_47__["SpecialServerIps"].hasOwnProperty("Darkweb Server"), // There's no reason not to give that infomation here as well. Worst case scenario it isn't used.
mult: {
agility: sl.agility_mult,
agilityExp: sl.agility_exp_mult,
companyRep: sl.company_rep_mult,
crimeMoney: sl.crime_money_mult,
crimeSuccess: sl.crime_success_mult,
defense: sl.defense_mult,
defenseExp: sl.defense_exp_mult,
dexterity: sl.dexterity_mult,
dexterityExp: sl.dexterity_exp_mult,
factionRep: sl.faction_rep_mult,
hacking: sl.hacking_mult,
hackingExp: sl.hacking_exp_mult,
strength: sl.strength_mult,
strengthExp: sl.strength_exp_mult,
workMoney: sl.work_money_mult,
},
timeWorked: sl.currentTaskTime,
earningsForSleeves : {
workHackExpGain: sl.earningsForSleeves.hack,
workStrExpGain: sl.earningsForSleeves.str,
workDefExpGain: sl.earningsForSleeves.def,
workDexExpGain: sl.earningsForSleeves.dex,
workAgiExpGain: sl.earningsForSleeves.agi,
workChaExpGain: sl.earningsForSleeves.cha,
workMoneyGain: sl.earningsForSleeves.money,
},
earningsForPlayer : {
workHackExpGain: sl.earningsForPlayer.hack,
workStrExpGain: sl.earningsForPlayer.str,
workDefExpGain: sl.earningsForPlayer.def,
workDexExpGain: sl.earningsForPlayer.dex,
workAgiExpGain: sl.earningsForPlayer.agi,
workChaExpGain: sl.earningsForPlayer.cha,
workMoneyGain: sl.earningsForPlayer.money,
},
earningsForTask : {
workHackExpGain: sl.earningsForTask.hack,
workStrExpGain: sl.earningsForTask.str,
workDefExpGain: sl.earningsForTask.def,
workDexExpGain: sl.earningsForTask.dex,
workAgiExpGain: sl.earningsForTask.agi,
workChaExpGain: sl.earningsForTask.cha,
workMoneyGain: sl.earningsForTask.money,
},
workRepGain: sl.getRepGain(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"]),
}
},
getSleeveAugmentations: function(sleeveNumber=0) {
updateDynamicRam("getSleeveAugmentations", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getSleeveAugmentations"));
checkSleeveAPIAccess("getSleeveAugmentations");
checkSleeveNumber("getSleeveAugmentations", sleeveNumber);
const augs = [];
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].augmentations.length; i++) {
augs.push(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].augmentations[i].name);
}
return augs;
},
getSleevePurchasableAugs: function(sleeveNumber=0) {
updateDynamicRam("getSleevePurchasableAugs", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "getSleevePurchasableAugs"));
checkSleeveAPIAccess("getSleevePurchasableAugs");
checkSleeveNumber("getSleevePurchasableAugs", sleeveNumber);
const purchasableAugs = Object(_PersonObjects_Sleeve_SleeveHelpers__WEBPACK_IMPORTED_MODULE_66__["findSleevePurchasableAugs"])(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber], _Player__WEBPACK_IMPORTED_MODULE_38__["Player"]);
const augs = [];
for (let i = 0; i < purchasableAugs.length; i++) {
const aug = purchasableAugs[i];
augs.push({
name: aug.name,
cost: aug.startingCost,
});
}
return augs;
},
purchaseSleeveAug: function(sleeveNumber=0, augName="") {
updateDynamicRam("purchaseSleeveAug", Object(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_2__["getRamCost"])("sleeve", "purchaseSleeveAug"));
checkSleeveAPIAccess("purchaseSleeveAug");
checkSleeveNumber("purchaseSleeveAug", sleeveNumber);
const aug = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_4__["Augmentations"][augName];
if (!aug) {
throw makeRuntimeErrorMsg("sleeve.purchaseSleeveAug", `Invalid aug: ${augName}`)
}
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].sleeves[sleeveNumber].tryBuyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_38__["Player"], aug);
},
}, // End sleeve
formulas: {
basic: {
calculateSkill: function(exp, mult = 1) {
checkFormulasAccess("basic.calculateSkill", 5);
return Object(_PersonObjects_formulas_skill__WEBPACK_IMPORTED_MODULE_35__["calculateSkill"])(exp, mult);
},
calculateExp: function(skill, mult = 1) {
checkFormulasAccess("basic.calculateExp", 5);
return Object(_PersonObjects_formulas_skill__WEBPACK_IMPORTED_MODULE_35__["calculateExp"])(skill, mult);
},
hackChance: function(server, player) {
checkFormulasAccess("basic.hackChance", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingChance"])(server, player);
},
hackExp: function(server, player) {
checkFormulasAccess("basic.hackExp", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingExpGain"])(server, player);
},
hackPercent: function(server, player) {
checkFormulasAccess("basic.hackPercent", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculatePercentMoneyHacked"])(server, player);
},
growPercent: function(server, threads, player, cores = 1) {
checkFormulasAccess("basic.growPercent", 5);
return Object(_Server_formulas_grow__WEBPACK_IMPORTED_MODULE_18__["calculateServerGrowth"])(server, threads, player, cores);
},
hackTime: function(server, player) {
checkFormulasAccess("basic.hackTime", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateHackingTime"])(server, player);
},
growTime: function(server, player) {
checkFormulasAccess("basic.growTime", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateGrowTime"])(server, player);
},
weakenTime: function(server, player) {
checkFormulasAccess("basic.weakenTime", 5);
return Object(_Hacking__WEBPACK_IMPORTED_MODULE_17__["calculateWeakenTime"])(server, player);
},
},
hacknetNodes: {
moneyGainRate: function(level, ram, cores, mult=1) {
checkFormulasAccess("hacknetNodes.moneyGainRate", 5);
return Object(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__["calculateMoneyGainRate"])(level, ram, cores, mult);
},
levelUpgradeCost: function(startingLevel, extraLevels=1, costMult=1) {
checkFormulasAccess("hacknetNodes.levelUpgradeCost", 5);
return Object(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__["calculateLevelUpgradeCost"])(startingLevel, extraLevels, costMult);
},
ramUpgradeCost: function(startingRam, extraLevels=1, costMult=1) {
checkFormulasAccess("hacknetNodes.ramUpgradeCost", 5);
return Object(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__["calculateRamUpgradeCost"])(startingRam, extraLevels, costMult);
},
coreUpgradeCost: function(startingCore, extraCores=1, costMult=1) {
checkFormulasAccess("hacknetNodes.coreUpgradeCost", 5);
return Object(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__["calculateCoreUpgradeCost"])(startingCore, extraCores, costMult);
},
hacknetNodeCost: function(n, mult) {
checkFormulasAccess("hacknetNodes.hacknetNodeCost", 5);
return Object(_Hacknet_formulas_HacknetNodes__WEBPACK_IMPORTED_MODULE_28__["calculateNodeCost"])(n, mult);
},
constants: function() {
checkFormulasAccess("hacknetNodes.constants", 5);
return Object.assign({}, _Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30__["HacknetNodeConstants"]);
},
},
hacknetServers: {
hashGainRate: function(level, ramUsed, maxRam, cores, mult=1) {
checkFormulasAccess("hacknetServers.hashGainRate", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateHashGainRate"])(level, ramUsed, maxRam, cores, mult);
},
levelUpgradeCost: function(startingLevel, extraLevels=1, costMult=1) {
checkFormulasAccess("hacknetServers.levelUpgradeCost", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateLevelUpgradeCost"])(startingLevel, extraLevels, costMult);
},
ramUpgradeCost: function(startingRam, extraLevels=1, costMult=1) {
checkFormulasAccess("hacknetServers.ramUpgradeCost", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateRamUpgradeCost"])(startingRam, extraLevels, costMult);
},
coreUpgradeCost: function(startingCore, extraCores=1, costMult=1) {
checkFormulasAccess("hacknetServers.coreUpgradeCost", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateCoreUpgradeCost"])(startingCore, extraCores, costMult);
},
cacheUpgradeCost: function(startingCache, extraCache=1, costMult=1) {
checkFormulasAccess("hacknetServers.cacheUpgradeCost", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateCacheUpgradeCost"])(startingCache, extraCache, costMult);
},
hashUpgradeCost: function(upgName, level) {
checkFormulasAccess("hacknetServers.hashUpgradeCost", 9);
const upg = _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].hashManager.getUpgrade(upgName);
if(!upg) {
throw makeRuntimeErrorMsg("formulas.hacknetServers.calculateHashUpgradeCost", `Invalid Hash Upgrade: ${upgName}`);
}
return upg.getCost(level);
},
hacknetServerCost: function(n, mult) {
checkFormulasAccess("hacknetServers.hacknetServerCost", 9);
return Object(_Hacknet_formulas_HacknetServers__WEBPACK_IMPORTED_MODULE_29__["calculateServerCost"])(n, mult);
},
constants: function() {
checkFormulasAccess("hacknetServers.constants", 9);
return Object.assign({}, _Hacknet_data_Constants__WEBPACK_IMPORTED_MODULE_30__["HacknetServerConstants"]);
},
},
}, // end formulas
heart: {
// Easter egg function
break: function() {
return _Player__WEBPACK_IMPORTED_MODULE_38__["Player"].karma;
},
},
exploit: function() {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].giveExploit(_Exploits_Exploit_ts__WEBPACK_IMPORTED_MODULE_67__["Exploit"].UndocumentedFunctionCall);
},
bypass: function(doc) {
// reset both fields first
doc.completely_unused_field = undefined;
document.completely_unused_field = undefined;
// set one to true and check that it affected the other.
document.completely_unused_field = true;
if(doc.completely_unused_field && workerScript.ramUsage === 1.6) {
_Player__WEBPACK_IMPORTED_MODULE_38__["Player"].giveExploit(_Exploits_Exploit_ts__WEBPACK_IMPORTED_MODULE_67__["Exploit"].Bypass);
}
doc.completely_unused_field = undefined;
document.completely_unused_field = undefined;
},
flags: function(data) {
data = toNative(data);
// We always want the help flag.
const args = {};
for(const d of data) {
let t = String;
if(typeof d[1] === 'number') {
t = Number;
} else if(typeof d[1] === 'boolean') {
t = Boolean;
} else if(Array.isArray(d[1])) {
t = [String];
}
const numDashes = d[0].length > 1 ? 2 : 1;
args['-'.repeat(numDashes)+d[0]] = t
}
const ret = arg__WEBPACK_IMPORTED_MODULE_1__(args, {argv: workerScript.args});
for(const d of data) {
if(!ret.hasOwnProperty('--'+d[0]) || !ret.hasOwnProperty('-'+d[0])) ret[d[0]] = d[1];
}
for(const key of Object.keys(ret)) {
if(!key.startsWith('-')) continue;
const value = ret[key];
delete ret[key];
const numDashes = key.length === 2 ? 1 : 2;
ret[key.slice(numDashes)] = value;
}
return ret;
},
}
function getFunctionNames(obj) {
const functionNames = [];
for(const [key, value] of Object.entries(obj)){
if(typeof(value)=="function"){
functionNames.push(key);
}else if(typeof(value)=="object"){
functionNames.push(...getFunctionNames(value));
}
}
return functionNames;
}
const possibleLogs = Object.fromEntries(["ALL", ...getFunctionNames(functions)].map(a => [a, true]))
return functions;
} // End NetscriptFunction()
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 143)))
/***/ }),
/* 447 */
/*!******************************!*\
!*** ./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 acorn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! acorn */ 104);
/**
* @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 = acorn__WEBPACK_IMPORTED_MODULE_0__[/* parse */ "b"](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 = acorn__WEBPACK_IMPORTED_MODULE_0__[/* parse */ "b"](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 = acorn__WEBPACK_IMPORTED_MODULE_0__[/* parse */ "b"](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 = acorn__WEBPACK_IMPORTED_MODULE_0__[/* parse */ "b"]('(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 = acorn__WEBPACK_IMPORTED_MODULE_0__[/* parse */ "b"](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;};
/***/ }),
/* 448 */
/*!***********************************!*\
!*** ./src/ui/React/HashRate.tsx ***!
\***********************************/
/*! no static exports found */
/*! exports used: HashRate */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashRate = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Hashes_1 = __webpack_require__(/*! ../../ui/React/Hashes */ 126);
function HashRate(hashes) {
return Hashes_1.Hashes(`${numeralFormat_1.numeralWrapper.formatHashes(hashes)} / sec`);
}
exports.HashRate = HashRate;
/***/ }),
/* 449 */
/*!*********************************!*\
!*** ./src/Hacknet/ui/Root.jsx ***!
\*********************************/
/*! exports provided: PurchaseMultipliers, HacknetRoot */
/*! exports used: HacknetRoot, PurchaseMultipliers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PurchaseMultipliers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HacknetRoot; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _GeneralInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./GeneralInfo */ 789);
/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./HacknetNode */ 788);
/* harmony import */ var _HacknetServer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./HacknetServer */ 787);
/* harmony import */ var _HashUpgradePopup__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./HashUpgradePopup */ 786);
/* harmony import */ var _MultiplierButtons__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./MultiplierButtons */ 785);
/* harmony import */ var _PlayerInfo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./PlayerInfo */ 784);
/* harmony import */ var _PurchaseButton__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./PurchaseButton */ 783);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _ui_React_createPopup__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
/* harmony import */ var _ui_React_createPopup__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_ui_React_createPopup__WEBPACK_IMPORTED_MODULE_11__);
/**
* Root React Component for the Hacknet Node UI
*/
const PurchaseMultipliers = Object.freeze({
"x1": 1,
"x5": 5,
"x10": 10,
"MAX": "MAX"
});
class HacknetRoot extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
constructor(props) {
super(props);
this.state = {
purchaseMultiplier: PurchaseMultipliers.x1,
totalProduction: 0 // Total production ($ / s) of Hacknet Nodes
};
this.createHashUpgradesPopup = this.createHashUpgradesPopup.bind(this);
this.handlePurchaseButtonClick = this.handlePurchaseButtonClick.bind(this);
this.recalculateTotalProduction = this.recalculateTotalProduction.bind(this);
}
componentDidMount() {
this.recalculateTotalProduction();
}
createHashUpgradesPopup() {
const id = "hacknet-server-hash-upgrades-popup";
Object(_ui_React_createPopup__WEBPACK_IMPORTED_MODULE_11__["createPopup"])(id, _HashUpgradePopup__WEBPACK_IMPORTED_MODULE_4__[/* HashUpgradePopup */ "a"], {
popupId: id,
rerender: this.createHashUpgradesPopup
});
}
handlePurchaseButtonClick() {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* purchaseHacknet */ "m"])() >= 0) {
this.recalculateTotalProduction();
}
}
recalculateTotalProduction() {
let total = 0;
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.length; ++i) {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* hasHacknetServers */ "h"])()) {
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][_Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes[i]];
if (hserver) {
total += hserver.hashRate;
} else {
console.warn(`Could not find Hacknet Server object in AllServers map (i=${i})`);
}
} else {
total += _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes[i].moneyGainRatePerSecond;
}
}
this.setState({
totalProduction: total
});
}
setPurchaseMultiplier(mult) {
this.setState({
purchaseMultiplier: mult
});
}
render() {
// Cost to purchase a new Hacknet Node
let purchaseCost;
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* hasHacknetServers */ "h"])()) {
purchaseCost = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* getCostOfNextHacknetServer */ "c"])();
} else {
purchaseCost = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* getCostOfNextHacknetNode */ "b"])();
} // onClick event handlers for purchase multiplier buttons
const purchaseMultiplierOnClicks = [this.setPurchaseMultiplier.bind(this, PurchaseMultipliers.x1), this.setPurchaseMultiplier.bind(this, PurchaseMultipliers.x5), this.setPurchaseMultiplier.bind(this, PurchaseMultipliers.x10), this.setPurchaseMultiplier.bind(this, PurchaseMultipliers.MAX)]; // HacknetNode components
const nodes = _Player__WEBPACK_IMPORTED_MODULE_9__["Player"].hacknetNodes.map(node => {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* hasHacknetServers */ "h"])()) {
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_10__["AllServers"][node];
if (hserver == null) {
throw new Error(`Could not find Hacknet Server object in AllServers map for IP: ${node}`);
}
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_HacknetServer__WEBPACK_IMPORTED_MODULE_3__[/* HacknetServer */ "a"], {
key: hserver.hostname,
node: hserver,
purchaseMultiplier: this.state.purchaseMultiplier,
recalculate: this.recalculateTotalProduction
});
} else {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_HacknetNode__WEBPACK_IMPORTED_MODULE_2__[/* HacknetNode */ "a"], {
key: node.name,
node: node,
purchaseMultiplier: this.state.purchaseMultiplier,
recalculate: this.recalculateTotalProduction
});
}
});
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", null, "Hacknet ", Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* hasHacknetServers */ "h"])() ? "Servers" : "Nodes"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_GeneralInfo__WEBPACK_IMPORTED_MODULE_1__[/* GeneralInfo */ "a"], null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_PurchaseButton__WEBPACK_IMPORTED_MODULE_7__[/* PurchaseButton */ "a"], {
cost: purchaseCost,
multiplier: this.state.purchaseMultiplier,
onClick: this.handlePurchaseButtonClick
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
id: "hacknet-nodes-money-multipliers-div"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_PlayerInfo__WEBPACK_IMPORTED_MODULE_6__[/* PlayerInfo */ "a"], {
totalProduction: this.state.totalProduction
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MultiplierButtons__WEBPACK_IMPORTED_MODULE_5__[/* MultiplierButtons */ "a"], {
onClicks: purchaseMultiplierOnClicks,
purchaseMultiplier: this.state.purchaseMultiplier
})), Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_8__[/* hasHacknetServers */ "h"])() && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: "std-button",
onClick: this.createHashUpgradesPopup,
style: {
display: "block"
}
}, "Spend Hashes on Upgrades"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", {
id: "hacknet-nodes-list"
}, nodes));
}
}
/***/ }),
/* 450 */
/*!******************************!*\
!*** ./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 */ 15);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/SetTimeoutRef */ 76);
/* harmony import */ var _utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 149);
/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 91);
/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/helpers/isString */ 72);
/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__);
let cinematicTextFlag = false;
/**
* Print a message using a hacking-style "typing" effect.
* Note that this clears the UI so that the text from this is the only thing visible.
*
* @param lines {string[]} Array of strings to print, where each element is a separate line
*/
function writeCinematicText(lines) {
cinematicTextFlag = true;
if (lines.constructor !== Array) {
throw new Error("Invalid non-array argument passed into writeCinematicText()");
}
// Reuse the 'Red Pill' content
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCinematicTextContent();
const container = document.getElementById("cinematic-text-container");
container.style.width = "75%";
if (container == null) {throw new Error("Could not find cinematic-text-container for writeCinematicText()");}
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_2__["removeChildrenFromElement"])(container);
for (let i = 0; i < lines.length; ++i) {
if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_5__["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_4__["exceptionAlert"])(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) {
const container = document.getElementById("cinematic-text-container");
const pElem = document.createElement("p");
container.appendChild(pElem);
const 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) {
Object(_utils_SetTimeoutRef__WEBPACK_IMPORTED_MODULE_1__["setTimeoutRef"])(function() {
const textToShow = line.substring(0, i);
if (i >= line.length) {
pElem.innerHTML = textToShow;
return resolve(true);
}
pElem.innerHTML = textToShow + " █ ";
const 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_3__["createElement"])("br"));
return new Promise (function(resolve) {
container.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_3__["createElement"])("a", {
class:"a-link-button", innerText:"Continue...",
clickListener:()=>{
Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_2__["removeChildrenFromElement"])(container);
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
mainMenu.style.visibility = "visible";
cinematicTextFlag = false;
resolve();
},
}));
});
}
/***/ }),
/* 451 */
/*!***********************************************!*\
!*** ./src/PersonObjects/Sleeve/SleeveUI.tsx ***!
\***********************************************/
/*! no static exports found */
/*! exports used: clearSleevesPage, createSleevesPage, updateSleevesPage */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearSleevesPage = exports.updateSleevesPage = exports.createSleevesPage = void 0;
/**
* Module for handling the Sleeve UI
*/
const SleeveAugmentationsUI_1 = __webpack_require__(/*! ./SleeveAugmentationsUI */ 875);
const SleeveTaskTypesEnum_1 = __webpack_require__(/*! ./SleeveTaskTypesEnum */ 242);
const SleeveFaq_1 = __webpack_require__(/*! ./data/SleeveFaq */ 874);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
const FactionWorkTypeEnum_1 = __webpack_require__(/*! ../../Faction/FactionWorkTypeEnum */ 410);
const Crimes_1 = __webpack_require__(/*! ../../Crime/Crimes */ 169);
const Cities_1 = __webpack_require__(/*! ../../Locations/Cities */ 192);
const CityNames_1 = __webpack_require__(/*! ../../Locations/data/CityNames */ 42);
const LocationNames_1 = __webpack_require__(/*! ../../Locations/data/LocationNames */ 40);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const navigationTracking_1 = __webpack_require__(/*! ../../ui/navigationTracking */ 18);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const exceptionAlert_1 = __webpack_require__(/*! ../../../utils/helpers/exceptionAlert */ 91);
const clearEventListeners_1 = __webpack_require__(/*! ../../../utils/uiHelpers/clearEventListeners */ 49);
const createElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createElement */ 51);
const createOptionElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createOptionElement */ 540);
const createPopup_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createPopup */ 129);
const createPopupCloseButton_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createPopupCloseButton */ 468);
const getSelectData_1 = __webpack_require__(/*! ../../../utils/uiHelpers/getSelectData */ 491);
const removeChildrenFromElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeChildrenFromElement */ 149);
const removeElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElement */ 224);
const removeElementById_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElementById */ 90);
const EarningsTableElement_1 = __webpack_require__(/*! ./ui/EarningsTableElement */ 873);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const MoneyRate_1 = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
const ReputationRate_1 = __webpack_require__(/*! ../../ui/React/ReputationRate */ 441);
const StatsElement_1 = __webpack_require__(/*! ./ui/StatsElement */ 872);
const MoreStatsContent_1 = __webpack_require__(/*! ./ui/MoreStatsContent */ 871);
const MoreEarningsContent_1 = __webpack_require__(/*! ./ui/MoreEarningsContent */ 870);
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ 21));
const server_1 = __webpack_require__(/*! react-dom/server */ 398);
const UIElems = {
container: null,
docButton: null,
faqButton: null,
info: null,
sleeveList: null,
sleeves: null,
};
// Creates the UI for the entire Sleeves page
let playerRef;
function createSleevesPage(p) {
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Sleeves)) {
return;
}
try {
playerRef = p;
UIElems.container = createElement_1.createElement("div", {
class: "generic-menupage-container",
id: "sleeves-container",
position: "fixed",
});
UIElems.info = createElement_1.createElement("p", {
class: "sleeves-page-info",
innerHTML: "
Sleeves
Duplicate Sleeves are MK-V Synthoids (synthetic androids) into which your " +
"consciousness has been copied. In other words, these Synthoids contain " +
"a perfect duplicate of your mind.
" +
"Sleeves can be used to perform different tasks synchronously.
",
});
UIElems.faqButton = createElement_1.createElement("button", {
class: "std-button",
display: "inline-block",
innerText: "FAQ",
clickListener: () => {
DialogBox_1.dialogBoxCreate(SleeveFaq_1.SleeveFaq, false);
},
});
UIElems.docButton = createElement_1.createElement("a", {
class: "std-button",
display: "inline-block",
href: "https://bitburner.readthedocs.io/en/latest/advancedgameplay/sleeves.html#duplicate-sleeves",
innerText: "Documentation",
target: "_blank",
});
UIElems.sleeveList = createElement_1.createElement("ul");
UIElems.sleeves = [];
// Create UI modules for all Sleeve
for (const sleeve of p.sleeves) {
const sleeveUi = createSleeveUi(sleeve, p.sleeves);
if (sleeveUi.container == null)
throw new Error("sleeveUi.container is null in createSleevesPage()");
UIElems.sleeveList.appendChild(sleeveUi.container);
UIElems.sleeves.push(sleeveUi);
}
UIElems.container.appendChild(UIElems.info);
UIElems.container.appendChild(UIElems.faqButton);
UIElems.container.appendChild(UIElems.docButton);
UIElems.container.appendChild(UIElems.sleeveList);
const container = document.getElementById("entire-game-container");
if (container === null)
throw new Error("entire-game-container not found in createSleevesPage()");
container.appendChild(UIElems.container);
}
catch (e) {
exceptionAlert_1.exceptionAlert(e);
}
}
exports.createSleevesPage = createSleevesPage;
// Updates the UI for the entire Sleeves page
function updateSleevesPage() {
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Sleeves)) {
return;
}
if (playerRef === null)
throw new Error("playerRef is null in updateSleevesPage()");
if (UIElems.sleeves === null)
throw new Error("UIElems.sleeves is null in updateSleevesPage()");
try {
for (let i = 0; i < playerRef.sleeves.length; ++i) {
const sleeve = playerRef.sleeves[i];
const elems = UIElems.sleeves[i];
updateSleeveUi(sleeve, elems);
}
}
catch (e) {
exceptionAlert_1.exceptionAlert(e);
}
}
exports.updateSleevesPage = updateSleevesPage;
function clearSleevesPage() {
if (UIElems.container instanceof HTMLElement) {
removeElement_1.removeElement(UIElems.container);
}
for (const prop in UIElems) {
UIElems[prop] = null;
}
playerRef = null;
}
exports.clearSleevesPage = clearSleevesPage;
// Creates the UI for a single Sleeve
// Returns an object containing the DOM elements in the UI (ISleeveUIElems)
function createSleeveUi(sleeve, allSleeves) {
const elems = {
container: null,
statsPanel: null,
stats: null,
moreStatsButton: null,
travelButton: null,
purchaseAugsButton: null,
taskPanel: null,
taskSelector: null,
taskDetailsSelector: null,
taskDetailsSelector2: null,
taskDescription: null,
taskSetButton: null,
taskProgressBar: null,
earningsPanel: null,
currentEarningsInfo: null,
totalEarningsButton: null,
};
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Sleeves)) {
return elems;
}
elems.container = createElement_1.createElement("div", {
class: "sleeve-container",
display: "block",
});
elems.statsPanel = createElement_1.createElement("div", { class: "sleeve-panel", width: "25%" });
elems.stats = createElement_1.createElement("div", { class: "sleeve-stats-text" });
elems.moreStatsButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "More Stats",
clickListener: () => {
DialogBox_1.dialogBoxCreate(MoreStatsContent_1.MoreStatsContent(sleeve));
},
});
elems.travelButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "Travel",
clickListener: () => {
const popupId = "sleeve-travel-popup";
const popupArguments = [];
popupArguments.push(createPopupCloseButton_1.createPopupCloseButton(popupId, { class: "std-button" }));
popupArguments.push(createElement_1.createElement("p", {
innerHTML: "Have this sleeve travel to a different city. This affects " +
"the gyms and universities at which this sleeve can study. " +
`Traveling to a different city costs ${server_1.renderToStaticMarkup(Money_1.Money(Constants_1.CONSTANTS.TravelCost))}. ` +
"It will also CANCEL the sleeve's current task (setting it to idle)",
}));
for (const cityName in Cities_1.Cities) {
if (sleeve.city === cityName) {
continue;
}
(function (sleeve, cityName) {
popupArguments.push(createElement_1.createElement("div", {
// Reusing this css class. It adds a border and makes it so that
// the background color changes when you hover
class: "cmpy-mgmt-find-employee-option",
innerText: cityName,
clickListener: () => {
if (playerRef == null)
throw new Error("playerRef is null in popupArguments.click()");
if (!playerRef.canAfford(Constants_1.CONSTANTS.TravelCost)) {
DialogBox_1.dialogBoxCreate("You cannot afford to have this sleeve travel to another city", false);
return false;
}
sleeve.city = cityName;
playerRef.loseMoney(Constants_1.CONSTANTS.TravelCost);
sleeve.resetTaskStatus();
removeElementById_1.removeElementById(popupId);
updateSleeveUi(sleeve, elems);
updateSleeveTaskSelector(sleeve, elems, allSleeves);
return false;
},
}));
})(sleeve, cityName);
}
createPopup_1.createPopup(popupId, popupArguments);
},
});
elems.purchaseAugsButton = createElement_1.createElement("button", {
class: "std-button",
display: "block",
innerText: "Manage Augmentations",
clickListener: () => {
if (playerRef == null)
throw new Error("playerRef is null in purchaseAugsButton.click()");
SleeveAugmentationsUI_1.createSleevePurchaseAugsPopup(sleeve, playerRef);
},
});
elems.statsPanel.appendChild(elems.stats);
elems.statsPanel.appendChild(elems.moreStatsButton);
elems.statsPanel.appendChild(elems.travelButton);
if (sleeve.shock >= 100) {
// You can only buy augs when shock recovery is 0
elems.statsPanel.appendChild(elems.purchaseAugsButton);
}
elems.taskPanel = createElement_1.createElement("div", { class: "sleeve-panel", width: "40%" });
elems.taskSelector = createElement_1.createElement("select", { class: "dropdown" });
elems.taskSelector.add(createOptionElement_1.createOptionElement("------"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Work for Company"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Work for Faction"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Commit Crime"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Take University Course"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Workout at Gym"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Shock Recovery"));
elems.taskSelector.add(createOptionElement_1.createOptionElement("Synchronize"));
elems.taskDetailsSelector = createElement_1.createElement("select", { class: "dropdown" });
elems.taskDetailsSelector2 = createElement_1.createElement("select", { class: "dropdown" });
elems.taskDescription = createElement_1.createElement("p");
elems.taskProgressBar = createElement_1.createElement("p");
elems.taskSelector.addEventListener("change", () => {
updateSleeveTaskSelector(sleeve, elems, allSleeves);
});
elems.taskSelector.selectedIndex = sleeve.currentTask; // Set initial value for Task Selector
elems.taskSelector.dispatchEvent(new Event('change'));
updateSleeveTaskDescription(sleeve, elems);
elems.taskSetButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "Set Task",
clickListener: () => {
setSleeveTask(sleeve, elems);
},
});
elems.taskPanel.appendChild(elems.taskSelector);
elems.taskPanel.appendChild(elems.taskDetailsSelector);
elems.taskPanel.appendChild(elems.taskDetailsSelector2);
elems.taskPanel.appendChild(elems.taskSetButton);
elems.taskPanel.appendChild(elems.taskDescription);
elems.taskPanel.appendChild(elems.taskProgressBar);
elems.earningsPanel = createElement_1.createElement("div", { class: "sleeve-panel", width: "35%" });
elems.currentEarningsInfo = createElement_1.createElement("div");
elems.totalEarningsButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "More Earnings Info",
clickListener: () => {
DialogBox_1.dialogBoxCreate(MoreEarningsContent_1.MoreEarningsContent(sleeve));
},
});
elems.earningsPanel.appendChild(elems.currentEarningsInfo);
elems.earningsPanel.appendChild(elems.totalEarningsButton);
updateSleeveUi(sleeve, elems);
elems.container.appendChild(elems.statsPanel);
elems.container.appendChild(elems.taskPanel);
elems.container.appendChild(elems.earningsPanel);
return elems;
}
// Updates the UI for a single Sleeve
function updateSleeveUi(sleeve, elems) {
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Sleeves)) {
return;
}
if (playerRef == null)
throw new Error("playerRef is null in updateSleeveUi()");
if (elems.taskProgressBar == null)
throw new Error("elems.taskProgressBar is null");
if (elems.stats == null)
throw new Error("elems.stats is null");
if (elems.currentEarningsInfo == null)
throw new Error("elems.currentEarningsInfo is null");
ReactDOM.render(StatsElement_1.StatsElement(sleeve), elems.stats);
if (sleeve.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Crime) {
const data = [
[`Money`, Money_1.Money(parseFloat(sleeve.currentTaskLocation)), `(on success)`],
[`Hacking Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.hack), `(2x on success)`],
[`Strength Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.str), `(2x on success)`],
[`Defense Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.def), `(2x on success)`],
[`Dexterity Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.dex), `(2x on success)`],
[`Agility Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.agi), `(2x on success)`],
[`Charisma Exp`, numeralFormat_1.numeralWrapper.formatExp(sleeve.gainRatesForTask.cha), `(2x on success)`],
];
ReactDOM.render(EarningsTableElement_1.EarningsTableElement('Earnings (Pre-Synchronization)', data), elems.currentEarningsInfo);
elems.taskProgressBar.innerText = createProgressBarText_1.createProgressBarText({
progress: sleeve.currentTaskTime / sleeve.currentTaskMaxTime,
totalTicks: 25,
});
}
else {
const data = [
[`Money:`, MoneyRate_1.MoneyRate(5 * sleeve.gainRatesForTask.money)],
[`Hacking Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.hack)} / s`],
[`Strength Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.str)} / s`],
[`Defense Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.def)} / s`],
[`Dexterity Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.dex)} / s`],
[`Agility Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.agi)} / s`],
[`Charisma Exp:`, `${numeralFormat_1.numeralWrapper.formatExp(5 * sleeve.gainRatesForTask.cha)} / s`],
];
if (sleeve.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Company || sleeve.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Faction) {
const repGain = sleeve.getRepGain(playerRef);
data.push([`Reputation:`, ReputationRate_1.ReputationRate(5 * repGain)]);
}
ReactDOM.render(EarningsTableElement_1.EarningsTableElement('Earnings (Pre-Synchronization)', data), elems.currentEarningsInfo);
elems.taskProgressBar.innerText = "";
}
}
const universitySelectorOptions = [
"Study Computer Science",
"Data Structures",
"Networks",
"Algorithms",
"Management",
"Leadership",
];
const gymSelectorOptions = [
"Train Strength",
"Train Defense",
"Train Dexterity",
"Train Agility",
];
// Whenever a new task is selected, the "details" selector must update accordingly
function updateSleeveTaskSelector(sleeve, elems, allSleeves) {
if (playerRef == null) {
throw new Error(`playerRef is null in updateSleeveTaskSelector()`);
}
// Array of all companies that other sleeves are working at
const forbiddenCompanies = [];
for (const otherSleeve of allSleeves) {
if (sleeve === otherSleeve) {
continue;
}
if (otherSleeve.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Company) {
forbiddenCompanies.push(otherSleeve.currentTaskLocation);
}
}
// Array of all factions that other sleeves are working for
const forbiddenFactions = [];
for (const otherSleeve of allSleeves) {
if (sleeve === otherSleeve) {
continue;
}
if (otherSleeve.currentTask === SleeveTaskTypesEnum_1.SleeveTaskType.Faction) {
forbiddenFactions.push(otherSleeve.currentTaskLocation);
}
}
if (elems.taskDetailsSelector === null) {
throw new Error("elems.taskDetailsSelector is null");
}
if (elems.taskDetailsSelector2 === null) {
throw new Error("elems.taskDetailsSelector is null");
}
// Reset Selectors
removeChildrenFromElement_1.removeChildrenFromElement(elems.taskDetailsSelector);
removeChildrenFromElement_1.removeChildrenFromElement(elems.taskDetailsSelector2);
elems.taskDetailsSelector2 = clearEventListeners_1.clearEventListeners(elems.taskDetailsSelector2);
const value = getSelectData_1.getSelectValue(elems.taskSelector);
switch (value) {
case "Work for Company": {
let companyCount = 0;
const allJobs = Object.keys(playerRef.jobs);
for (let i = 0; i < allJobs.length; ++i) {
if (!forbiddenCompanies.includes(allJobs[i])) {
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement(allJobs[i]));
// Set initial value of the 'Details' selector
if (sleeve.currentTaskLocation === allJobs[i]) {
elems.taskDetailsSelector.selectedIndex = companyCount;
}
++companyCount;
}
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("------"));
}
break;
}
case "Work for Faction": {
let factionCount = 0;
for (const fac of playerRef.factions) {
if (!forbiddenFactions.includes(fac)) {
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement(fac));
// Set initial value of the 'Details' Selector
if (sleeve.currentTaskLocation === fac) {
elems.taskDetailsSelector.selectedIndex = factionCount;
}
++factionCount;
}
}
// The available faction work types depends on the faction
elems.taskDetailsSelector.addEventListener("change", () => {
if (elems.taskDetailsSelector2 === null)
throw new Error("elems.taskDetailsSelector2 is null");
const facName = getSelectData_1.getSelectValue(elems.taskDetailsSelector);
const faction = Factions_1.Factions[facName];
if (faction == null) {
console.warn(`Invalid faction name when trying to update Sleeve Task Selector: ${facName}`);
return;
}
const facInfo = faction.getInfo();
removeChildrenFromElement_1.removeChildrenFromElement(elems.taskDetailsSelector2);
let numOptionsAdded = 0;
if (facInfo.offerHackingWork) {
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("Hacking Contracts"));
if (sleeve.factionWorkType === FactionWorkTypeEnum_1.FactionWorkType.Hacking) {
elems.taskDetailsSelector2.selectedIndex = numOptionsAdded;
}
++numOptionsAdded;
}
if (facInfo.offerFieldWork) {
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("Field Work"));
if (sleeve.factionWorkType === FactionWorkTypeEnum_1.FactionWorkType.Field) {
elems.taskDetailsSelector2.selectedIndex = numOptionsAdded;
}
++numOptionsAdded;
}
if (facInfo.offerSecurityWork) {
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("Security Work"));
if (sleeve.factionWorkType === FactionWorkTypeEnum_1.FactionWorkType.Security) {
elems.taskDetailsSelector2.selectedIndex = numOptionsAdded;
}
++numOptionsAdded;
}
});
elems.taskDetailsSelector.dispatchEvent(new Event("change"));
break;
}
case "Commit Crime": {
let i = 0;
for (const crimeLabel in Crimes_1.Crimes) {
const name = Crimes_1.Crimes[crimeLabel].name;
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement(name, crimeLabel));
// Set initial value for crime type
if (sleeve.crimeType === "") {
continue;
}
const crime = Crimes_1.Crimes[sleeve.crimeType];
if (crime === null) {
continue;
}
if (name === crime.name) {
elems.taskDetailsSelector.selectedIndex = i;
}
++i;
}
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("------"));
break;
}
case "Take University Course":
// First selector has class type
for (let i = 0; i < universitySelectorOptions.length; ++i) {
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement(universitySelectorOptions[i]));
// Set initial value
if (sleeve.className === universitySelectorOptions[i]) {
elems.taskDetailsSelector.selectedIndex = i;
}
}
// Second selector has which university
switch (sleeve.city) {
case CityNames_1.CityName.Aevum:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.AevumSummitUniversity));
break;
case CityNames_1.CityName.Sector12:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.Sector12RothmanUniversity));
break;
case CityNames_1.CityName.Volhaven:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.VolhavenZBInstituteOfTechnology));
break;
default:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("No university available in city!"));
break;
}
break;
case "Workout at Gym":
// First selector has what stat is being trained
for (let i = 0; i < gymSelectorOptions.length; ++i) {
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement(gymSelectorOptions[i]));
// Set initial value
if (sleeve.gymStatType === gymSelectorOptions[i].substring(6, 9).toLowerCase()) {
elems.taskDetailsSelector.selectedIndex = i;
}
}
// Second selector has gym
// In this switch statement we also set the initial value of the second selector
switch (sleeve.city) {
case CityNames_1.CityName.Aevum:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.AevumCrushFitnessGym));
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.AevumSnapFitnessGym));
// Set initial value
if (sleeve.currentTaskLocation === LocationNames_1.LocationName.AevumCrushFitnessGym) {
elems.taskDetailsSelector2.selectedIndex = 0;
}
else if (sleeve.currentTaskLocation === LocationNames_1.LocationName.AevumSnapFitnessGym) {
elems.taskDetailsSelector2.selectedIndex = 1;
}
break;
case CityNames_1.CityName.Sector12:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.Sector12IronGym));
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.Sector12PowerhouseGym));
// Set initial value
if (sleeve.currentTaskLocation === LocationNames_1.LocationName.Sector12IronGym) {
elems.taskDetailsSelector2.selectedIndex = 0;
}
else if (sleeve.currentTaskLocation === LocationNames_1.LocationName.Sector12PowerhouseGym) {
elems.taskDetailsSelector2.selectedIndex = 1;
}
break;
case CityNames_1.CityName.Volhaven:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement(LocationNames_1.LocationName.VolhavenMilleniumFitnessGym));
break;
default:
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("No gym available in city!"));
break;
}
break;
case "Shock Recovery":
case "Synchronize":
case "------":
// No options in "Details" selector
elems.taskDetailsSelector.add(createOptionElement_1.createOptionElement("------"));
elems.taskDetailsSelector2.add(createOptionElement_1.createOptionElement("------"));
return;
default:
break;
}
}
function setSleeveTask(sleeve, elems) {
try {
if (playerRef == null) {
throw new Error("playerRef is null in Sleeve UI's setSleeveTask()");
}
if (elems.taskDescription == null)
throw new Error("elems.taskDescription is null");
const taskValue = getSelectData_1.getSelectValue(elems.taskSelector);
const detailValue = getSelectData_1.getSelectValue(elems.taskDetailsSelector);
const detailValue2 = getSelectData_1.getSelectValue(elems.taskDetailsSelector2);
let res = false;
switch (taskValue) {
case "------":
elems.taskDescription.innerText = "This sleeve is currently idle";
break;
case "Work for Company":
res = sleeve.workForCompany(playerRef, detailValue);
break;
case "Work for Faction":
res = sleeve.workForFaction(playerRef, detailValue, detailValue2);
break;
case "Commit Crime":
res = sleeve.commitCrime(playerRef, detailValue);
break;
case "Take University Course":
res = sleeve.takeUniversityCourse(playerRef, detailValue2, detailValue);
break;
case "Workout at Gym":
res = sleeve.workoutAtGym(playerRef, detailValue2, detailValue);
break;
case "Shock Recovery":
sleeve.currentTask = SleeveTaskTypesEnum_1.SleeveTaskType.Recovery;
res = sleeve.shockRecovery(playerRef);
break;
case "Synchronize":
res = sleeve.synchronize(playerRef);
break;
default:
console.error(`Invalid/Unrecognized taskValue in setSleeveTask(): ${taskValue}`);
}
if (res) {
updateSleeveTaskDescription(sleeve, elems);
}
else {
switch (taskValue) {
case "Work for Faction":
elems.taskDescription.innerText = "Failed to assign sleeve to task. This is most likely because the selected faction does not offer the selected work type.";
break;
default:
elems.taskDescription.innerText = "Failed to assign sleeve to task. Invalid choice(s).";
break;
}
}
if (navigationTracking_1.routing.isOn(navigationTracking_1.Page.Sleeves)) {
updateSleevesPage();
// Update the task selector for all sleeves by triggering a change event
if (UIElems.sleeves == null)
throw new Error("UIElems.sleeves is null");
for (const e of UIElems.sleeves) {
if (e.taskSelector == null)
throw new Error("e.taskSelector is null");
e.taskSelector.dispatchEvent(new Event('change'));
}
}
return res;
}
catch (e) {
console.error(`Exception caught in setSleeveTask(): ${e}`);
exceptionAlert_1.exceptionAlert(e);
return false;
}
}
function updateSleeveTaskDescription(sleeve, elems) {
try {
if (playerRef == null) {
throw new Error("playerRef is null in Sleeve UI's setSleeveTask()");
}
const taskValue = getSelectData_1.getSelectValue(elems.taskSelector);
const detailValue = getSelectData_1.getSelectValue(elems.taskDetailsSelector);
const detailValue2 = getSelectData_1.getSelectValue(elems.taskDetailsSelector2);
if (elems.taskDescription == null)
throw new Error("elems.taskDescription should not be null");
switch (taskValue) {
case "------":
elems.taskDescription.innerText = "This sleeve is currently idle";
break;
case "Work for Company":
elems.taskDescription.innerText = `This sleeve is currently working your job at ${sleeve.currentTaskLocation}.`;
break;
case "Work for Faction":
elems.taskDescription.innerText = `This sleeve is currently doing ${detailValue2} for ${sleeve.currentTaskLocation}.`;
break;
case "Commit Crime":
elems.taskDescription.innerText = `This sleeve is currently attempting to ${Crimes_1.Crimes[detailValue].type} (Success Rate: ${numeralFormat_1.numeralWrapper.formatPercentage(Crimes_1.Crimes[detailValue].successRate(sleeve))}).`;
break;
case "Take University Course":
elems.taskDescription.innerText = `This sleeve is currently studying/taking a course at ${sleeve.currentTaskLocation}.`;
break;
case "Workout at Gym":
elems.taskDescription.innerText = `This sleeve is currently working out at ${sleeve.currentTaskLocation}.`;
break;
case "Shock Recovery":
elems.taskDescription.innerText = "This sleeve is currently set to focus on shock recovery. This causes " +
"the Sleeve's shock to decrease at a faster rate.";
break;
case "Synchronize":
elems.taskDescription.innerText = "This sleeve is currently set to synchronize with the original consciousness. " +
"This causes the Sleeve's synchronization to increase.";
break;
default:
console.error(`Invalid/Unrecognized taskValue in updateSleeveTaskDescription(): ${taskValue}`);
}
}
catch (e) {
console.error(`Exception caught in updateSleeveTaskDescription(): ${e}`);
exceptionAlert_1.exceptionAlert(e);
}
}
/***/ }),
/* 452 */,
/* 453 */,
/* 454 */,
/* 455 */
/*!***********************************!*\
!*** ./src/Locations/ui/Root.tsx ***!
\***********************************/
/*! no static exports found */
/*! exports used: LocationRoot */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocationRoot = void 0;
/**
* Root React Component for displaying overall Location UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const City_1 = __webpack_require__(/*! ./City */ 907);
const GenericLocation_1 = __webpack_require__(/*! ./GenericLocation */ 906);
const Cities_1 = __webpack_require__(/*! ../Cities */ 192);
const Locations_1 = __webpack_require__(/*! ../Locations */ 408);
const LocationTypeEnum_1 = __webpack_require__(/*! ../LocationTypeEnum */ 477);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
class LocationRoot extends React.Component {
constructor(props) {
super(props);
this.state = {
city: props.p.city,
inCity: props.initiallyInCity == null ? true : props.initiallyInCity,
location: props.p.location,
};
this.enterLocation = this.enterLocation.bind(this);
this.returnToCity = this.returnToCity.bind(this);
this.travel = this.travel.bind(this);
}
enterLocation(to) {
this.props.p.gotoLocation(to);
this.setState({
inCity: false,
location: to,
});
}
/**
* Click listener for a button that lets the player go from a specific location
* back to the city
*/
returnToCity() {
this.setState({
inCity: true,
});
}
/**
* Render UI for a city
*/
renderCity() {
const city = Cities_1.Cities[this.state.city];
if (city == null) {
throw new Error(`Invalid city when rendering UI: ${this.state.city}`);
}
return (React.createElement("div", { className: "noselect" },
React.createElement("h2", null, this.state.city),
React.createElement(City_1.LocationCity, { city: city, enterLocation: this.enterLocation })));
}
/**
* Render UI for a specific location
*/
renderLocation() {
const loc = Locations_1.Locations[this.state.location];
if (loc == null) {
throw new Error(`Invalid location when rendering UI: ${this.state.location}`);
}
if (loc.types.includes(LocationTypeEnum_1.LocationType.StockMarket)) {
this.props.engine.loadStockMarketContent();
}
return (React.createElement(GenericLocation_1.GenericLocation, { engine: this.props.engine, loc: loc, p: this.props.p, returnToCity: this.returnToCity, travel: this.travel }));
}
/**
* Travel to a different city
* @param {CityName} to - Destination city
*/
travel(to) {
const p = this.props.p;
const cost = Constants_1.CONSTANTS.TravelCost;
if (!p.canAfford(cost)) {
DialogBox_1.dialogBoxCreate(`You cannot afford to travel to ${to}`);
return;
}
p.loseMoney(cost);
p.travel(to);
DialogBox_1.dialogBoxCreate(React.createElement("span", { className: "noselect" },
"You are now in ",
to,
"!"));
// Dynamically update main menu
if (p.firstTimeTraveled === false) {
p.firstTimeTraveled = true;
const travelTab = document.getElementById("travel-tab");
const worldHeader = document.getElementById("world-menu-header");
if (travelTab != null && worldHeader !== null) {
travelTab.style.display = "list-item";
worldHeader.click();
worldHeader.click();
}
}
if (this.props.p.travel(to)) {
this.setState({
inCity: true,
city: to,
});
}
}
render() {
if (this.state.inCity) {
return this.renderCity();
}
else {
return this.renderLocation();
}
}
}
exports.LocationRoot = LocationRoot;
/***/ }),
/* 456 */
/*!***********************************************!*\
!*** ./src/Company/GetNextCompanyPosition.ts ***!
\***********************************************/
/*! no static exports found */
/*! exports used: getNextCompanyPositionHelper */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNextCompanyPositionHelper = void 0;
const CompanyPositions_1 = __webpack_require__(/*! ./CompanyPositions */ 52);
function getNextCompanyPositionHelper(currPos) {
if (currPos == null) {
return null;
}
const nextPosName = currPos.nextPosition;
if (nextPosName == null) {
return null;
}
return CompanyPositions_1.CompanyPositions[nextPosName];
}
exports.getNextCompanyPositionHelper = getNextCompanyPositionHelper;
/***/ }),
/* 457 */,
/* 458 */
/*!**********************************!*\
!*** ./src/Terminal/HelpText.ts ***!
\**********************************/
/*! no static exports found */
/*! exports used: HelpTexts, TerminalHelpText */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelpTexts = exports.TerminalHelpText = void 0;
exports.TerminalHelpText = "Type 'help name' to learn more about the command 'name'
" +
'alias [-g] [name="value"] Create or display Terminal aliases ' +
"analyze Get information about the current machine " +
'backdoor Install a backdoor on the current machine ' +
"buy [-l/program] Purchase a program through the Dark Web " +
"cat [file] Display a .msg, .lit, or .txt file " +
"cd [dir] Change to a new directory " +
"check [script] [args...] Print a script's logs to Terminal " +
"clear Clear all text on the terminal " +
"cls See 'clear' command " +
"connect [ip/hostname] Connects to a remote server " +
"download [script/text file] Downloads scripts or text files to your computer " +
"expr [math expression] Evaluate a mathematical expression " +
"free Check the machine's memory (RAM) usage " +
"hack Hack the current machine " +
"help [command] Display this help text, or the help text for a command " +
"home Connect to home computer " +
"hostname Displays the hostname of the machine " +
"ifconfig Displays the IP address of the machine " +
"kill [script/pid] [args...] Stops the specified script on the current server " +
"killall Stops all running scripts on the current machine " +
"ls [dir] [| grep pattern] Displays all files on the machine " +
"lscpu Displays the number of CPU cores on the machine " +
"mem [script] [-t] [n] Displays the amount of RAM required to run the script " +
"mv [src] [dest] Move/rename a text or script file " +
"nano [file] Text editor - Open up and edit a script or text file " +
"ps Display all scripts that are currently running " +
"rm [file] Delete a file from the server " +
"run [name] [-t] [n] [args...] Execute a program or script " +
"scan Prints all immediately-available network connections " +
"scan-analyze [d] [-a] Prints info for all servers up to d nodes away " +
"scp [file] [server] Copies a file to a destination server " +
"sudov Shows whether you have root access on this computer " +
"tail [script] [args...] Displays dynamic logs for the specified script " +
"theme [preset] | bg txt hlgt Change the color scheme of the UI " +
"top Displays all running scripts and their RAM usage " +
'unalias [alias name] Deletes the specified alias ' +
"wget [url] [target file] Retrieves code/text from a web server ";
exports.HelpTexts = {
alias: 'alias [-g] [name="value"] ' +
"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:
" +
'alias nuke="run NUKE.exe"
' +
"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:
" +
'alias worm="HTTPWorm.exe"
' +
"and then you tried to run the following terminal command:
" +
"run worm
" +
"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:
" +
'alias -g worm="HTTPWorm.exe"
' +
"Now, the 'worm' alias will be substituted anytime it shows up as an individual word in a Terminal command.
" +
"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.
" +
"The 'unalias' command can be used to remove aliases.
",
analyze: "analze " +
"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.",
backdoor: "backdoor " +
"Install a backdoor on the current machine, grants a secret bonus depending on the machine. " +
"Requires root access to run. ",
buy: "buy [-l / program] " +
"Purchase a program through the Dark Web. Requires a TOR router to use.
" +
"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.
" +
"Otherwise, the name of the program must be passed in as a parameter. This name is NOT case-sensitive.",
cat: "cat [file] " +
"Display message (.msg), literature (.lit), or text (.txt) files. Examples:
" +
"cat j1.msg " +
"cat foo.lit " +
"cat servers.txt",
cd: "cd [dir] " +
"Change to the specified directory. Note that this works even for directories that don't exist. If you " +
"change to a directory that does not exist, it will not be 'created'. Examples:
" +
"cd scripts/hacking " +
"cd /logs " +
"cd ../",
check: "check [script name] [args...] " +
"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:
" +
"run foo.script 1 2 foodnstuff
" +
"Then to run the 'check' command on this script you would have to pass the same arguments in:
" +
"check foo.script 1 2 foodnstuff",
clear: "clear " +
"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 " +
"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] " +
"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] " +
"Downloads a script or text file to your computer (like your real life computer). " +
"You can also download all of your scripts/text files as a zip file using the following Terminal commands:
" +
"Download all scripts and text files: download * " +
"Download all scripts: download *.script " +
"Download all text files: download *.txt ",
expr: "expr [mathematical expression] " +
"Evaluate a simple mathematical expression. Supports native JavaScript operators: " +
"+, -, /, *, **, % " +
"Example: " +
"expr 25 * 2 ** 10 " +
"Note that letters (non-digits) are not allowed and will be removed from the input.",
free: "free " +
"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 " +
"Attempt to hack the current server. Requires root access in order to be run. See the wiki page for hacking mechanics ",
help: "help [command] " +
"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:
" +
"help alias " +
"help scan-analyze",
home: "home " +
"Connect to your home computer. This will work no matter what server you are currently connected to.",
hostname: "hostname " +
"Prints the hostname of the current server",
ifconfig: "ipconfig " +
"Prints the IP address of the current server",
kill: "kill [script name] [args...] " +
"kill [pid] " +
"Kill the script specified by the script name and arguments OR by its PID.
" +
"If you are killing the script using its filename and arguments, then 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:
" +
"run foo.script 1 sigma-cosmetics
" +
"Then to kill this script the same arguments would have to be used:
" +
"kill foo.script 1 sigma-cosmetics
" +
"If you are killing the script using its PID, then the PID argument must be numeric",
killall: "killall " +
"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 [dir] [| grep pattern] " +
"The ls command, with no arguments, prints all files and directories on the current server's directory to the Terminal screen. " +
"The files will be displayed in alphabetical order.
" +
"The 'dir' optional parameter can be used to display files/directories in another directory.
" +
"The '| grep pattern' optional parameter can be used to only display files whose filenames match the specified pattern.
" +
"Examples:
" +
"List all files with the '.script' extension in the current directory: " +
"ls | grep .script
" +
"List all files with the '.js' extension in the root directory: " +
"ls / | grep .js
" +
"List all files with the word 'purchase' in the filename, in the 'scripts' directory: " +
"ls scripts | grep purchase",
lscpu: "lscpu " +
"Prints the number of CPU Cores the current server has",
mem: "mem [script name] [-t] [num threads] " +
"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:
" +
"mem foo.script " +
"mem foo.script -t 50 " +
"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.",
mv: "mv [src] [dest] " +
"Move the source file to the specified destination. This can also be used to rename files. " +
"This command only works for scripts and text files (.txt). This command CANNOT be used to " +
"convert to different file types
" +
"Note that, unlike the Linux 'mv' command, the destination argument must be the " +
"full filepath. " +
"Examples:
" +
"mv hacking-controller.script scripts/hacking-controller.script " +
"mv myScript.js myOldScript.js",
nano: "nano [file name] " +
"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 " +
"Prints all scripts that are running on the current server",
rm: "rm [file] " +
"Removes the specified file from the current server. A file can be a script, a program, or a message file.
" +
"WARNING: This is permanent and cannot be undone",
run: "run [file name] [-t] [num threads] [args...] " +
"Execute a program or a script.
" +
"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.
" +
"[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.
",
scan: "scan " +
"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] " +
"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.
" +
"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.
" +
"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.
" +
"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] " +
"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 " +
"Prints whether or not you have root access to the current machine",
tail: "tail [script name] [args...] " +
"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:
" +
"run foo.script 10 50000
" +
"Then in order to check its logs with 'tail' the same arguments must be used:
" +
"tail foo.script 10 50000",
theme: "theme [preset] | [#background #text #highlight] " +
"Change the color of the game's user interface
" +
"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:
" +
"theme #ffffff #385 #235012
" +
"A color picker such as " +
"Google's " +
"can be used to get your desired hex color values
" +
"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 " +
"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] ' +
"Deletes the specified alias. Note that the double quotation marks are required.
" +
"As an example, if an alias was declared using:
" +
'alias r="run"
' +
"Then it could be removed using:
" +
'unalias r
' +
"It is not necessary to differentiate between global and non-global aliases when using 'unalias'",
wget: "wget [url] [target file] " +
"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.
" +
"Note that it will not be possible to download data from many websites because they do not allow " +
"cross-origin resource sharing (CORS). Example:
" +
"wget https://raw.githubusercontent.com/danielyxie/bitburner/master/README.md game_readme.txt",
};
/***/ }),
/* 459 */,
/* 460 */,
/* 461 */,
/* 462 */,
/* 463 */,
/* 464 */,
/* 465 */
/*!*****************************!*\
!*** ./src/Casino/utils.ts ***!
\*****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.trusted = void 0;
function trusted(f) {
return function (event) {
if (!event.isTrusted)
return;
f();
};
}
exports.trusted = trusted;
/***/ }),
/* 466 */,
/* 467 */,
/* 468 */
/*!***************************************************!*\
!*** ./utils/uiHelpers/createPopupCloseButton.ts ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Creates a Close/Cancel button that is used for removing popups
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPopupCloseButton = void 0;
const createElement_1 = __webpack_require__(/*! ./createElement */ 51);
const removeElement_1 = __webpack_require__(/*! ./removeElement */ 224);
function createPopupCloseButton(popup, options) {
const button = createElement_1.createElement("button", {
class: options.class ? options.class : "popup-box-button",
display: options.display ? options.display : "inline-block",
innerText: options.innerText == null ? "Cancel" : options.innerText,
});
function closePopupWithEscFn(e) {
if (e.keyCode === 27) {
button.click();
}
}
button.addEventListener("click", () => {
if (popup instanceof Element) {
removeElement_1.removeElement(popup);
}
else {
try {
const popupEl = document.getElementById(popup);
if (popupEl instanceof Element) {
removeElement_1.removeElement(popupEl);
}
}
catch (e) {
console.error(`createPopupCloseButton() threw: ${e}`);
}
}
document.removeEventListener("keydown", closePopupWithEscFn);
return false;
});
document.addEventListener("keydown", closePopupWithEscFn);
return button;
}
exports.createPopupCloseButton = createPopupCloseButton;
/***/ }),
/* 469 */
/*!********************************************!*\
!*** ./src/Locations/LocationsHelpers.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.purchaseTorRouter = exports.createUpgradeHomeRamPopup = exports.createUpgradeHomeCoresPopup = exports.createStartCorporationPopup = exports.createPurchaseServerPopup = exports.createTravelPopup = void 0;
/**
* Location and traveling-related helper functions.
* Mostly used for UI
*/
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const AllServers_1 = __webpack_require__(/*! ../Server/AllServers */ 20);
const ServerHelpers_1 = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
const ServerPurchases_1 = __webpack_require__(/*! ../Server/ServerPurchases */ 136);
const SpecialServerIps_1 = __webpack_require__(/*! ../Server/SpecialServerIps */ 38);
const Settings_1 = __webpack_require__(/*! ../Settings/Settings */ 24);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const YesNoBox_1 = __webpack_require__(/*! ../../utils/YesNoBox */ 61);
const createElement_1 = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
const createPopup_1 = __webpack_require__(/*! ../../utils/uiHelpers/createPopup */ 129);
const createPopupCloseButton_1 = __webpack_require__(/*! ../../utils/uiHelpers/createPopupCloseButton */ 468);
const removeElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/removeElementById */ 90);
const React = __importStar(__webpack_require__(/*! react */ 0));
function createTravelPopup(destination, travelFn) {
const cost = Constants_1.CONSTANTS.TravelCost;
if (Settings_1.Settings.SuppressTravelConfirmation) {
travelFn(destination);
return;
}
const yesBtn = YesNoBox_1.yesNoBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
console.warn(`Could not find YesNo pop-up box buttons`);
return;
}
yesBtn.innerHTML = "Yes";
yesBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
travelFn(destination);
return false;
});
noBtn.innerHTML = "No";
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
return false;
});
YesNoBox_1.yesNoBoxCreate(React.createElement("span", null,
"Would you like to travel to ",
destination,
"? The trip will cost ",
Money_1.Money(cost),
"."));
}
exports.createTravelPopup = createTravelPopup;
/**
* Create a pop-up box that lets the player purchase a server.
* @param {number} ram - Amount of RAM (GB) on server
* @param {IPlayer} p - Player object
*/
function createPurchaseServerPopup(ram, p) {
const cost = ServerPurchases_1.getPurchaseServerCost(ram);
if (cost === Infinity) {
DialogBox_1.dialogBoxCreate("Something went wrong when trying to purchase this server. Please contact developer.");
return;
}
const yesBtn = YesNoBox_1.yesNoTxtInpBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoTxtInpBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
return;
}
yesBtn.innerHTML = "Purchase Server";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function () {
ServerPurchases_1.purchaseServer(ram, p);
YesNoBox_1.yesNoTxtInpBoxClose();
});
noBtn.addEventListener("click", function () {
YesNoBox_1.yesNoTxtInpBoxClose();
});
YesNoBox_1.yesNoTxtInpBoxCreate(React.createElement(React.Fragment, null,
"Would you like to purchase a new server with ",
numeralFormat_1.numeralWrapper.formatRAM(ram),
" of RAM for ",
Money_1.Money(cost),
"?",
React.createElement("br", null),
React.createElement("br", null),
"Please enter the server hostname below:",
React.createElement("br", null)));
}
exports.createPurchaseServerPopup = createPurchaseServerPopup;
/**
* Create a popup that lets the player start a Corporation
* @param {IPlayer} p - Player object
*/
function createStartCorporationPopup(p) {
if (!p.canAccessCorporation() || p.hasCorporation()) {
return;
}
const popupId = "create-corporation-popup";
const txt = createElement_1.createElement("p", {
innerHTML: "Would you like to start a corporation? This will require $150b for registration " +
"and initial funding. This $150b can either be self-funded, or you can obtain " +
"the seed money from the government in exchange for 500 million shares
" +
"If you would like to start one, please enter a name for your corporation below:",
});
const nameInput = createElement_1.createElement("input", {
class: 'text-input',
placeholder: "Corporation Name",
});
const selfFundedButton = createElement_1.createElement("button", {
class: "popup-box-button",
innerText: "Self-Fund",
clickListener: () => {
if (!p.canAfford(150e9)) {
DialogBox_1.dialogBoxCreate("You don't have enough money to create a corporation! You need $150b.");
return false;
}
const companyName = nameInput.value;
if (companyName == null || companyName == "") {
DialogBox_1.dialogBoxCreate("Invalid company name!");
return false;
}
p.startCorporation(companyName);
p.loseMoney(150e9);
const worldHeader = document.getElementById("world-menu-header");
if (worldHeader instanceof HTMLElement) {
worldHeader.click();
worldHeader.click();
}
DialogBox_1.dialogBoxCreate("Congratulations! You just self-funded your own corporation. You can visit " +
"and manage your company in the City.");
removeElementById_1.removeElementById(popupId);
return false;
},
});
const seedMoneyButton = createElement_1.createElement("button", {
class: "popup-box-button",
innerText: "Use Seed Money",
clickListener: () => {
const companyName = nameInput.value;
if (companyName == null || companyName == "") {
DialogBox_1.dialogBoxCreate("Invalid company name!");
return false;
}
p.startCorporation(companyName, 500e6);
const worldHeader = document.getElementById("world-menu-header");
if (worldHeader instanceof HTMLElement) {
worldHeader.click();
worldHeader.click();
}
DialogBox_1.dialogBoxCreate("Congratulations! You just started your own corporation with government seed money. " +
"You can visit and manage your company in the City.");
removeElementById_1.removeElementById(popupId);
return false;
},
});
const cancelBtn = createPopupCloseButton_1.createPopupCloseButton(popupId, { class: "popup-box-button" });
createPopup_1.createPopup(popupId, [txt, nameInput, cancelBtn, selfFundedButton, seedMoneyButton]);
nameInput.focus();
}
exports.createStartCorporationPopup = createStartCorporationPopup;
/**
* Create a popup that lets the player upgrade the cores on his/her home computer
* @param {IPlayer} p - Player object
*/
function createUpgradeHomeCoresPopup(p) {
const currentCores = p.getHomeComputer().cpuCores;
if (currentCores >= 8) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null, "You have the maximum amount of CPU cores on your home computer."));
return;
}
// Cost of purchasing another cost is found by indexing this array with number of current cores
const allCosts = [
0,
10e9,
250e9,
5e12,
100e12,
1e15,
20e15,
200e15,
];
const cost = allCosts[currentCores];
const yesBtn = YesNoBox_1.yesNoBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
return;
}
yesBtn.innerHTML = "Purchase";
yesBtn.addEventListener("click", () => {
if (!p.canAfford(cost)) {
DialogBox_1.dialogBoxCreate("You do not have enough money to purchase an additional CPU Core for your home computer!");
}
else {
p.loseMoney(cost);
p.getHomeComputer().cpuCores++;
DialogBox_1.dialogBoxCreate("You purchased an additional CPU Core for your home computer! It now has " +
p.getHomeComputer().cpuCores + " cores.");
}
YesNoBox_1.yesNoBoxClose();
});
noBtn.innerHTML = "Cancel";
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
});
YesNoBox_1.yesNoBoxCreate(React.createElement(React.Fragment, null,
"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.",
React.createElement("br", null),
React.createElement("br", null),
"Purchasing an additional core (for a total of ",
p.getHomeComputer().cpuCores + 1,
") will cost ",
Money_1.Money(cost)));
}
exports.createUpgradeHomeCoresPopup = createUpgradeHomeCoresPopup;
/**
* Create a popup that lets the player upgrade the RAM on his/her home computer
* @param {IPlayer} p - Player object
*/
function createUpgradeHomeRamPopup(p) {
const cost = p.getUpgradeHomeRamCost();
const ram = p.getHomeComputer().maxRam;
const yesBtn = YesNoBox_1.yesNoBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
return;
}
const homeComputer = p.getHomeComputer();
if (homeComputer.maxRam >= Constants_1.CONSTANTS.HomeComputerMaxRam) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null, "You have the maximum amount of RAM on your home computer."));
return;
}
yesBtn.innerText = "Purchase";
yesBtn.addEventListener("click", () => {
ServerPurchases_1.purchaseRamForHomeComputer(cost, p);
YesNoBox_1.yesNoBoxClose();
});
noBtn.innerText = "Cancel";
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
});
YesNoBox_1.yesNoBoxCreate(React.createElement(React.Fragment, null,
"Would you like to purchase additional RAM for your home computer? ",
React.createElement("br", null),
React.createElement("br", null),
"This will upgrade your RAM from ",
numeralFormat_1.numeralWrapper.formatRAM(ram),
" to ",
numeralFormat_1.numeralWrapper.formatRAM(ram * 2),
". ",
React.createElement("br", null),
React.createElement("br", null),
"This will cost ",
Money_1.Money(cost)));
}
exports.createUpgradeHomeRamPopup = createUpgradeHomeRamPopup;
/**
* Attempt to purchase a TOR router
* @param {IPlayer} p - Player object
*/
function purchaseTorRouter(p) {
if (p.hasTorRouter()) {
DialogBox_1.dialogBoxCreate(`You already have a TOR Router!`);
return;
}
if (!p.canAfford(Constants_1.CONSTANTS.TorRouterCost)) {
DialogBox_1.dialogBoxCreate("You cannot afford to purchase the TOR router!");
return;
}
p.loseMoney(Constants_1.CONSTANTS.TorRouterCost);
const darkweb = ServerHelpers_1.safetlyCreateUniqueServer({
ip: AllServers_1.createUniqueRandomIp(), hostname: "darkweb", organizationName: "",
isConnectedTo: false, adminRights: false, purchasedByPlayer: false, maxRam: 1,
});
AllServers_1.AddToAllServers(darkweb);
SpecialServerIps_1.SpecialServerIps.addIp("Darkweb Server", darkweb.ip);
p.getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(p.getHomeComputer().ip);
DialogBox_1.dialogBoxCreate("You have purchased a TOR router! " +
"You now have access to the dark web from your home computer. " +
"Use the scan/scan-analyze commands to search for the dark web connection.");
}
exports.purchaseTorRouter = purchaseTorRouter;
/***/ }),
/* 470 */
/*!************************************************!*\
!*** ./src/ui/React/AutoupdatingStdButton.tsx ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoupdatingStdButton = void 0;
/**
* Basic stateless button that automatically re-renders itself every X seconds
* Uses the 'std-button' css class
*
* NOT recommended for usage - only if you really have to
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
class AutoupdatingStdButton extends React.Component {
constructor(props) {
super(props);
/**
* Timer ID for auto-updating implementation (returned value from setInterval())
*/
this.interval = 0;
this.state = {
i: 0,
};
}
componentDidMount() {
const time = this.props.intervalTime ? this.props.intervalTime : 1000;
this.interval = window.setInterval(() => this.tick(), time);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState(prevState => ({
i: prevState.i + 1,
}));
}
render() {
const hasTooltip = this.props.tooltip != null && this.props.tooltip !== "";
let className = this.props.disabled ? "std-button-disabled" : "std-button";
if (hasTooltip) {
className += " tooltip";
}
// Tooltip will eb set using inner HTML
const tooltipMarkup = {
__html: this.props.tooltip ? this.props.tooltip : "",
};
return (React.createElement("button", { className: className, onClick: this.props.onClick, style: this.props.style },
this.props.text,
hasTooltip &&
React.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: tooltipMarkup })));
}
}
exports.AutoupdatingStdButton = AutoupdatingStdButton;
/***/ }),
/* 471 */,
/* 472 */,
/* 473 */,
/* 474 */,
/* 475 */,
/* 476 */
/*!**********************************************!*\
!*** ./src/Bladeburner/ui/SuccessChance.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuccessChance = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
function SuccessChance(props) {
if (props.chance[0] === props.chance[1]) {
return (react_1.default.createElement(react_1.default.Fragment, null,
StringHelperFunctions_1.formatNumber(props.chance[0] * 100, 1),
"%"));
}
return (react_1.default.createElement(react_1.default.Fragment, null,
StringHelperFunctions_1.formatNumber(props.chance[0] * 100, 1),
"% ~ ",
StringHelperFunctions_1.formatNumber(props.chance[1] * 100, 1),
"%"));
}
exports.SuccessChance = SuccessChance;
/***/ }),
/* 477 */
/*!*******************************************!*\
!*** ./src/Locations/LocationTypeEnum.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocationType = void 0;
/**
* Enum defining the different types of possible locations
*/
var LocationType;
(function (LocationType) {
LocationType[LocationType["Company"] = 0] = "Company";
LocationType[LocationType["Gym"] = 1] = "Gym";
LocationType[LocationType["Hospital"] = 2] = "Hospital";
LocationType[LocationType["Slums"] = 3] = "Slums";
LocationType[LocationType["Special"] = 4] = "Special";
LocationType[LocationType["StockMarket"] = 5] = "StockMarket";
LocationType[LocationType["TechVendor"] = 6] = "TechVendor";
LocationType[LocationType["TravelAgency"] = 7] = "TravelAgency";
LocationType[LocationType["University"] = 8] = "University";
LocationType[LocationType["Casino"] = 9] = "Casino";
})(LocationType = exports.LocationType || (exports.LocationType = {}));
/***/ }),
/* 478 */,
/* 479 */,
/* 480 */,
/* 481 */,
/* 482 */,
/* 483 */,
/* 484 */,
/* 485 */,
/* 486 */
/*!***********************************!*\
!*** ./src/Gang/data/upgrades.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gangMemberUpgradesMetadata = exports.UpgradeType = void 0;
var UpgradeType;
(function (UpgradeType) {
UpgradeType["Weapon"] = "w";
UpgradeType["Armor"] = "a";
UpgradeType["Vehicle"] = "v";
UpgradeType["Rootkit"] = "r";
UpgradeType["Augmentation"] = "g";
})(UpgradeType = exports.UpgradeType || (exports.UpgradeType = {}));
/**
* 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: UpgradeType.Weapon,
},
{
cost: 12e6,
mults: { str: 1.08, def: 1.08, dex: 1.08 },
name: "Katana",
upgType: UpgradeType.Weapon,
},
{
cost: 25e6,
mults: { str: 1.1, def: 1.1, dex: 1.1, agi: 1.1 },
name: "Glock 18C",
upgType: UpgradeType.Weapon,
},
{
cost: 50e6,
mults: { str: 1.12, def: 1.1, agi: 1.1 },
name: "P90C",
upgType: UpgradeType.Weapon,
},
{
cost: 60e6,
mults: { str: 1.2, def: 1.15 },
name: "Steyr AUG",
upgType: UpgradeType.Weapon,
},
{
cost: 100e6,
mults: { str: 1.25, def: 1.2 },
name: "AK-47",
upgType: UpgradeType.Weapon,
},
{
cost: 150e6,
mults: { str: 1.3, def: 1.25 },
name: "M15A10 Assault Rifle",
upgType: UpgradeType.Weapon,
},
{
cost: 225e6,
mults: { str: 1.3, dex: 1.25, agi: 1.3 },
name: "AWM Sniper Rifle",
upgType: UpgradeType.Weapon,
},
{
cost: 2e6,
mults: { def: 1.04 },
name: "Bulletproof Vest",
upgType: UpgradeType.Armor,
},
{
cost: 5e6,
mults: { def: 1.08 },
name: "Full Body Armor",
upgType: UpgradeType.Armor,
},
{
cost: 25e6,
mults: { def: 1.15, agi: 1.15 },
name: "Liquid Body Armor",
upgType: UpgradeType.Armor,
},
{
cost: 40e6,
mults: { def: 1.2 },
name: "Graphene Plating Armor",
upgType: UpgradeType.Armor,
},
{
cost: 3e6,
mults: { agi: 1.04, cha: 1.04 },
name: "Ford Flex V20",
upgType: UpgradeType.Vehicle,
},
{
cost: 9e6,
mults: { agi: 1.08, cha: 1.08 },
name: "ATX1070 Superbike",
upgType: UpgradeType.Vehicle,
},
{
cost: 18e6,
mults: { agi: 1.12, cha: 1.12 },
name: "Mercedes-Benz S9001",
upgType: UpgradeType.Vehicle,
},
{
cost: 30e6,
mults: { agi: 1.16, cha: 1.16 },
name: "White Ferrari",
upgType: UpgradeType.Vehicle,
},
{
cost: 5e6,
mults: { hack: 1.05 },
name: "NUKE Rootkit",
upgType: UpgradeType.Rootkit,
},
{
cost: 25e6,
mults: { hack: 1.1 },
name: "Soulstealer Rootkit",
upgType: UpgradeType.Rootkit,
},
{
cost: 75e6,
mults: { hack: 1.15 },
name: "Demon Rootkit",
upgType: UpgradeType.Rootkit,
},
{
cost: 40e6,
mults: { hack: 1.12 },
name: "Hmap Node",
upgType: UpgradeType.Rootkit,
},
{
cost: 75e6,
mults: { hack: 1.15 },
name: "Jack the Ripper",
upgType: UpgradeType.Rootkit,
},
{
cost: 10e9,
mults: { str: 1.3, dex: 1.3 },
name: "Bionic Arms",
upgType: UpgradeType.Augmentation,
},
{
cost: 10e9,
mults: { agi: 1.6 },
name: "Bionic Legs",
upgType: UpgradeType.Augmentation,
},
{
cost: 15e9,
mults: { str: 1.15, def: 1.15, dex: 1.15, agi: 1.15 },
name: "Bionic Spine",
upgType: UpgradeType.Augmentation,
},
{
cost: 20e9,
mults: { str: 1.4, def: 1.4 },
name: "BrachiBlades",
upgType: UpgradeType.Augmentation,
},
{
cost: 12e9,
mults: { str: 1.2, def: 1.2 },
name: "Nanofiber Weave",
upgType: UpgradeType.Augmentation,
},
{
cost: 25e9,
mults: { str: 1.5, agi: 1.5 },
name: "Synthetic Heart",
upgType: UpgradeType.Augmentation,
},
{
cost: 15e9,
mults: { str: 1.3, def: 1.3 },
name: "Synfibril Muscle",
upgType: UpgradeType.Augmentation,
},
{
cost: 5e9,
mults: { hack: 1.05 },
name: "BitWire",
upgType: UpgradeType.Augmentation,
},
{
cost: 10e9,
mults: { hack: 1.15 },
name: "Neuralstimulator",
upgType: UpgradeType.Augmentation,
},
{
cost: 7.5e9,
mults: { hack: 1.1 },
name: "DataJack",
upgType: UpgradeType.Augmentation,
},
{
cost: 50e9,
mults: { str: 1.7, def: 1.7 },
name: "Graphene Bone Lacings",
upgType: UpgradeType.Augmentation,
},
];
/***/ }),
/* 487 */
/*!***********************************!*\
!*** ./src/utils/EventEmitter.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventEmitter = void 0;
class EventEmitter {
constructor(subs) {
/**
* Map of Subscriber name -> Callback function
*/
this.subscribers = {};
if (Array.isArray(subs)) {
for (const s of subs) {
this.addSubscriber(s);
}
}
}
addSubscriber(s) {
this.subscribers[s.id] = s.cb;
}
emitEvent(...args) {
for (const s in this.subscribers) {
const sub = this.subscribers[s];
sub(args);
}
}
removeSubscriber(id) {
delete this.subscribers[id];
}
}
exports.EventEmitter = EventEmitter;
/***/ }),
/* 488 */
/*!******************************!*\
!*** ./src/Server/Server.ts ***!
\******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Server = void 0;
// Class representing a single hackable Server
const BaseServer_1 = __webpack_require__(/*! ./BaseServer */ 680);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const createRandomString_1 = __webpack_require__(/*! ../utils/helpers/createRandomString */ 1061);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 399);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class Server extends BaseServer_1.BaseServer {
constructor(params = { hostname: "", ip: IPAddress_1.createRandomIp() }) {
super(params);
// Flag indicating whether this server has a backdoor installed by a player
this.backdoorInstalled = false;
// Initial server security level
// (i.e. security level when the server was created)
this.baseDifficulty = 1;
// Server Security Level
this.hackDifficulty = 1;
// Minimum server security level that this server can be weakened to
this.minDifficulty = 1;
// How much money currently resides on the server and can be hacked
this.moneyAvailable = 0;
// Maximum amount of money that this server can hold
this.moneyMax = 0;
// Number of open ports required in order to gain admin/root access
this.numOpenPortsRequired = 5;
// How many ports are currently opened on the server
this.openPortCount = 0;
// Flag indicating wehther this is a purchased server
this.purchasedByPlayer = false;
// Hacking level required to hack this server
this.requiredHackingSkill = 1;
// Parameter that affects how effectively this server's money can
// be increased using the grow() Netscript function
this.serverGrowth = 1;
// "hacknet-node-X" hostnames are reserved for Hacknet Servers
if (this.hostname.startsWith("hacknet-node-")) {
this.hostname = createRandomString_1.createRandomString(10);
}
this.purchasedByPlayer = params.purchasedByPlayer != null ? params.purchasedByPlayer : false;
//RAM, CPU speed and Scripts
this.maxRam = params.maxRam != null ? params.maxRam : 0; //GB
/* 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_1.BitNodeMultipliers.ServerStartingMoney : 0;
this.moneyMax = 25 * this.moneyAvailable * BitNodeMultipliers_1.BitNodeMultipliers.ServerMaxMoney;
//Hack Difficulty is synonymous with server security. Base Difficulty = Starting difficulty
this.hackDifficulty = params.hackDifficulty != null ? params.hackDifficulty * BitNodeMultipliers_1.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()
//Port information, required for porthacking servers to get admin rights
this.numOpenPortsRequired = params.numOpenPortsRequired != null ? params.numOpenPortsRequired : 5;
}
/**
* Ensures that the server's difficulty (server security) doesn't get too high
*/
capDifficulty() {
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 > 100) {
this.hackDifficulty = 100;
}
}
/**
* Change this server's minimum security
* @param n - Value by which to increase/decrease the server's minimum security
* @param perc - Whether it should be changed by a percentage, or a flat value
*/
changeMinimumSecurity(n, perc = false) {
if (perc) {
this.minDifficulty *= n;
}
else {
this.minDifficulty += n;
}
// Server security cannot go below 1
this.minDifficulty = Math.max(1, this.minDifficulty);
}
/**
* Change this server's maximum money
* @param n - Value by which to change the server's maximum money
* @param perc - Whether it should be changed by a percentage, or a flat value
*/
changeMaximumMoney(n, perc = false) {
if (perc) {
this.moneyMax *= n;
}
else {
this.moneyMax += n;
}
}
/**
* Strengthens a server's security level (difficulty) by the specified amount
*/
fortify(amt) {
this.hackDifficulty += amt;
this.capDifficulty();
}
/**
* Lowers the server's security level (difficulty) by the specified amount)
*/
weaken(amt) {
this.hackDifficulty -= (amt * BitNodeMultipliers_1.BitNodeMultipliers.ServerWeakenRate);
this.capDifficulty();
}
/**
* Serialize the current object to a JSON save state
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Server", this);
}
// Initializes a Server Object from a JSON save state
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Server, value.data);
}
}
exports.Server = Server;
JSONReviver_1.Reviver.constructors.Server = Server;
/***/ }),
/* 489 */
/*!***************************************!*\
!*** ./src/Script/RamCalculations.js ***!
\***************************************/
/*! exports provided: calculateRamUsage */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateRamUsage", function() { return calculateRamUsage; });
/* harmony import */ var acorn_walk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! acorn-walk */ 203);
/* harmony import */ var acorn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! acorn */ 104);
/* harmony import */ var _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./RamCalculationErrorCodes */ 152);
/* harmony import */ var _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Netscript/RamCostGenerator */ 10);
/* harmony import */ var _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__);
/**
* Implements RAM Calculation functionality.
*
* Uses the acorn.js library to parse a script's code into an AST and
* recursively walk through that AST, calculating RAM usage along
* the way
*/
// 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__";
/**
* Parses code into an AST and walks through it recursively to calculate
* RAM usage. Also accounts for imported modules.
* @param {Script[]} otherScripts - All other scripts on the server. Used to account for imported scripts
* @param {string} codeCopy - The code being parsed
* @param {WorkerScript} workerScript - Object containing RAM costs of Netscript functions. Also used to
* keep track of what functions have/havent been accounted for
*/
async function parseOnlyRamCalculate(otherScripts, 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
dependencyMap = Object.assign(dependencyMap, result.dependencyMap);
}
// Parse the initial module, which is the "main" script that is being run
const initialModule = "__SPECIAL_INITIAL_MODULE__";
parseCode(code, initialModule);
// Process additional modules, which occurs if the "main" script has any imports
while (parseQueue.length > 0) {
const nextModule = parseQueue.shift();
// Additional modules can either be imported from the web (in which case we use
// a dynamic import), or from other in-game scripts
let code;
if (nextModule.startsWith("https://") || nextModule.startsWith("http://")) {
try {
// eslint-disable-next-line no-await-in-loop
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 _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].URLImportError;
}
} else {
if (!Array.isArray(otherScripts)) {
console.warn(`parseOnlyRamCalculate() not called with array of scripts`);
return _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].ImportError;
}
let script = null;
let fn = nextModule.startsWith("./") ? nextModule.slice(2) : nextModule;
for (const s of otherScripts) {
if (s.filename === fn) {
script = s;
break;
}
}
if (script == null) {
return _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].ImportError; // 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 = _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__["RamCostConstants"].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 += _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__["RamCostConstants"].ScriptHacknetNodesRamCost;
}
if (ref === "document" && !resolvedRefs.has("document")) {
ram += _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__["RamCostConstants"].ScriptDomRamCost;
}
if (ref === "window" && !resolvedRefs.has("window")) {
ram += _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__["RamCostConstants"].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 identifier is a function in the workerScript environment.
// If it is, then we need to get its RAM cost.
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.error(`Error applying function: ${e}`);
return 0;
}
} else {
return 0;
}
}
// Only count each function once
if (workerScript.loadedFns[ref]) {
continue;
} else {
workerScript.loadedFns[ref] = true;
}
// This accounts for namespaces (Bladeburner, CodingCpntract, etc.)
let 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 if (ref in workerScript.env.vars.sleeve) {
func = workerScript.env.vars.sleeve[ref];
} else {
func = workerScript.env.vars[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 _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].SyntaxError;
}
}
/**
* Helper function that parses a single script. It returns a map of all dependencies,
* which are items in the code's AST that potentially need to be evaluated
* for RAM usage calculations. It also returns an array of additional modules
* that need to be parsed (i.e. are 'import'ed scripts).
*/
function parseOnlyCalculateDeps(code, currentModule) {
const ast = Object(acorn__WEBPACK_IMPORTED_MODULE_1__[/* parse */ "b"])(code, {sourceType:"module", ecmaVersion: 9});
// 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) => {
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);
},
}
}
acorn_walk__WEBPACK_IMPORTED_MODULE_0__[/* recursive */ "a"](ast, {key: globalKey}, Object.assign({
ImportDeclaration: (node, st) => {
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) => {
const key = currentModule + "." + node.id.name;
acorn_walk__WEBPACK_IMPORTED_MODULE_0__[/* recursive */ "a"](node, {key: key}, commonVisitors());
},
}, commonVisitors()));
return {dependencyMap: dependencyMap, additionalModules: additionalModules};
}
/**
* Calculate's a scripts RAM Usage
* @param {string} codeCopy - The script's code
* @param {Script[]} otherScripts - All other scripts on the server.
* Used to account for imported scripts
*/
async function calculateRamUsage(codeCopy, otherScripts) {
// We don't need a real WorkerScript for this. Just an object that keeps
// track of whatever's needed for RAM calculations
const workerScript = {
loadedFns: {},
env: {
vars: _Netscript_RamCostGenerator__WEBPACK_IMPORTED_MODULE_3__["RamCosts"],
},
}
try {
return await parseOnlyRamCalculate(otherScripts, codeCopy, workerScript);
} catch (e) {
console.error(`Failed to parse script for RAM calculations:`);
console.error(e);
return _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].SyntaxError;
}
return _RamCalculationErrorCodes__WEBPACK_IMPORTED_MODULE_2__["RamCalculationErrorCode"].SyntaxError;
}
/***/ }),
/* 490 */
/*!***********************************!*\
!*** ./src/Bladeburner/Action.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Action = void 0;
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const addOffset_1 = __webpack_require__(/*! ../../utils/helpers/addOffset */ 229);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 142);
class StatsMultiplier {
constructor() {
this.hack = 0;
this.str = 0;
this.def = 0;
this.dex = 0;
this.agi = 0;
this.cha = 0;
this.int = 0;
}
}
class Action {
// Base Class for Contracts, Operations, and BlackOps
constructor(params = null) {
this.name = "";
this.desc = "";
// Difficulty scales with level. See getDifficulty() method
this.level = 1;
this.maxLevel = 1;
this.autoLevel = true;
this.baseDifficulty = 100;
this.difficultyFac = 1.01;
// Rank increase/decrease is affected by this exponent
this.rewardFac = 1.02;
this.successes = 0;
this.failures = 0;
// All of these scale with level/difficulty
this.rankGain = 0;
this.rankLoss = 0;
this.hpLoss = 0;
this.hpLost = 0;
// Action Category. Current categories are stealth and kill
this.isStealth = false;
this.isKill = 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 = getRandomInt_1.getRandomInt(1e3, 25e3);
this.countGrowth = getRandomInt_1.getRandomInt(1, 5);
// Weighting of each stat in determining action success rate
this.weights = { hack: 1 / 7, str: 1 / 7, def: 1 / 7, dex: 1 / 7, agi: 1 / 7, cha: 1 / 7, int: 1 / 7 };
// Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1)
this.decays = { hack: 0.9, str: 0.9, def: 0.9, dex: 0.9, agi: 0.9, cha: 0.9, int: 0.9 };
this.teamCount = 0;
if (params && params.name)
this.name = params.name;
if (params && params.desc)
this.desc = params.desc;
if (params && params.baseDifficulty)
this.baseDifficulty = addOffset_1.addOffset(params.baseDifficulty, 10);
if (params && params.difficultyFac)
this.difficultyFac = params.difficultyFac;
if (params && params.rewardFac)
this.rewardFac = params.rewardFac;
if (params && params.rankGain)
this.rankGain = params.rankGain;
if (params && params.rankLoss)
this.rankLoss = params.rankLoss;
if (params && params.hpLoss)
this.hpLoss = params.hpLoss;
if (params && params.isStealth)
this.isStealth = params.isStealth;
if (params && params.isKill)
this.isKill = params.isKill;
if (params && params.count)
this.count = params.count;
if (params && params.countGrowth)
this.countGrowth = params.countGrowth;
if (params && params.weights)
this.weights = params.weights;
if (params && params.decays)
this.decays = params.decays;
// Check to make sure weights are summed properly
let sum = 0;
for (const weight in this.weights) {
if (this.weights.hasOwnProperty(weight)) {
sum += this.weights[weight];
}
}
if (sum - 1 >= 10 * Number.EPSILON) {
throw new Error("Invalid weights when constructing Action " + this.name +
". The weights should sum up to 1. They sum up to :" + 1);
}
for (const decay in this.decays) {
if (this.decays.hasOwnProperty(decay)) {
if (this.decays[decay] > 1) {
throw new Error("Invalid decays when constructing " +
"Action " + this.name + ". " +
"Decay value cannot be greater than 1");
}
}
}
}
getDifficulty() {
const difficulty = this.baseDifficulty * Math.pow(this.difficultyFac, this.level - 1);
if (isNaN(difficulty)) {
throw new Error("Calculated NaN in Action.getDifficulty()");
}
return difficulty;
}
/**
* Tests for success. Should be called when an action has completed
* @param inst {Bladeburner} - Bladeburner instance
*/
attempt(inst) {
return (Math.random() < this.getSuccessChance(inst));
}
// To be implemented by subtypes
getActionTimePenalty() {
return 1;
}
getActionTime(inst) {
const difficulty = this.getDifficulty();
let baseTime = difficulty / Constants_1.BladeburnerConstants.DifficultyToTimeFactor;
const skillFac = inst.skillMultipliers.actionTime; // Always < 1
const effAgility = Player_1.Player.agility * inst.skillMultipliers.effAgi;
const effDexterity = Player_1.Player.dexterity * inst.skillMultipliers.effDex;
const statFac = 0.5 * (Math.pow(effAgility, Constants_1.BladeburnerConstants.EffAgiExponentialFactor) +
Math.pow(effDexterity, Constants_1.BladeburnerConstants.EffDexExponentialFactor) +
(effAgility / Constants_1.BladeburnerConstants.EffAgiLinearFactor) +
(effDexterity / Constants_1.BladeburnerConstants.EffDexLinearFactor)); // Always > 1
baseTime = Math.max(1, baseTime * skillFac / statFac);
return Math.ceil(baseTime * this.getActionTimePenalty());
}
// For actions that have teams. To be implemented by subtypes.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getTeamSuccessBonus(inst) {
return 1;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getActionTypeSkillSuccessBonus(inst) {
return 1;
}
getChaosCompetencePenalty(inst, params) {
const city = inst.getCurrentCity();
if (params.est) {
return Math.pow((city.popEst / Constants_1.BladeburnerConstants.PopulationThreshold), Constants_1.BladeburnerConstants.PopulationExponent);
}
else {
return Math.pow((city.pop / Constants_1.BladeburnerConstants.PopulationThreshold), Constants_1.BladeburnerConstants.PopulationExponent);
}
}
getChaosDifficultyBonus(inst /*, params: ISuccessChanceParams*/) {
const city = inst.getCurrentCity();
if (city.chaos > Constants_1.BladeburnerConstants.ChaosThreshold) {
const diff = 1 + (city.chaos - Constants_1.BladeburnerConstants.ChaosThreshold);
const mult = Math.pow(diff, 0.1);
return mult;
}
return 1;
}
getEstSuccessChance(inst) {
function clamp(x) {
return Math.max(0, Math.min(x, 1));
}
const est = this.getSuccessChance(inst, { est: true });
const real = this.getSuccessChance(inst);
const diff = Math.abs(real - est);
let low = real - diff;
let high = real + diff;
const city = inst.getCurrentCity();
const r = city.pop / city.popEst;
if (r < 1)
low *= r;
else
high *= r;
return [clamp(low), clamp(high)];
}
/**
* @inst - Bladeburner Object
* @params - options:
* est (bool): Get success chance estimate instead of real success chance
*/
getSuccessChance(inst, params = { est: false }) {
if (inst == null) {
throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");
}
let difficulty = this.getDifficulty();
let competence = 0;
for (const stat in this.weights) {
if (this.weights.hasOwnProperty(stat)) {
const playerStatLvl = Player_1.Player.queryStatFromString(stat);
const key = "eff" + stat.charAt(0).toUpperCase() + stat.slice(1);
let effMultiplier = inst.skillMultipliers[key];
if (effMultiplier == null) {
console.error(`Failed to find Bladeburner Skill multiplier for: ${stat}`);
effMultiplier = 1;
}
competence += (this.weights[stat] * Math.pow(effMultiplier * playerStatLvl, this.decays[stat]));
}
}
competence *= Player_1.Player.getIntelligenceBonus(0.75);
competence *= inst.calculateStaminaPenalty();
competence *= this.getTeamSuccessBonus(inst);
competence *= this.getChaosCompetencePenalty(inst, params);
difficulty *= this.getChaosDifficultyBonus(inst);
if (this.name == "Raid" && inst.getCurrentCity().comms <= 0) {
return 0;
}
// Factor skill multipliers into success chance
competence *= inst.skillMultipliers.successChanceAll;
competence *= this.getActionTypeSkillSuccessBonus(inst);
if (this.isStealth) {
competence *= inst.skillMultipliers.successChanceStealth;
}
if (this.isKill) {
competence *= inst.skillMultipliers.successChanceKill;
}
// Augmentation multiplier
competence *= Player_1.Player.bladeburner_success_chance_mult;
if (isNaN(competence)) {
throw new Error("Competence calculated as NaN in Action.getSuccessChance()");
}
return Math.min(1, competence / difficulty);
}
getSuccessesNeededForNextLevel(baseSuccessesPerLevel) {
return Math.ceil((0.5) * (this.maxLevel) * (2 * baseSuccessesPerLevel + (this.maxLevel - 1)));
}
setMaxLevel(baseSuccessesPerLevel) {
if (this.successes >= this.getSuccessesNeededForNextLevel(baseSuccessesPerLevel)) {
++this.maxLevel;
}
}
toJSON() {
return JSONReviver_1.Generic_toJSON("Action", this);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Action, value.data);
}
}
exports.Action = Action;
JSONReviver_1.Reviver.constructors.Action = Action;
/***/ }),
/* 491 */
/*!******************************************!*\
!*** ./utils/uiHelpers/getSelectData.ts ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSelectText = exports.getSelectValue = void 0;
function getSelectValue(selector) {
if (selector == null) {
return "";
}
if (selector.options.length <= 0) {
return "";
}
if (selector.selectedIndex < 0) {
return "";
}
return selector.options[selector.selectedIndex].value;
}
exports.getSelectValue = getSelectValue;
function getSelectText(selector) {
if (selector == null) {
return "";
}
if (selector.options.length <= 0) {
return "";
}
if (selector.selectedIndex < 0) {
return "";
}
return selector.options[selector.selectedIndex].text;
}
exports.getSelectText = getSelectText;
/***/ }),
/* 492 */
/*!************************************!*\
!*** ./src/Corporation/Product.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Product = void 0;
const EmployeePositions_1 = __webpack_require__(/*! ./EmployeePositions */ 282);
const MaterialSizes_1 = __webpack_require__(/*! ./MaterialSizes */ 400);
const ProductRatingWeights_1 = __webpack_require__(/*! ./ProductRatingWeights */ 1122);
const createCityMap_1 = __webpack_require__(/*! ../Locations/createCityMap */ 1121);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
class Product {
constructor(params = {}) {
// Product name
this.name = "";
// The demand for this Product in the market. Gradually decreases
this.dmd = 0;
// How much competition there is in the market for this Product
this.cmp = 0;
// Markup. Affects how high of a price you can charge for this Product
// without suffering a loss in the # of sales
this.mku = 0;
// Production cost - estimation of how much money it costs to make this Product
this.pCost = 0;
// Sell cost
this.sCost = 0;
// Variables for handling the creation process of this Product
this.fin = false; // Whether this Product has finished being created
this.prog = 0; // Creation progress - A number betwee 0-100 representing percentage
this.createCity = ""; // City in which the product is/was being created
this.designCost = 0; // How much money was invested into designing this Product
this.advCost = 0; // How much money was invested into advertising this Product
// Aggregate score for this Product's 'rating'
// This is based on the stats/properties below. The weighting of the
// stats/properties below differs between different industries
this.rat = 0;
// Stats/properties of this Product
this.qlt = 0;
this.per = 0;
this.dur = 0;
this.rel = 0;
this.aes = 0;
this.fea = 0;
// Data refers to the production, sale, and quantity of the products
// These values are specific to a city
// For each city, the data is [qty, prod, sell]
this.data = createCityMap_1.createCityMap([0, 0, 0]);
// Location of this Product
// Only applies for location-based products like restaurants/hospitals
this.loc = "";
// How much space 1 unit of the Product takes (in the warehouse)
// Not applicable for all Products
this.siz = 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 = {};
// Data to keep track of whether production/sale of this Product is
// manually limited. These values are specific to a city
// [Whether production/sale is limited, limit amount]
this.prdman = createCityMap_1.createCityMap([false, 0]);
this.sllman = createCityMap_1.createCityMap([false, 0]);
// Flags that signal whether automatic sale pricing through Market TA is enabled
this.marketTa1 = false;
this.marketTa2 = false;
this.marketTa2Price = createCityMap_1.createCityMap(0);
this.name = params.name ? params.name : "";
this.dmd = params.demand ? params.demand : 0;
this.cmp = params.competition ? params.competition : 0;
this.mku = params.markup ? params.markup : 0;
this.createCity = params.createCity ? params.createCity : "";
this.designCost = params.designCost ? params.designCost : 0;
this.advCost = params.advCost ? params.advCost : 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;
this.loc = params.loc ? params.loc : "";
this.siz = params.size ? params.size : 0;
this.reqMats = params.req ? params.req : {};
}
// empWorkMult is a multiplier that increases progress rate based on
// productivity of employees
createProduct(marketCycles = 1, empWorkMult = 1) {
if (this.fin) {
return;
}
this.prog += (marketCycles * .01 * empWorkMult);
}
// @param industry - Industry object. Reference to industry that makes this Product
finishProduct(employeeProd, industry) {
this.fin = true;
//Calculate properties
const progrMult = this.prog / 100;
const engrRatio = employeeProd[EmployeePositions_1.EmployeePositions.Engineer] / employeeProd["total"];
const mgmtRatio = employeeProd[EmployeePositions_1.EmployeePositions.Management] / employeeProd["total"];
const rndRatio = employeeProd[EmployeePositions_1.EmployeePositions.RandD] / employeeProd["total"];
const opsRatio = employeeProd[EmployeePositions_1.EmployeePositions.Operations] / employeeProd["total"];
const busRatio = employeeProd[EmployeePositions_1.EmployeePositions.Business] / employeeProd["total"];
const designMult = 1 + (Math.pow(this.designCost, 0.1) / 100);
const balanceMult = (1.2 * engrRatio) + (0.9 * mgmtRatio) + (1.3 * rndRatio) +
(1.5 * opsRatio) + (busRatio);
const sciMult = 1 + (Math.pow(industry.sciResearch.qty, industry.sciFac) / 800);
const totalMult = progrMult * balanceMult * designMult * sciMult;
this.qlt = totalMult * ((0.10 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.per = totalMult * ((0.15 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.dur = totalMult * ((0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.08 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.rel = totalMult * ((0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.08 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.08 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.aes = totalMult * ((0.00 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.08 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.10 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.fea = totalMult * ((0.08 * employeeProd[EmployeePositions_1.EmployeePositions.Engineer]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Management]) +
(0.02 * employeeProd[EmployeePositions_1.EmployeePositions.RandD]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Operations]) +
(0.05 * employeeProd[EmployeePositions_1.EmployeePositions.Business]));
this.calculateRating(industry);
const advMult = 1 + (Math.pow(this.advCost, 0.1) / 100);
this.mku = 100 / (advMult * Math.pow((this.qlt + 0.001), 0.65) * (busRatio + mgmtRatio));
// I actually don't understand well enough to know if this is right.
// I'm adding this to prevent a crash.
if (this.mku === 0)
this.mku = 1;
this.dmd = industry.awareness === 0 ? 20 : Math.min(100, advMult * (100 * (industry.popularity / industry.awareness)));
this.cmp = getRandomInt_1.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 (const 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 (const matName in industry.reqMats) {
this.siz += MaterialSizes_1.MaterialSizes[matName] * industry.reqMats[matName];
}
//Delete unneeded variables
// @ts-ignore
delete this.prog;
// @ts-ignore
delete this.createCity;
// @ts-ignore
delete this.designCost;
// @ts-ignore
delete this.advCost;
}
calculateRating(industry) {
const weights = ProductRatingWeights_1.ProductRatingWeights[industry.type];
if (weights == null) {
console.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;
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("Product", this);
}
// Initiatizes a Product object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Product, value.data);
}
}
exports.Product = Product;
JSONReviver_1.Reviver.constructors.Product = Product;
/***/ }),
/* 493 */
/*!****************************************!*\
!*** ./src/Corporation/ResearchMap.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResearchMap = void 0;
// The Research Map is an object that holds all Corporation Research objects
// as values. They are identified by their names
const Research_1 = __webpack_require__(/*! ./Research */ 1128);
const ResearchMetadata_1 = __webpack_require__(/*! ./data/ResearchMetadata */ 1127);
exports.ResearchMap = {};
function addResearch(p) {
if (exports.ResearchMap[p.name] != null) {
console.warn(`Duplicate Research being defined: ${p.name}`);
}
exports.ResearchMap[p.name] = new Research_1.Research(p);
}
for (const metadata of ResearchMetadata_1.researchMetadata) {
addResearch(metadata);
}
/***/ }),
/* 494 */
/*!*************************************!*\
!*** ./src/Corporation/Material.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Material = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class Material {
constructor(params = {}) {
// Name of material
this.name = "InitName";
// Amount of material owned
this.qty = 0;
// Material's "quality". Unbounded
this.qlt = 0;
// How much demand the Material has in the market, and the range of possible
// values for this "demand"
this.dmd = 0;
this.dmdR = [0, 0];
// How much competition there is for this Material in the market, and the range
// of possible values for this "competition"
this.cmp = 0;
this.cmpR = [0, 0];
// Maximum volatility of this Materials stats
this.mv = 0;
// Markup. Determines how high of a price you can charge on the material
// compared to the market price without suffering loss in # of sales
// Quality is divided by this to determine markup limits
// e,g, If mku is 10 and quality is 100 then you can markup prices by 100/10 = 10
this.mku = 0;
// How much of this material is being bought, sold, imported and produced every second
this.buy = 0;
this.sll = 0;
this.prd = 0;
this.imp = 0;
// Exports of this material to another warehouse/industry
this.exp = [];
// Total amount of this material exported in the last cycle
this.totalExp = 0;
// Cost / sec to buy this material. AKA Market Price
this.bCost = 0;
// Cost / sec to sell this material
this.sCost = 0;
// Flags to keep track of whether production and/or sale of this material is limited
// [Whether production/sale is limited, limit amount]
this.prdman = [false, 0]; // Production
this.sllman = [false, 0]; // Sale
// Flags that signal whether automatic sale pricing through Market TA is enabled
this.marketTa1 = false;
this.marketTa2 = false;
this.marketTa2Price = 0;
if (params.name) {
this.name = params.name;
}
this.init();
}
getMarkupLimit() {
return this.qlt / this.mku;
}
init() {
switch (this.name) {
case "Water":
this.dmd = 75;
this.dmdR = [65, 85];
this.cmp = 50;
this.cmpR = [40, 60];
this.bCost = 1500;
this.mv = 0.2;
this.mku = 6;
break;
case "Energy":
this.dmd = 90;
this.dmdR = [80, 99];
this.cmp = 80;
this.cmpR = [65, 95];
this.bCost = 2000;
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 = 8e3;
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 = 9e3;
this.mv = 1.2;
this.mku = 2;
break;
case "Real Estate":
this.dmd = 50;
this.dmdR = [5, 99];
this.cmp = 50;
this.cmpR = [25, 75];
this.bCost = 80e3;
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, 99];
this.bCost = 40e3;
this.mv = 1.6;
this.mku = 1;
break;
case "Robots":
this.dmd = 90;
this.dmdR = [80, 9];
this.cmp = 90;
this.cmpR = [80, 9];
this.bCost = 75e3;
this.mv = 0.5; //Less mv bc its processed twice
this.mku = 1;
break;
case "AI Cores":
this.dmd = 90;
this.dmdR = [80, 99];
this.cmp = 90;
this.cmpR = [80, 9];
this.bCost = 15e3;
this.mv = 0.8; //Less mv bc its processed twice
this.mku = 0.5;
break;
case "Scientific Research":
case "InitName":
break;
default:
console.error(`Invalid material type in init(): ${this.name}`);
break;
}
}
// Process change in demand, competition, and buy cost of this material
processMarket() {
// The price will change in accordance with demand and competition.
// e.g. If demand goes up, then so does price. If competition goes up, price goes down
const priceVolatility = (Math.random() * this.mv) / 300;
const priceChange = 1 + priceVolatility;
//This 1st random check determines whether competition increases or decreases
const compVolatility = (Math.random() * this.mv) / 100;
const compChange = 1 + compVolatility;
if (Math.random() < 0.5) {
this.cmp *= compChange;
if (this.cmp > this.cmpR[1]) {
this.cmp = this.cmpR[1];
}
this.bCost *= (1 / priceChange); // Competition increases, so price goes down
}
else {
this.cmp *= (1 / compChange);
if (this.cmp < this.cmpR[0]) {
this.cmp = this.cmpR[0];
}
this.bCost *= priceChange; // Competition decreases, so price goes up
}
// This 2nd random check determines whether demand increases or decreases
const dmdVolatility = (Math.random() * this.mv) / 100;
const dmdChange = 1 + dmdVolatility;
if (Math.random() < 0.5) {
this.dmd *= dmdChange;
if (this.dmd > this.dmdR[1]) {
this.dmd = this.dmdR[1];
}
this.bCost *= priceChange; // Demand increases, so price goes up
}
else {
this.dmd *= (1 / dmdChange);
if (this.dmd < this.dmdR[0]) {
this.dmd = this.dmdR[0];
}
this.bCost *= (1 / priceChange);
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("Material", this);
}
// Initiatizes a Material object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Material, value.data);
}
}
exports.Material = Material;
JSONReviver_1.Reviver.constructors.Material = Material;
/***/ }),
/* 495 */
/*!**************************************!*\
!*** ./src/Corporation/Warehouse.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Warehouse = void 0;
const Material_1 = __webpack_require__(/*! ./Material */ 494);
const MaterialSizes_1 = __webpack_require__(/*! ./MaterialSizes */ 400);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const exceptionAlert_1 = __webpack_require__(/*! ../../utils/helpers/exceptionAlert */ 91);
class Warehouse {
constructor(params = {}) {
// Text that describes how the space in this Warehouse is being used
// Used to create a tooltip in the UI
this.breakdown = "";
// Warehouse's level, which affects its maximum size
this.level = 1;
// Amount of space currently used by warehouse
this.sizeUsed = 0;
// Whether Smart Supply is enabled for this Industry (the Industry that this Warehouse is for)
this.smartSupplyEnabled = false;
// Flag that indicates whether Smart Supply accounts for imports when calculating
// the amount fo purchase
this.smartSupplyConsiderExports = false;
// 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.loc = params.loc ? params.loc : "";
this.size = params.size ? params.size : 0;
this.materials = {
Water: new Material_1.Material({ name: "Water" }),
Energy: new Material_1.Material({ name: "Energy" }),
Food: new Material_1.Material({ name: "Food" }),
Plants: new Material_1.Material({ name: "Plants" }),
Metal: new Material_1.Material({ name: "Metal" }),
Hardware: new Material_1.Material({ name: "Hardware" }),
Chemicals: new Material_1.Material({ name: "Chemicals" }),
Drugs: new Material_1.Material({ name: "Drugs" }),
Robots: new Material_1.Material({ name: "Robots" }),
AICores: new Material_1.Material({ name: "AI Cores" }),
RealEstate: new Material_1.Material({ name: "Real Estate" }),
};
if (params.corp && params.industry) {
this.updateSize(params.corp, params.industry);
}
}
// Re-calculate how much space is being used by this Warehouse
updateMaterialSizeUsed() {
this.sizeUsed = 0;
this.breakdown = "";
for (const matName in this.materials) {
const mat = this.materials[matName];
if (MaterialSizes_1.MaterialSizes.hasOwnProperty(matName)) {
this.sizeUsed += (mat.qty * MaterialSizes_1.MaterialSizes[matName]);
if (mat.qty > 0) {
this.breakdown += (matName + ": " + numeralFormat_1.numeralWrapper.format(mat.qty * MaterialSizes_1.MaterialSizes[matName], "0,0.0") + " ");
}
}
}
if (this.sizeUsed > this.size) {
console.warn("Warehouse size used greater than capacity, something went wrong");
}
}
updateSize(corporation, industry) {
try {
this.size = (this.level * 100)
* corporation.getStorageMultiplier()
* industry.getStorageMultiplier();
}
catch (e) {
exceptionAlert_1.exceptionAlert(e);
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("Warehouse", this);
}
// Initiatizes a Warehouse object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Warehouse, value.data);
}
}
exports.Warehouse = Warehouse;
JSONReviver_1.Reviver.constructors.Warehouse = Warehouse;
/***/ }),
/* 496 */,
/* 497 */,
/* 498 */,
/* 499 */,
/* 500 */,
/* 501 */,
/* 502 */,
/* 503 */,
/* 504 */,
/* 505 */,
/* 506 */,
/* 507 */,
/* 508 */,
/* 509 */,
/* 510 */,
/* 511 */,
/* 512 */,
/* 513 */,
/* 514 */,
/* 515 */,
/* 516 */,
/* 517 */,
/* 518 */,
/* 519 */,
/* 520 */,
/* 521 */
/*!***************************************************!*\
!*** ./src/PersonObjects/Sleeve/SleeveHelpers.ts ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findSleevePurchasableAugs = void 0;
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const AugmentationNames_1 = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
function findSleevePurchasableAugs(sleeve, p) {
// You can only purchase Augmentations that are actually available from
// your factions. I.e. you must be in a faction that has the Augmentation
// and you must also have enough rep in that faction in order to purchase it.
const ownedAugNames = sleeve.augmentations.map((e) => { return e.name; });
const availableAugs = [];
// Helper function that helps filter out augs that are already owned
// and augs that aren't allowed for sleeves
function isAvailableForSleeve(aug) {
if (aug.name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
return false;
}
if (ownedAugNames.includes(aug.name)) {
return false;
}
if (availableAugs.includes(aug)) {
return false;
}
if (aug.isSpecial) {
return false;
}
return true;
}
// If player is in a gang, then we return all augs that the player
// has enough reputation for (since that gang offers all augs)
if (p.inGang()) {
const fac = p.getGangFaction();
for (const augName in Augmentations_1.Augmentations) {
const aug = Augmentations_1.Augmentations[augName];
if (!isAvailableForSleeve(aug)) {
continue;
}
if (fac.playerReputation > aug.baseRepRequirement) {
availableAugs.push(aug);
}
}
return availableAugs;
}
for (const facName of p.factions) {
if (facName === "Bladeburners") {
continue;
}
if (facName === "Netburners") {
continue;
}
const fac = Factions_1.Factions[facName];
if (fac == null) {
continue;
}
for (const augName of fac.augmentations) {
const aug = Augmentations_1.Augmentations[augName];
if (!isAvailableForSleeve(aug)) {
continue;
}
if (fac.playerReputation > aug.baseRepRequirement) {
availableAugs.push(aug);
}
}
}
return availableAugs;
}
exports.findSleevePurchasableAugs = findSleevePurchasableAugs;
/***/ }),
/* 522 */
/*!*************************************!*\
!*** ./src/Server/formulas/grow.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateServerGrowth = void 0;
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
function calculateServerGrowth(server, threads, p, cores = 1) {
const numServerGrowthCycles = Math.max(Math.floor(threads), 0);
//Get adjusted growth rate, which accounts for server security
const growthRate = Constants_1.CONSTANTS.ServerBaseGrowthRate;
let adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty;
if (adjGrowthRate > Constants_1.CONSTANTS.ServerMaxGrowthRate) {
adjGrowthRate = Constants_1.CONSTANTS.ServerMaxGrowthRate;
}
//Calculate adjusted server growth rate based on parameters
const serverGrowthPercentage = server.serverGrowth / 100;
const numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * BitNodeMultipliers_1.BitNodeMultipliers.ServerGrowthRate;
//Apply serverGrowth for the calculated number of growth cycles
const coreBonus = 1 + (cores - 1) / 16;
return Math.pow(adjGrowthRate, numServerGrowthCyclesAdjusted * p.hacking_grow_mult * coreBonus);
}
exports.calculateServerGrowth = calculateServerGrowth;
/***/ }),
/* 523 */
/*!*********************************************!*\
!*** ./src/Literature/LiteratureHelpers.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.showLiterature = void 0;
const Literatures_1 = __webpack_require__(/*! ./Literatures */ 1135);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
function showLiterature(fn) {
const litObj = Literatures_1.Literatures[fn];
if (litObj == null) {
return;
}
const txt = `${litObj.title}
${litObj.txt}`;
DialogBox_1.dialogBoxCreate(txt);
}
exports.showLiterature = showLiterature;
/***/ }),
/* 524 */
/*!************************************************!*\
!*** ./utils/uiHelpers/removeLoadingScreen.ts ***!
\************************************************/
/*! no static exports found */
/*! exports used: removeLoadingScreen */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeLoadingScreen = void 0;
const getElementById_1 = __webpack_require__(/*! ./getElementById */ 190);
const removeElementById_1 = __webpack_require__(/*! ./removeElementById */ 90);
/**
* 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;
/***/ }),
/* 525 */
/*!***************************************!*\
!*** ./src/ui/ActiveScripts/Root.tsx ***!
\***************************************/
/*! no static exports found */
/*! exports used: ActiveScriptsRoot */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActiveScriptsRoot = void 0;
/**
* Root React Component for the "Active Scripts" UI page. This page displays
* and provides information about all of the player's scripts that are currently running
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const ScriptProduction_1 = __webpack_require__(/*! ./ScriptProduction */ 867);
const ServerAccordions_1 = __webpack_require__(/*! ./ServerAccordions */ 866);
class ActiveScriptsRoot extends React.Component {
constructor(props) {
super(props);
}
render() {
return (React.createElement(React.Fragment, null,
React.createElement("p", null, "This page displays a list of all of your scripts that are currently running across every machine. It also provides information about each script's production. The scripts are categorized by the hostname of the servers on which they are running."),
React.createElement(ScriptProduction_1.ScriptProduction, Object.assign({}, this.props)),
React.createElement(ServerAccordions_1.ServerAccordions, Object.assign({}, this.props))));
}
}
exports.ActiveScriptsRoot = ActiveScriptsRoot;
/***/ }),
/* 526 */
/*!*******************************************************!*\
!*** ./src/PersonObjects/Resleeving/ResleevingUI.tsx ***!
\*******************************************************/
/*! no static exports found */
/*! exports used: clearResleevesPage, createResleevesPage */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearResleevesPage = exports.createResleevesPage = void 0;
const Resleeving_1 = __webpack_require__(/*! ./Resleeving */ 869);
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const navigationTracking_1 = __webpack_require__(/*! ../../ui/navigationTracking */ 18);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const exceptionAlert_1 = __webpack_require__(/*! ../../../utils/helpers/exceptionAlert */ 91);
const createElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createElement */ 51);
const createOptionElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createOptionElement */ 540);
const getSelectData_1 = __webpack_require__(/*! ../../../utils/uiHelpers/getSelectData */ 491);
const removeChildrenFromElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeChildrenFromElement */ 149);
const removeElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElement */ 224);
const React = __importStar(__webpack_require__(/*! react */ 0));
const server_1 = __webpack_require__(/*! react-dom/server */ 398);
const UIElems = {
container: null,
info: null,
sortTag: null,
sortSelector: null,
resleeveList: null,
resleeves: null,
};
let playerRef;
function createResleevesPage(p) {
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Resleeves)) {
return;
}
try {
playerRef = p;
UIElems.container = createElement_1.createElement("div", {
class: "generic-menupage-container",
id: "resleeves-container",
position: "fixed",
});
UIElems.info = createElement_1.createElement("p", {
display: "block",
innerHTML: "Re-sleeving is the process of digitizing and transferring your consciousness " +
"into a new human body, or 'sleeve'. Here at VitaLife, you can purchase new " +
"specially-engineered bodies for the re-sleeve process. Many of these bodies " +
"even come with genetic and cybernetic Augmentations!
" +
"Re-sleeving will change your experience for every stat. It will also REMOVE " +
"all of your currently-installed Augmentations, and replace " +
"them with the ones provided by the purchased sleeve. However, Augmentations that you have " +
"purchased but not installed will NOT be removed. If you have purchased an " +
"Augmentation and then re-sleeve into a body which already has that Augmentation, " +
"it will be removed (since you cannot have duplicate Augmentations).
" +
"NOTE: The stats and multipliers displayed on this page do NOT include your bonuses from " +
"Source-File.",
width: "75%",
});
// Randomly create all Resleeves if they dont already exist
if (p.resleeves.length === 0) {
p.resleeves = Resleeving_1.generateResleeves();
}
// Create a selector for sorting the list of Resleeves
UIElems.sortTag = createElement_1.createElement("p", {
display: "inline-block",
innerText: "Sort By: ",
});
UIElems.sortSelector = createElement_1.createElement("select", { class: "dropdown" });
let SortOption;
(function (SortOption) {
SortOption["Cost"] = "Cost";
SortOption["Hacking"] = "Hacking";
SortOption["Strength"] = "Strength";
SortOption["Defense"] = "Defense";
SortOption["Dexterity"] = "Dexterity";
SortOption["Agility"] = "Agility";
SortOption["Charisma"] = "Charisma";
SortOption["AverageCombatStats"] = "AverageCombat";
SortOption["AverageAllStats"] = "AverageAllStats";
SortOption["TotalNumAugmentations"] = "TotalNumAugmentations";
})(SortOption || (SortOption = {}));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Cost", SortOption.Cost));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Hacking Level", SortOption.Hacking));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Strength Level", SortOption.Strength));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Defense Level", SortOption.Defense));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Dexterity Level", SortOption.Dexterity));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Agility Level", SortOption.Agility));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Charisma Level", SortOption.Charisma));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Average Combat Stats", SortOption.AverageCombatStats));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Average Stats", SortOption.AverageAllStats));
UIElems.sortSelector.add(createOptionElement_1.createOptionElement("Number of Augmentations", SortOption.TotalNumAugmentations));
UIElems.resleeveList = createElement_1.createElement("ul");
UIElems.sortSelector.onchange = () => {
removeChildrenFromElement_1.removeChildrenFromElement(UIElems.resleeveList);
UIElems.resleeves = [];
// Helper function for averaging
function getAverage(...values) {
let sum = 0;
for (let i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum / values.length;
}
const sortOpt = getSelectData_1.getSelectValue(UIElems.sortSelector);
switch (sortOpt) {
case SortOption.Hacking:
p.resleeves.sort((a, b) => {
return a.hacking_skill - b.hacking_skill;
});
break;
case SortOption.Strength:
p.resleeves.sort((a, b) => {
return a.strength - b.strength;
});
break;
case SortOption.Defense:
p.resleeves.sort((a, b) => {
return a.defense - b.defense;
});
break;
case SortOption.Dexterity:
p.resleeves.sort((a, b) => {
return a.dexterity - b.dexterity;
});
break;
case SortOption.Agility:
p.resleeves.sort((a, b) => {
return a.agility - b.agility;
});
break;
case SortOption.Charisma:
p.resleeves.sort((a, b) => {
return a.charisma - b.charisma;
});
break;
case SortOption.AverageCombatStats:
p.resleeves.sort((a, b) => {
const aAvg = getAverage(a.strength, a.defense, a.dexterity, a.agility);
const bAvg = getAverage(b.strength, b.defense, b.dexterity, b.agility);
return aAvg - bAvg;
});
break;
case SortOption.AverageAllStats:
p.resleeves.sort((a, b) => {
const aAvg = getAverage(a.hacking_skill, a.strength, a.defense, a.dexterity, a.agility, a.charisma);
const bAvg = getAverage(b.hacking_skill, b.strength, b.defense, b.dexterity, b.agility, b.charisma);
return aAvg - bAvg;
});
break;
case SortOption.TotalNumAugmentations:
p.resleeves.sort((a, b) => {
return a.augmentations.length - b.augmentations.length;
});
break;
case SortOption.Cost:
default:
p.resleeves.sort((a, b) => {
return a.getCost() - b.getCost();
});
break;
}
if (UIElems.resleeveList == null)
throw new Error("UIElems.resleeveList is null in sortSelector.click()");
if (UIElems.resleeves == null)
throw new Error("UIElems.resleeves is null in sortSelector.click()");
// Create UI for all Resleeves
for (const resleeve of p.resleeves) {
const resleeveUi = createResleeveUi(resleeve);
if (resleeveUi.container == null)
throw new Error("resleeveUi.container is null in sortSelector.click()");
UIElems.resleeveList.appendChild(resleeveUi.container);
UIElems.resleeves.push(resleeveUi);
}
};
UIElems.sortSelector.dispatchEvent(new Event('change')); // Force onchange event
UIElems.container.appendChild(UIElems.info);
UIElems.container.appendChild(createElement_1.createElement("br"));
UIElems.container.appendChild(UIElems.sortTag);
UIElems.container.appendChild(UIElems.sortSelector);
UIElems.container.appendChild(UIElems.resleeveList);
const container = document.getElementById("entire-game-container");
if (container == null)
throw new Error("Could not find entire-game-container in createResleevesPage()");
container.appendChild(UIElems.container);
}
catch (e) {
exceptionAlert_1.exceptionAlert(e);
}
}
exports.createResleevesPage = createResleevesPage;
function clearResleevesPage() {
if (UIElems.container instanceof HTMLElement) {
removeElement_1.removeElement(UIElems.container);
}
for (const prop in UIElems) {
UIElems[prop] = null;
}
playerRef = null;
}
exports.clearResleevesPage = clearResleevesPage;
function createResleeveUi(resleeve) {
const elems = {
container: null,
statsPanel: null,
stats: null,
multipliersButton: null,
augPanel: null,
augSelector: null,
augDescription: null,
costPanel: null,
costText: null,
buyButton: null,
};
if (!navigationTracking_1.routing.isOn(navigationTracking_1.Page.Resleeves)) {
return elems;
}
elems.container = createElement_1.createElement("div", {
class: "resleeve-container",
display: "block",
});
elems.statsPanel = createElement_1.createElement("div", { class: "resleeve-panel", width: "30%" });
elems.stats = createElement_1.createElement("p", {
class: "resleeve-stats-text",
innerHTML: `Hacking: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.hacking_skill)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.hacking_exp)} exp) ` +
`Strength: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.strength)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.strength_exp)} exp) ` +
`Defense: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.defense)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.defense_exp)} exp) ` +
`Dexterity: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.dexterity)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.dexterity_exp)} exp) ` +
`Agility: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.agility)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.agility_exp)} exp) ` +
`Charisma: ${numeralFormat_1.numeralWrapper.formatSkill(resleeve.charisma)} (${numeralFormat_1.numeralWrapper.formatExp(resleeve.charisma_exp)} exp) ` +
`# Augmentations: ${resleeve.augmentations.length}`,
});
elems.multipliersButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "Multipliers",
clickListener: () => {
DialogBox_1.dialogBoxCreate([
"
Total Multipliers:
",
`Hacking Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_mult)}`,
`Hacking Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_exp_mult)}`,
`Strength Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.strength_mult)}`,
`Strength Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.strength_exp_mult)}`,
`Defense Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.defense_mult)}`,
`Defense Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.defense_exp_mult)}`,
`Dexterity Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.dexterity_mult)}`,
`Dexterity Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.dexterity_exp_mult)}`,
`Agility Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.agility_mult)}`,
`Agility Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.agility_exp_mult)}`,
`Charisma Level multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.charisma_mult)}`,
`Charisma Experience multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.charisma_exp_mult)}`,
`Hacking Chance multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_chance_mult)}`,
`Hacking Speed multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_speed_mult)}`,
`Hacking Money multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_money_mult)}`,
`Hacking Growth multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacking_grow_mult)}`,
`Salary multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.work_money_mult)}`,
`Company Reputation Gain multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.company_rep_mult)}`,
`Faction Reputation Gain multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.faction_rep_mult)}`,
`Crime Money multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.crime_money_mult)}`,
`Crime Success multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.crime_success_mult)}`,
`Hacknet Income multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacknet_node_money_mult)}`,
`Hacknet Purchase Cost multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacknet_node_purchase_cost_mult)}`,
`Hacknet Level Upgrade Cost multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacknet_node_level_cost_mult)}`,
`Hacknet Ram Upgrade Cost multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacknet_node_ram_cost_mult)}`,
`Hacknet Core Upgrade Cost multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.hacknet_node_core_cost_mult)}`,
`Bladeburner Max Stamina multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.bladeburner_max_stamina_mult)}`,
`Bladeburner Stamina Gain multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.bladeburner_stamina_gain_mult)}`,
`Bladeburner Field Analysis multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.bladeburner_analysis_mult)}`,
`Bladeburner Success Chance multiplier: ${numeralFormat_1.numeralWrapper.formatPercentage(resleeve.bladeburner_success_chance_mult)}`,
].join(" "), false);
},
});
elems.statsPanel.appendChild(elems.stats);
elems.statsPanel.appendChild(elems.multipliersButton);
elems.augPanel = createElement_1.createElement("div", { class: "resleeve-panel", width: "50%" });
elems.augSelector = createElement_1.createElement("select", { class: "resleeve-aug-selector dropdown" });
elems.augDescription = createElement_1.createElement("p");
for (let i = 0; i < resleeve.augmentations.length; ++i) {
elems.augSelector.add(createOptionElement_1.createOptionElement(resleeve.augmentations[i].name));
}
elems.augSelector.addEventListener("change", () => {
updateAugDescription(elems);
});
elems.augSelector.dispatchEvent(new Event('change')); // Set inital description by manually triggering change event
elems.augPanel.appendChild(elems.augSelector);
elems.augPanel.appendChild(elems.augDescription);
const cost = resleeve.getCost();
elems.costPanel = createElement_1.createElement("div", { class: "resleeve-panel", width: "20%" });
elems.costText = createElement_1.createElement("p", {
innerHTML: `It costs ${server_1.renderToStaticMarkup(Money_1.Money(cost))} ` +
`to purchase this Sleeve.`,
});
elems.buyButton = createElement_1.createElement("button", {
class: "std-button",
innerText: "Purchase",
clickListener: () => {
if (playerRef == null)
throw new Error("playerRef is null in buyButton.click()");
if (Resleeving_1.purchaseResleeve(resleeve, playerRef)) {
DialogBox_1.dialogBoxCreate((React.createElement(React.Fragment, null,
"You re-sleeved for ",
Money_1.Money(cost),
"!")), false);
}
else {
DialogBox_1.dialogBoxCreate(`You cannot afford to re-sleeve into this body`, false);
}
},
});
elems.costPanel.appendChild(elems.costText);
elems.costPanel.appendChild(elems.buyButton);
elems.container.appendChild(elems.statsPanel);
elems.container.appendChild(elems.augPanel);
elems.container.appendChild(elems.costPanel);
return elems;
}
function updateAugDescription(elems) {
if (elems.augDescription == null)
throw new Error("elems.augDescription is null in updateAugDescription()");
const augName = getSelectData_1.getSelectValue(elems.augSelector);
const aug = Augmentations_1.Augmentations[augName];
if (aug == null) {
console.warn(`Could not find Augmentation with name ${augName}`);
return;
}
let innerHTML = aug.info;
if (typeof innerHTML !== 'string') {
innerHTML = server_1.renderToStaticMarkup(innerHTML);
}
elems.augDescription.innerHTML = innerHTML;
}
/***/ }),
/* 527 */,
/* 528 */,
/* 529 */,
/* 530 */,
/* 531 */,
/* 532 */
/*!*************************!*\
!*** ./src/DevMenu.jsx ***!
\*************************/
/*! 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 _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CodingContracts */ 93);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CodingContractGenerator */ 176);
/* harmony import */ var _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Player */ 2);
/* harmony import */ var _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./SourceFile/PlayerOwnedSourceFile */ 443);
/* harmony import */ var _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./RedPill */ 103);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./StockMarket/StockMarket */ 47);
/* harmony import */ var _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Bladeburner/Bladeburner */ 94);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _StockMarket_Stock__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./StockMarket/Stock */ 191);
/* harmony import */ var _StockMarket_Stock__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_Stock__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./engine */ 15);
/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SaveObject */ 114);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 51);
/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 90);
/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_21__);
const Component = react__WEBPACK_IMPORTED_MODULE_20___default.a.Component; // Update as additional BitNodes get implemented
const validSFN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; // Some dev menu buttons just add a lot of something for convenience
const tonsPP = 1e27;
const tonsP = 1e12;
class ValueAdjusterComponent extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.setValue = this.setValue.bind(this);
}
setValue(event) {
this.setState({
value: parseFloat(event.target.value)
});
}
render() {
const {
title,
add,
subtract,
reset
} = this.props;
return react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_20___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button add-exp-button",
onClick: () => add(this.state.value)
}, "+"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("input", {
className: "text-input exp-input",
type: "number",
placeholder: `+/- ${title}`,
value: this.state.value,
onChange: this.setValue
}), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button remove-exp-button",
onClick: () => subtract(this.state.value)
}, "-"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: reset
}, "Reset"));
}
}
class DevMenuComponent extends Component {
constructor(props) {
super(props);
this.state = {
company: 'ECorp',
faction: 'Illuminati',
program: 'NUKE.exe',
server: 'home',
augmentation: 'Augmented Targeting I',
codingcontract: 'Find Largest Prime Factor'
};
this.setSF = this.setSF.bind(this);
this.setAllSF = this.setAllSF.bind(this);
this.clearExploits = this.clearExploits.bind(this);
this.processStocks = this.processStocks.bind(this);
this.setStockPrice = this.setStockPrice.bind(this);
this.viewStockCaps = this.viewStockCaps.bind(this);
this.setFactionDropdown = this.setFactionDropdown.bind(this);
this.setCompanyDropdown = this.setCompanyDropdown.bind(this);
this.setProgramDropdown = this.setProgramDropdown.bind(this);
this.setServerDropdown = this.setServerDropdown.bind(this);
this.setAugmentationDropdown = this.setAugmentationDropdown.bind(this);
this.setCodingcontractDropdown = this.setCodingcontractDropdown.bind(this);
this.receiveInvite = this.receiveInvite.bind(this);
this.modifyFactionRep = this.modifyFactionRep.bind(this);
this.resetFactionRep = this.resetFactionRep.bind(this);
this.modifyFactionFavor = this.modifyFactionFavor.bind(this);
this.resetFactionFavor = this.resetFactionFavor.bind(this);
this.queueAug = this.queueAug.bind(this);
this.addProgram = this.addProgram.bind(this);
this.rootServer = this.rootServer.bind(this);
this.minSecurity = this.minSecurity.bind(this);
this.maxMoney = this.maxMoney.bind(this);
this.modifyCompanyRep = this.modifyCompanyRep.bind(this);
this.resetCompanyRep = this.resetCompanyRep.bind(this);
this.modifyCompanyFavor = this.modifyCompanyFavor.bind(this);
this.resetCompanyFavor = this.resetCompanyFavor.bind(this);
this.specificContract = this.specificContract.bind(this);
}
setFactionDropdown(event) {
this.setState({
faction: event.target.value
});
}
setCompanyDropdown(event) {
this.setState({
company: event.target.value
});
}
setProgramDropdown(event) {
this.setState({
program: event.target.value
});
}
setServerDropdown(event) {
this.setState({
server: event.target.value
});
}
setAugmentationDropdown(event) {
this.setState({
augmentation: event.target.value
});
}
setCodingcontractDropdown(event) {
this.setState({
codingcontract: event.target.value
});
}
addMoney(n) {
return function () {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainMoney(n);
};
}
upgradeRam() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer().maxRam *= 2;
}
quickB1tFlum3() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_10__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN, true, true);
}
b1tflum3() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_10__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN, true);
}
quickHackW0r1dD43m0n() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_10__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN, false, true);
}
hackW0r1dD43m0n() {
Object(_RedPill__WEBPACK_IMPORTED_MODULE_10__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN);
}
modifyExp(stat, modifier) {
return function (exp) {
switch (stat) {
case "hacking":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainHackingExp(exp * modifier);
}
break;
case "strength":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainStrengthExp(exp * modifier);
}
break;
case "defense":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainDefenseExp(exp * modifier);
}
break;
case "dexterity":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainDexterityExp(exp * modifier);
}
break;
case "agility":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainAgilityExp(exp * modifier);
}
break;
case "charisma":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainCharismaExp(exp * modifier);
}
break;
case "intelligence":
if (exp) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainIntelligenceExp(exp * modifier);
}
break;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
};
}
modifyKarma(modifier) {
return function (amt) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].karma += amt * modifier;
};
}
tonsOfExp() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainHackingExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainStrengthExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainDefenseExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainDexterityExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainAgilityExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainCharismaExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gainIntelligenceExp(tonsPP);
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
}
resetAllExp() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
}
resetExperience(stat) {
return function () {
switch (stat) {
case "hacking":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp = 0;
break;
case "strength":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp = 0;
break;
case "defense":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp = 0;
break;
case "dexterity":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp = 0;
break;
case "agility":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp = 0;
break;
case "charisma":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp = 0;
break;
case "intelligence":
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence_exp = 0;
break;
}
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
};
}
resetKarma() {
return function () {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].karma = 0;
};
}
enableIntelligence() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence === 0) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence = 1;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
}
}
disableIntelligence() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence_exp = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].intelligence = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].updateSkillLevels();
}
receiveInvite() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].receiveInvite(this.state.faction);
}
receiveAllInvites() {
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].receiveInvite(_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].name);
}
}
modifyFactionRep(modifier) {
return reputation => {
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][this.state.faction];
if (fac != null && !isNaN(reputation)) {
fac.playerReputation += reputation * modifier;
}
};
}
resetFactionRep() {
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][this.state.faction];
if (fac != null) {
fac.playerReputation = 0;
}
}
modifyFactionFavor(modifier) {
return favor => {
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][this.state.faction];
if (fac != null && !isNaN(favor)) {
fac.favor += favor * modifier;
}
};
}
resetFactionFavor() {
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][this.state.faction];
if (fac != null) {
fac.favor = 0;
}
}
tonsOfRep() {
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].playerReputation = tonsPP;
}
}
resetAllRep() {
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].playerReputation = 0;
}
}
tonsOfFactionFavor() {
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].favor = tonsPP;
}
}
resetAllFactionFavor() {
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
_Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].favor = 0;
}
}
queueAug() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queueAugmentation(this.state.augmentation);
}
queueAllAugs() {
for (const i in _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"]) {
const augName = _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"][i];
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queueAugmentation(augName);
}
}
setSF(sfN, sfLvl) {
return function () {
if (sfLvl === 0) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.filter(sf => sf.n !== sfN);
return;
}
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.some(sf => sf.n === sfN)) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.push(new _SourceFile_PlayerOwnedSourceFile__WEBPACK_IMPORTED_MODULE_7__["PlayerOwnedSourceFile"](sfN, sfLvl));
return;
}
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.length; i++) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles[i].n === sfN) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles[i].lvl = sfLvl;
}
}
};
}
setAllSF(sfLvl) {
return () => {
for (let i = 0; i < validSFN.length; i++) {
this.setSF(validSFN[i], sfLvl)();
}
};
}
clearExploits() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].exploits = [];
}
addProgram() {
const program = this.state.program;
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hasProgram(program)) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer().programs.push(program);
}
}
addAllPrograms() {
for (const i in _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"]) {
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hasProgram(_Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"][i].name)) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer().programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"][i].name);
}
}
}
rootServer() {
const serverName = this.state.server;
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9__["GetServerByHostname"])(serverName);
server.hasAdminRights = true;
server.sshPortOpen = true;
server.ftpPortOpen = true;
server.smtpPortOpen = true;
server.httpPortOpen = true;
server.sqlPortOpen = true;
server.openPortCount = 5;
}
rootAllServers() {
for (const i in _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].hasAdminRights = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].sshPortOpen = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].ftpPortOpen = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].smtpPortOpen = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].httpPortOpen = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].sqlPortOpen = true;
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].openPortCount = 5;
}
}
minSecurity() {
const serverName = this.state.server;
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9__["GetServerByHostname"])(serverName);
server.hackDifficulty = server.minDifficulty;
}
minAllSecurity() {
for (const i in _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].hackDifficulty = _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].minDifficulty;
}
}
maxMoney() {
const serverName = this.state.server;
const server = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_9__["GetServerByHostname"])(serverName);
server.moneyAvailable = server.moneyMax;
}
maxAllMoney() {
for (const i in _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
_Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].moneyAvailable = _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].moneyMax;
}
}
modifyCompanyRep(modifier) {
return reputation => {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][this.state.company];
if (company != null && !isNaN(reputation)) {
company.playerReputation += reputation * modifier;
}
};
}
resetCompanyRep() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][this.state.company];
company.playerReputation = 0;
}
modifyCompanyFavor(modifier) {
return favor => {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][this.state.company];
if (company != null && !isNaN(favor)) {
company.favor += favor * modifier;
}
};
}
resetCompanyFavor() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][this.state.company];
company.favor = 0;
}
tonsOfRepCompanies() {
for (const c in _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"]) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][c].playerReputation = tonsP;
}
}
resetAllRepCompanies() {
for (const c in _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"]) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][c].playerReputation = 0;
}
}
tonsOfFavorCompanies() {
for (const c in _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"]) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][c].favor = tonsP;
}
}
resetAllFavorCompanies() {
for (const c in _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"]) {
_Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][c].favor = 0;
}
}
modifyBladeburnerRank(modify) {
return function (rank) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.changeRank(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"], rank * modify);
}
};
}
resetBladeburnerRank() {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.rank = 0;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.maxRank = 0;
}
addTonsBladeburnerRank() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.changeRank(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"], tonsP);
}
}
modifyBladeburnerCycles(modify) {
return function (cycles) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.storedCycles += cycles * modify;
}
};
}
resetBladeburnerCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.storedCycles = 0;
}
}
addTonsBladeburnerCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.storedCycles += tonsP;
}
}
addTonsGangCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang.storedCycles = tonsP;
}
}
modifyGangCycles(modify) {
return function (cycles) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang.storedCycles += cycles * modify;
}
};
}
resetGangCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].gang.storedCycles = 0;
}
}
addTonsCorporationFunds() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.funds = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.funds.plus(1e99);
}
}
addTonsCorporationCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.storedCycles = tonsP;
}
}
modifyCorporationCycles(modify) {
return function (cycles) {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.storedCycles += cycles * modify;
}
};
}
resetCorporationCycles() {
if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.storedCycles = 0;
}
}
finishCorporationProducts() {
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) return;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.divisions.forEach(div => {
Object.keys(div.products).forEach(prod => div.products[prod].prog = 99.9);
});
}
addCorporationResearch() {
if (!_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation) return;
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].corporation.divisions.forEach(div => {
div.sciResearch.qty += 1e10;
});
}
specificContract() {
Object(_CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2__["generateContract"])({
problemType: this.state.codingcontract,
server: "home"
});
}
processStocks(sub) {
const inputSymbols = document.getElementById('dev-stock-symbol').value.toString().replace(/\s/g, '');
let match = function () {
return true;
};
if (inputSymbols !== '' && inputSymbols !== 'all') {
match = function (symbol) {
return inputSymbols.split(',').includes(symbol);
};
}
for (const name in _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11__["StockMarket"]) {
if (_StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11__["StockMarket"].hasOwnProperty(name)) {
const stock = _StockMarket_StockMarket__WEBPACK_IMPORTED_MODULE_11__["StockMarket"][name];
if (stock instanceof _StockMarket_Stock__WEBPACK_IMPORTED_MODULE_13__["Stock"] && match(stock.symbol)) {
sub(stock);
}
}
}
}
setStockPrice() {
const price = parseFloat(document.getElementById('dev-stock-price').value);
if (!isNaN(price)) {
this.processStocks(stock => {
stock.price = price;
});
}
}
viewStockCaps() {
let stocks = [];
this.processStocks(stock => {
stocks.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", {
key: stock.symbol
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, stock.symbol), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", {
style: {
'textAlign': 'right'
}
}, Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_19__["Money"])(stock.cap))));
});
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("th", null, "Stock"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("th", null, "Price cap")), stocks)));
}
sleeveMaxAllShock() {
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves.length; ++i) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves[i].shock = 0;
}
}
sleeveClearAllShock() {
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves.length; ++i) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves[i].shock = 100;
}
}
sleeveSyncMaxAll() {
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves.length; ++i) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves[i].sync = 100;
}
}
sleeveSyncClearAll() {
for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves.length; ++i) {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves[i].sync = 0;
}
}
timeskip(time) {
return () => {
_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].lastUpdate -= time;
_engine__WEBPACK_IMPORTED_MODULE_14__["Engine"]._lastUpdate -= time;
_SaveObject__WEBPACK_IMPORTED_MODULE_15__[/* saveObject */ "b"].saveGame(_engine__WEBPACK_IMPORTED_MODULE_14__["Engine"].indexedDb);
setTimeout(() => location.reload(), 1000);
};
}
render() {
let factions = [];
for (const i in _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"]) {
factions.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].name,
value: _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].name
}, _Faction_Factions__WEBPACK_IMPORTED_MODULE_5__["Factions"][i].name));
}
let augs = [];
for (const i in _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"]) {
augs.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"][i],
value: _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"][i]
}, _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"][i]));
}
let programs = [];
for (const i in _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"]) {
programs.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"][i].name,
value: _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"][i].name
}, _Programs_Programs__WEBPACK_IMPORTED_MODULE_4__["Programs"][i].name));
}
let sourceFiles = [];
validSFN.forEach(i => sourceFiles.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", {
key: 'sf-' + i
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "SF-", i, ":")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-right",
onClick: this.setSF(i, 0)
}, "0"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-sides",
onClick: this.setSF(i, 1)
}, "1"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-sides",
onClick: this.setSF(i, 2)
}, "2"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-left",
onClick: this.setSF(i, 3)
}, "3")))));
let servers = [];
for (const i in _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
const hn = _Server_AllServers__WEBPACK_IMPORTED_MODULE_8__["AllServers"][i].hostname;
servers.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: hn,
value: hn
}, hn));
}
let companies = [];
for (const c in _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"]) {
const name = _Company_Companies__WEBPACK_IMPORTED_MODULE_3__["Companies"][c].name;
companies.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: name,
value: name
}, name));
}
const contractTypes = [];
const contractTypeNames = Object.keys(_CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContractTypes"]);
for (let i = 0; i < contractTypeNames.length; i++) {
const name = contractTypeNames[i];
contractTypes.push(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("option", {
key: name,
value: name
}, name));
}
return react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h1", null, "Development Menu - Only meant to be used for testing/debugging")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Generic")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addMoney(1e6)
}, "Add $1m"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addMoney(1e9)
}, "Add $1b"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addMoney(1e12)
}, "Add $1t"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addMoney(1e15)
}, "Add $1000t"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addMoney(Infinity)
}, "Add $Infinity"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.upgradeRam
}, "Upgrade Home Computer's RAM")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.quickB1tFlum3
}, "Quick b1t_flum3.exe"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.b1tflum3
}, "Run b1t_flum3.exe"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.quickHackW0r1dD43m0n
}, "Quick w0rld_d34m0n"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.hackW0r1dD43m0n
}, "Hack w0rld_d34m0n")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Experience / Stats")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "All:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button tooltip",
onClick: this.tonsOfExp
}, "Tons of exp", react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "tooltiptext"
}, "Sometimes you just need a ton of experience in every stat")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button tooltip",
onClick: this.resetAllExp
}, "Reset", react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "tooltiptext"
}, "Reset all experience to 0")))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Hacking:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "hacking exp",
add: this.modifyExp('hacking', 1),
subtract: this.modifyExp('hacking', -1),
reset: this.resetExperience('hacking')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Strength:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "strength exp",
add: this.modifyExp('strength', 1),
subtract: this.modifyExp('strength', -1),
reset: this.resetExperience('strength')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Defense:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "defense exp",
add: this.modifyExp('defense', 1),
subtract: this.modifyExp('defense', -1),
reset: this.resetExperience('defense')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Dexterity:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "dexterity exp",
add: this.modifyExp('dexterity', 1),
subtract: this.modifyExp('dexterity', -1),
reset: this.resetExperience('dexterity')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Agility:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "agility exp",
add: this.modifyExp('agility', 1),
subtract: this.modifyExp('agility', -1),
reset: this.resetExperience('agility')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Charisma:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "charisma exp",
add: this.modifyExp('charisma', 1),
subtract: this.modifyExp('charisma', -1),
reset: this.resetExperience('charisma')
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Intelligence:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "intelligence exp",
add: this.modifyExp('intelligence', 1),
subtract: this.modifyExp('intelligence', -1),
reset: this.resetExperience('intelligence')
})), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.enableIntelligence
}, "Enable")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.disableIntelligence
}, "Disable"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text text-center"
}, "Karma:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "karma",
add: this.modifyKarma(1),
subtract: this.modifyKarma(-1),
reset: this.resetKarma()
}))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Factions")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Faction:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "factions-dropdown",
className: "dropdown exp-input",
onChange: this.setFactionDropdown,
value: this.state.faction
}, factions))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Invites:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.receiveInvite
}, "Receive invite from faction")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.receiveAllInvites
}, "Receive all Invites"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Reputation:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "reputation",
add: this.modifyFactionRep(1),
subtract: this.modifyFactionRep(-1),
reset: this.resetFactionRep
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Favor:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "favor",
add: this.modifyFactionFavor(1),
subtract: this.modifyFactionFavor(-1),
reset: this.resetFactionFavor
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "All Reputation:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.tonsOfRep
}, "Tons"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.resetAllRep
}, "Reset"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "All Favor:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.tonsOfFactionFavor
}, "Tons"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.resetAllFactionFavor
}, "Reset"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Augmentations")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Aug:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "dev-augs-dropdown",
className: "dropdown",
onChange: this.setAugmentationDropdown,
value: this.state.augmentation
}, augs))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Queue:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.queueAug
}, "One"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.queueAllAugs
}, "All"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Source-Files")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Exploits:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-right",
onClick: this.clearExploits()
}, "Clear"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", {
key: 'sf-all'
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "All:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-right",
onClick: this.setAllSF(0)
}, "0"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-sides",
onClick: this.setAllSF(1)
}, "1"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-sides",
onClick: this.setAllSF(2)
}, "2"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button touch-left",
onClick: this.setAllSF(3)
}, "3"))), sourceFiles)))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Programs")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Program:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "dev-programs-dropdown",
className: "dropdown",
onChange: this.setProgramDropdown,
value: this.state.program
}, programs))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Add:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addProgram
}, "One"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addAllPrograms
}, "All"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Servers")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Server:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", {
colSpan: "2"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "dev-servers-dropdown",
className: "dropdown",
onChange: this.setServerDropdown,
value: this.state.server
}, servers))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Root:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.rootServer
}, "Root one")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.rootAllServers
}, "Root all"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Security:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.minSecurity
}, "Min one")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.minAllSecurity
}, "Min all"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Money:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.maxMoney
}, "Max one")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.maxAllMoney
}, "Max all"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Companies")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Company:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", {
colSpan: "3"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "dev-companies-dropdown",
className: "dropdown",
onChange: this.setCompanyDropdown,
value: this.state.company
}, companies))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Reputation:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "reputation",
add: this.modifyCompanyRep(1),
subtract: this.modifyCompanyRep(-1),
reset: this.resetCompanyRep
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Favor:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "favor",
add: this.modifyCompanyFavor(1),
subtract: this.modifyCompanyFavor(-1),
reset: this.resetCompanyFavor
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "All Reputation:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.tonsOfRepCompanies
}, "Tons"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.resetAllRepCompanies
}, "Reset"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "All Favor:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.tonsOfFavorCompanies
}, "Tons"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.resetAllFavorCompanies
}, "Reset"))))))), _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_12__["Bladeburner"] && react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Bladeburner")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Rank:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addTonsBladeburnerRank
}, "Tons")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "rank",
add: this.modifyBladeburnerRank(1),
subtract: this.modifyBladeburnerRank(-1),
reset: this.resetBladeburnerRank
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Cycles:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addTonsBladeburnerCycles
}, "Tons")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "cycles",
add: this.modifyBladeburnerCycles(1),
subtract: this.modifyBladeburnerCycles(-1),
reset: this.resetBladeburnerCycles
}))))))), _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].inGang() && react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Gang")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Cycles:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addTonsGangCycles
}, "Tons")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "cycles",
add: this.modifyGangCycles(1),
subtract: this.modifyGangCycles(-1),
reset: this.resetGangCycles
}))))))), _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hasCorporation() && react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Corporation")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addTonsCorporationFunds
}, "Tons of funds"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Cycles:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addTonsCorporationCycles
}, "Tons")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(ValueAdjusterComponent, {
title: "cycles",
add: this.modifyCorporationCycles(1),
subtract: this.modifyCorporationCycles(-1),
reset: this.resetCorporationCycles
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.finishCorporationProducts
}, "Finish products"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.addCorporationResearch
}, "Tons of research"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Coding Contracts")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2__["generateRandomContract"]
}, "Generate Random Contract"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: _CodingContractGenerator__WEBPACK_IMPORTED_MODULE_2__["generateRandomContractOnHome"]
}, "Generate Random Contract on Home Comp"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("select", {
id: "contract-types-dropdown",
className: "dropdown",
onChange: this.setCodingcontractDropdown,
value: this.state.codingcontract
}, contractTypes), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.specificContract
}, "Generate Specified Contract Type on Home Comp"))))))), _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hasWseAccount && react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Stock Market")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Symbol:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("input", {
id: "dev-stock-symbol",
className: "text-input",
type: "text",
placeholder: "symbol/'all'"
}))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Price:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("input", {
id: "dev-stock-price",
className: "text-input",
type: "number",
placeholder: "$$$"
}), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.setStockPrice
}, "Set"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Caps:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.viewStockCaps
}, "View stock caps"))))))), _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sleeves.length > 0 && react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Sleeves")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Shock:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.sleeveMaxAllShock
}, "Max all")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.sleeveClearAllShock
}, "Clear all"))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("span", {
className: "text"
}, "Sync:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.sleeveSyncMaxAll
}, "Max all")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.sleeveSyncClearAll
}, "Clear all"))))))), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "col"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("h2", null, "Offline time skip:")), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.timeskip(60 * 1000)
}, "1 minute"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.timeskip(60 * 60 * 1000)
}, "1 hour"), react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement("button", {
className: "std-button",
onClick: this.timeskip(24 * 60 * 60 * 1000)
}, "1 day")))));
}
}
const devMenuContainerId = "dev-menu-container";
function createDevMenu() {
if (false) {} // Add everything to container, then append to main menu
const devMenuContainer = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("div", {
class: "generic-menupage-container",
id: devMenuContainerId
});
const entireGameContainer = document.getElementById("entire-game-container");
if (entireGameContainer == null) {
throw new Error("Could not find entire-game-container DOM element");
}
entireGameContainer.appendChild(devMenuContainer);
react_dom__WEBPACK_IMPORTED_MODULE_21___default.a.render(react__WEBPACK_IMPORTED_MODULE_20___default.a.createElement(DevMenuComponent, null), devMenuContainer);
}
function closeDevMenu() {
Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_18__["removeElementById"])(devMenuContainerId);
}
/***/ }),
/* 533 */
/*!*********************************!*\
!*** ./src/DarkWeb/DarkWeb.tsx ***!
\*********************************/
/*! no static exports found */
/*! exports used: checkIfConnectedToDarkweb, executeDarkwebTerminalCommand */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeDarkwebTerminalCommand = exports.checkIfConnectedToDarkweb = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const DarkWebItems_1 = __webpack_require__(/*! ./DarkWebItems */ 289);
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const SpecialServerIps_1 = __webpack_require__(/*! ../Server/SpecialServerIps */ 38);
const postToTerminal_1 = __webpack_require__(/*! ../ui/postToTerminal */ 8);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const isValidIPAddress_1 = __webpack_require__(/*! ../../utils/helpers/isValidIPAddress */ 679);
//Posts a "help" message if connected to DarkWeb
function checkIfConnectedToDarkweb() {
if (SpecialServerIps_1.SpecialServerIps.hasOwnProperty("Darkweb Server")) {
const darkwebIp = SpecialServerIps_1.SpecialServerIps.getIp("Darkweb Server");
if (!isValidIPAddress_1.isValidIPAddress(darkwebIp)) {
return;
}
if (darkwebIp == Player_1.Player.getCurrentServer().ip) {
postToTerminal_1.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.");
}
}
}
exports.checkIfConnectedToDarkweb = checkIfConnectedToDarkweb;
//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) {
postToTerminal_1.post("Incorrect number of arguments. Usage: ");
postToTerminal_1.post("buy -l");
postToTerminal_1.post("buy [item name]");
return;
}
const arg = commandArray[1];
if (arg == "-l" || arg == "-1" || arg == "--list") {
listAllDarkwebItems();
}
else {
buyDarkwebItem(arg);
}
break;
}
default:
postToTerminal_1.post("Command not found");
break;
}
}
exports.executeDarkwebTerminalCommand = executeDarkwebTerminalCommand;
function listAllDarkwebItems() {
for (const key in DarkWebItems_1.DarkWebItems) {
const item = DarkWebItems_1.DarkWebItems[key];
postToTerminal_1.postElement(React.createElement(React.Fragment, null,
item.program,
" - ",
Money_1.Money(item.price),
" - ",
item.description));
}
}
function buyDarkwebItem(itemName) {
itemName = itemName.toLowerCase();
// find the program that matches, if any
let item = null;
for (const key in DarkWebItems_1.DarkWebItems) {
const i = DarkWebItems_1.DarkWebItems[key];
if (i.program.toLowerCase() == itemName) {
item = i;
}
}
// return if invalid
if (item === null) {
postToTerminal_1.post("Unrecognized item: " + itemName);
return;
}
// return if the player already has it.
if (Player_1.Player.hasProgram(item.program)) {
postToTerminal_1.post('You already have the ' + item.program + ' program');
return;
}
// return if the player doesn't have enough money
if (Player_1.Player.money.lt(item.price)) {
postToTerminal_1.post("Not enough money to purchase " + item.program);
return;
}
// buy and push
Player_1.Player.loseMoney(item.price);
Player_1.Player.getHomeComputer().programs.push(item.program);
postToTerminal_1.post('You have purchased the ' + item.program + ' program. The new program can be found on your home computer.');
}
/***/ }),
/* 534 */
/*!*****************************************!*\
!*** ./src/ui/React/ServerDropdown.jsx ***!
\*****************************************/
/*! exports provided: ServerType, ServerDropdown */
/*! exports used: ServerDropdown, ServerType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ServerType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ServerDropdown; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Hacknet/HacknetServer */ 78);
/* harmony import */ var _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_2__);
/**
* Creates a dropdown (select HTML element) with server hostnames as options
*
* Configurable to only contain certain types of servers
*/
// TODO make this an enum when this gets converted to TypeScript
const ServerType = {
All: 0,
Foreign: 1,
// Hackable, non-owned servers
Owned: 2,
// Home Computer, Purchased Servers, and Hacknet Servers
Purchased: 3 // Everything from Owned except home computer
};
class ServerDropdown extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
/**
* Checks if the server should be shown in the dropdown menu, based on the
* 'serverType' property
*/
isValidServer(s) {
const type = this.props.serverType;
switch (type) {
case ServerType.All:
return true;
case ServerType.Foreign:
return s.hostname !== "home" && !s.purchasedByPlayer;
case ServerType.Owned:
return s.purchasedByPlayer || s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_2__["HacknetServer"] || s.hostname === "home";
case ServerType.Purchased:
return s.purchasedByPlayer || s instanceof _Hacknet_HacknetServer__WEBPACK_IMPORTED_MODULE_2__["HacknetServer"];
default:
console.warn(`Invalid ServerType specified for ServerDropdown component: ${type}`);
return false;
}
}
/**
* Given a Server object, creates a Option element
*/
renderOption(s) {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("option", {
key: s.hostname,
value: s.hostname
}, s.hostname);
}
render() {
const servers = [];
for (const serverName in _Server_AllServers__WEBPACK_IMPORTED_MODULE_1__["AllServers"]) {
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_1__["AllServers"][serverName];
if (this.isValidServer(server)) {
servers.push(this.renderOption(server));
}
}
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("select", {
className: "dropdown",
onChange: this.props.onChange,
style: this.props.style
}, servers);
}
}
/***/ }),
/* 535 */
/*!************************************!*\
!*** ./src/Hacknet/HacknetNode.ts ***!
\************************************/
/*! no static exports found */
/*! exports used: HacknetNode */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HacknetNode = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const HacknetNodes_1 = __webpack_require__(/*! ./formulas/HacknetNodes */ 153);
const Constants_2 = __webpack_require__(/*! ./data/Constants */ 34);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class HacknetNode {
constructor(name = "", prodMult = 1) {
// Node's number of cores
this.cores = 1;
// Node's Level
this.level = 1;
// Node's production per second
this.moneyGainRatePerSecond = 0;
// How long this Node has existed, in seconds
this.onlineTimeSeconds = 0;
// Node's RAM (GB)
this.ram = 1;
// Total money earned by this Node
this.totalMoneyGenerated = 0;
this.name = name;
this.updateMoneyGainRate(prodMult);
}
// Get the cost to upgrade this Node's number of cores
calculateCoreUpgradeCost(levels = 1, costMult) {
return HacknetNodes_1.calculateCoreUpgradeCost(this.cores, levels, costMult);
}
// Get the cost to upgrade this Node's level
calculateLevelUpgradeCost(levels = 1, costMult) {
return HacknetNodes_1.calculateLevelUpgradeCost(this.level, levels, costMult);
}
// Get the cost to upgrade this Node's RAM
calculateRamUpgradeCost(levels = 1, costMult) {
return HacknetNodes_1.calculateRamUpgradeCost(this.ram, levels, costMult);
}
// Process this Hacknet Node in the game loop.
// Returns the amount of money generated
process(numCycles = 1) {
const seconds = numCycles * Constants_1.CONSTANTS.MilliPerCycle / 1000;
let gain = this.moneyGainRatePerSecond * seconds;
if (isNaN(gain)) {
console.error(`Hacknet Node ${this.name} calculated earnings of NaN`);
gain = 0;
}
this.totalMoneyGenerated += gain;
this.onlineTimeSeconds += seconds;
return gain;
}
// Upgrade this Node's number of cores, if possible
// Returns a boolean indicating whether new cores were successfully bought
upgradeCore(levels = 1, prodMult) {
this.cores = Math.min(Constants_2.HacknetNodeConstants.MaxCores, Math.round(this.cores + levels));
this.updateMoneyGainRate(prodMult);
}
// Upgrade this Node's level, if possible
// Returns a boolean indicating whether the level was successfully updated
upgradeLevel(levels = 1, prodMult) {
this.level = Math.min(Constants_2.HacknetNodeConstants.MaxLevel, Math.round(this.level + levels));
this.updateMoneyGainRate(prodMult);
}
// Upgrade this Node's RAM, if possible
// Returns a boolean indicating whether the RAM was successfully upgraded
upgradeRam(levels = 1, prodMult) {
for (let i = 0; i < levels; ++i) {
this.ram *= 2; // Ram is always doubled
}
this.ram = Math.round(this.ram); // Handle any floating point precision issues
this.updateMoneyGainRate(prodMult);
}
// Re-calculate this Node's production and update the moneyGainRatePerSecond prop
updateMoneyGainRate(prodMult) {
this.moneyGainRatePerSecond = HacknetNodes_1.calculateMoneyGainRate(this.level, this.ram, this.cores, prodMult);
if (isNaN(this.moneyGainRatePerSecond)) {
this.moneyGainRatePerSecond = 0;
DialogBox_1.dialogBoxCreate("Error in calculating Hacknet Node production. Please report to game developer", false);
}
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("HacknetNode", this);
}
/**
* Initiatizes a HacknetNode object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(HacknetNode, value.data);
}
}
exports.HacknetNode = HacknetNode;
JSONReviver_1.Reviver.constructors.HacknetNode = HacknetNode;
/***/ }),
/* 536 */,
/* 537 */,
/* 538 */
/*!******************************************!*\
!*** ./src/ui/React/AccordionButton.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccordionButton = void 0;
/**
* Basic stateless button that uses the 'accordion-button' css class.
* This class has a black background so that it does not clash with the default
* accordion coloring
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
function AccordionButton(props) {
const hasTooltip = props.tooltip != null && props.tooltip !== "";
// TODO Add a disabled class for accordion buttons?
let className = "accordion-button";
if (hasTooltip) {
className += " tooltip";
}
if (typeof props.addClasses === "string") {
className += ` ${props.addClasses}`;
}
// Tooltip will be set using inner HTML
const tooltipMarkup = {
__html: props.tooltip ? props.tooltip : "",
};
return (React.createElement("button", { className: className, id: props.id, onClick: props.onClick, style: props.style },
props.text,
hasTooltip &&
React.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: tooltipMarkup })));
}
exports.AccordionButton = AccordionButton;
/***/ }),
/* 539 */
/*!********************************************************!*\
!*** ./src/ui/ActiveScripts/WorkerScriptAccordion.tsx ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkerScriptAccordion = void 0;
/**
* React Component for displaying a single WorkerScript's info as an
* Accordion element
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../numeralFormat */ 7);
const Accordion_1 = __webpack_require__(/*! ../React/Accordion */ 161);
const AccordionButton_1 = __webpack_require__(/*! ../React/AccordionButton */ 538);
const killWorkerScript_1 = __webpack_require__(/*! ../../Netscript/killWorkerScript */ 70);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const LogBox_1 = __webpack_require__(/*! ../../../utils/LogBox */ 151);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const arrayToString_1 = __webpack_require__(/*! ../../../utils/helpers/arrayToString */ 113);
const Money_1 = __webpack_require__(/*! ../React/Money */ 27);
function WorkerScriptAccordion(props) {
const workerScript = props.workerScript;
const scriptRef = workerScript.scriptRef;
const logClickHandler = LogBox_1.logBoxCreate.bind(null, scriptRef);
const killScript = killWorkerScript_1.killWorkerScript.bind(null, scriptRef, scriptRef.server);
function killScriptClickHandler() {
killScript();
DialogBox_1.dialogBoxCreate("Killing script");
}
// Calculations for script stats
const onlineMps = scriptRef.onlineMoneyMade / scriptRef.onlineRunningTime;
const onlineEps = scriptRef.onlineExpGained / scriptRef.onlineRunningTime;
const offlineMps = scriptRef.offlineMoneyMade / scriptRef.offlineRunningTime;
const offlineEps = scriptRef.offlineExpGained / scriptRef.offlineRunningTime;
return (React.createElement(Accordion_1.Accordion, { headerClass: "active-scripts-script-header", headerContent: React.createElement(React.Fragment, null, props.workerScript.name), panelClass: "active-scripts-script-panel", panelContent: React.createElement(React.Fragment, null,
React.createElement("pre", null,
"Threads: ",
numeralFormat_1.numeralWrapper.formatThreads(props.workerScript.scriptRef.threads)),
React.createElement("pre", null,
"Args: ",
arrayToString_1.arrayToString(props.workerScript.args)),
React.createElement("pre", null,
"Online Time: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(scriptRef.onlineRunningTime * 1e3)),
React.createElement("pre", null,
"Offline Time: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(scriptRef.offlineRunningTime * 1e3)),
React.createElement("pre", null,
"Total online production: ",
Money_1.Money(scriptRef.onlineMoneyMade)),
React.createElement("pre", null, (Array(26).join(" ") + numeralFormat_1.numeralWrapper.formatExp(scriptRef.onlineExpGained) + " hacking exp")),
React.createElement("pre", null,
"Online production rate: ",
Money_1.Money(onlineMps),
" / second"),
React.createElement("pre", null, (Array(25).join(" ") + numeralFormat_1.numeralWrapper.formatExp(onlineEps) + " hacking exp / second")),
React.createElement("pre", null,
"Total offline production: ",
Money_1.Money(scriptRef.offlineMoneyMade)),
React.createElement("pre", null, (Array(27).join(" ") + numeralFormat_1.numeralWrapper.formatExp(scriptRef.offlineExpGained) + " hacking exp")),
React.createElement("pre", null,
"Offline production rate: ",
Money_1.Money(offlineMps),
" / second"),
React.createElement("pre", null, (Array(26).join(" ") + numeralFormat_1.numeralWrapper.formatExp(offlineEps) + " hacking exp / second")),
React.createElement(AccordionButton_1.AccordionButton, { onClick: logClickHandler, text: "Log" }),
React.createElement(AccordionButton_1.AccordionButton, { onClick: killScriptClickHandler, text: "Kill Script" })) }));
}
exports.WorkerScriptAccordion = WorkerScriptAccordion;
/***/ }),
/* 540 */
/*!************************************************!*\
!*** ./utils/uiHelpers/createOptionElement.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOptionElement = void 0;
const createElement_1 = __webpack_require__(/*! ./createElement */ 51);
function createOptionElement(text, value = "") {
let sanitizedValue = value;
if (sanitizedValue === "") {
sanitizedValue = text;
}
return createElement_1.createElement("option", {
text: text,
value: sanitizedValue,
});
}
exports.createOptionElement = createOptionElement;
/***/ }),
/* 541 */,
/* 542 */,
/* 543 */,
/* 544 */,
/* 545 */,
/* 546 */,
/* 547 */,
/* 548 */,
/* 549 */,
/* 550 */,
/* 551 */,
/* 552 */,
/* 553 */,
/* 554 */,
/* 555 */,
/* 556 */,
/* 557 */,
/* 558 */,
/* 559 */,
/* 560 */,
/* 561 */,
/* 562 */,
/* 563 */,
/* 564 */,
/* 565 */,
/* 566 */,
/* 567 */,
/* 568 */,
/* 569 */,
/* 570 */,
/* 571 */,
/* 572 */,
/* 573 */,
/* 574 */,
/* 575 */,
/* 576 */,
/* 577 */,
/* 578 */,
/* 579 */,
/* 580 */,
/* 581 */,
/* 582 */,
/* 583 */,
/* 584 */,
/* 585 */,
/* 586 */,
/* 587 */,
/* 588 */,
/* 589 */,
/* 590 */,
/* 591 */,
/* 592 */,
/* 593 */,
/* 594 */,
/* 595 */,
/* 596 */,
/* 597 */,
/* 598 */,
/* 599 */,
/* 600 */,
/* 601 */,
/* 602 */,
/* 603 */,
/* 604 */,
/* 605 */,
/* 606 */,
/* 607 */,
/* 608 */,
/* 609 */,
/* 610 */,
/* 611 */,
/* 612 */,
/* 613 */,
/* 614 */,
/* 615 */,
/* 616 */,
/* 617 */,
/* 618 */,
/* 619 */,
/* 620 */,
/* 621 */,
/* 622 */,
/* 623 */,
/* 624 */,
/* 625 */,
/* 626 */,
/* 627 */,
/* 628 */,
/* 629 */,
/* 630 */,
/* 631 */
/*!*************************************!*\
!*** ./src/Casino/CardDeck/Card.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Card = exports.Suit = void 0;
// Enum values are lowercased to match css classes
var Suit;
(function (Suit) {
Suit["Clubs"] = "clubs";
Suit["Diamonds"] = "diamonds";
Suit["Hearts"] = "hearts";
Suit["Spades"] = "spades";
})(Suit = exports.Suit || (exports.Suit = {}));
class Card {
constructor(value, suit) {
this.value = value;
this.suit = suit;
if (value < 1 || value > 13) {
throw new Error(`Card instantiated with improper value: ${value}`);
}
}
formatValue() {
switch (this.value) {
case 1:
return "A";
case 11:
return "J";
case 12:
return "Q";
case 13:
return "K";
default:
return `${this.value}`;
}
}
isRedSuit() {
return this.suit === Suit.Hearts || this.suit === Suit.Diamonds;
}
getStringRepresentation() {
const value = this.formatValue();
return `${value} of ${this.suit}`;
}
}
exports.Card = Card;
/***/ }),
/* 632 */
/*!************************************************!*\
!*** ./src/Infiltration/ui/BlinkingCursor.tsx ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlinkingCursor = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
function BlinkingCursor() {
return (react_1.default.createElement("span", { style: { fontSize: "1em" }, className: "blinking-cursor" }, "|"));
}
exports.BlinkingCursor = BlinkingCursor;
/***/ }),
/* 633 */,
/* 634 */,
/* 635 */,
/* 636 */,
/* 637 */,
/* 638 */,
/* 639 */,
/* 640 */,
/* 641 */
/*!**********************************************!*\
!*** ./src/Bladeburner/ui/TeamSizePopup.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TeamSizePopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
function TeamSizePopup(props) {
const [teamSize, setTeamSize] = react_1.useState();
function confirmTeamSize() {
if (teamSize === undefined)
return;
const num = Math.round(teamSize);
if (isNaN(num) || num < 0) {
DialogBox_1.dialogBoxCreate("Invalid value entered for number of Team Members (must be numeric, positive)");
}
else {
props.action.teamCount = num;
}
createPopup_1.removePopup(props.popupId);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "Enter the amount of team members you would like to take on this Op. 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."),
react_1.default.createElement("input", { autoFocus: true, type: "number", placeholder: "Team size", className: "text-input", onChange: event => setTeamSize(parseFloat(event.target.value)) }),
react_1.default.createElement("a", { className: "a-link-button", onClick: confirmTeamSize }, "Confirm")));
}
exports.TeamSizePopup = TeamSizePopup;
/***/ }),
/* 642 */
/*!************************************************!*\
!*** ./src/ui/React/AugmentationAccordion.tsx ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AugmentationAccordion = void 0;
/**
* React Component for displaying a single Augmentation as an accordion.
*
* The header of the accordion contains the Augmentation's name (and level, if
* applicable), and the accordion's panel contains the Augmentation's description.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Accordion_1 = __webpack_require__(/*! ./Accordion */ 161);
const AugmentationNames_1 = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
function AugmentationAccordion(props) {
let displayName = props.aug.name;
if (props.level != null) {
if (props.aug.name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
displayName += (` - Level ${props.level}`);
}
}
if (typeof props.aug.info === 'string') {
return (React.createElement(Accordion_1.Accordion, { headerContent: React.createElement(React.Fragment, null, displayName), panelContent: React.createElement("p", null,
React.createElement("span", { dangerouslySetInnerHTML: { __html: props.aug.info } }),
React.createElement("br", null),
React.createElement("br", null),
props.aug.stats) }));
}
return (React.createElement(Accordion_1.Accordion, { headerContent: React.createElement(React.Fragment, null, displayName), panelContent: React.createElement("p", null,
props.aug.info,
React.createElement("br", null),
React.createElement("br", null),
props.aug.stats) }));
}
exports.AugmentationAccordion = AugmentationAccordion;
/***/ }),
/* 643 */,
/* 644 */,
/* 645 */,
/* 646 */,
/* 647 */
/*!*********************************************!*\
!*** ./src/ui/React/StdButtonPurchased.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StdButtonPurchased = void 0;
/**
* Stateless button that represents something that has been purchased.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
class StdButtonPurchased extends React.Component {
constructor(props) {
super(props);
this.hasTooltip = this.hasTooltip.bind(this);
this.tooltip = this.tooltip.bind(this);
}
hasTooltip() {
return this.props.tooltip != null && this.props.tooltip !== "";
}
tooltip() {
if (!this.props.tooltip)
return "";
return this.props.tooltip;
}
render() {
let className = "std-button-bought";
if (this.hasTooltip()) {
className += " tooltip";
}
// Tooltip will be set using inner HTML
let tooltipMarkup = {
__html: "",
};
if (this.hasTooltip()) {
tooltipMarkup = {
__html: this.tooltip(),
};
}
return (React.createElement("button", { className: className, onClick: this.props.onClick, style: this.props.style },
this.props.text,
this.hasTooltip() &&
React.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: tooltipMarkup })));
}
}
exports.StdButtonPurchased = StdButtonPurchased;
/***/ }),
/* 648 */,
/* 649 */,
/* 650 */,
/* 651 */,
/* 652 */,
/* 653 */,
/* 654 */,
/* 655 */,
/* 656 */,
/* 657 */,
/* 658 */,
/* 659 */,
/* 660 */,
/* 661 */,
/* 662 */,
/* 663 */,
/* 664 */,
/* 665 */,
/* 666 */,
/* 667 */,
/* 668 */,
/* 669 */,
/* 670 */,
/* 671 */,
/* 672 */,
/* 673 */,
/* 674 */,
/* 675 */,
/* 676 */
/*!*********************************************!*\
!*** ./src/ScriptEditor/CursorPositions.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorPositions = exports.PositionTracker = void 0;
class PositionTracker {
constructor() {
this.positions = new Map();
}
saveCursor(filename, pos) {
this.positions.set(filename, pos);
}
getCursor(filename) {
const position = this.positions.get(filename);
if (!position) {
return {
row: -1,
column: -1,
};
}
return position;
}
}
exports.PositionTracker = PositionTracker;
exports.CursorPositions = new PositionTracker();
/***/ }),
/* 677 */
/*!************************************!*\
!*** ./src/Gang/GangMemberTask.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberTask = void 0;
class GangMemberTask {
// Defines tasks that Gang Members can work on
constructor(name, desc, isHacking, isCombat, params) {
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 };
}
}
exports.GangMemberTask = GangMemberTask;
/***/ }),
/* 678 */
/*!************************************!*\
!*** ./src/Gang/data/Constants.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangConstants = void 0;
exports.GangConstants = {
// Respect is divided by this to get rep gain
GangRespectToReputationRatio: 25,
MaximumGangMembers: 12,
CyclesPerTerritoryAndPowerUpdate: 100,
// Portion of upgrade multiplier that is kept after ascending
AscensionMultiplierRatio: .15,
// Names of possible Gangs
Names: [
"Slum Snakes",
"Tetrads",
"The Syndicate",
"The Dark Army",
"Speakers for the Dead",
"NiteSec",
"The Black Hand",
],
};
/***/ }),
/* 679 */
/*!*******************************************!*\
!*** ./utils/helpers/isValidIPAddress.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidIPAddress = void 0;
/**
* 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;
/***/ }),
/* 680 */
/*!**********************************!*\
!*** ./src/Server/BaseServer.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseServer = void 0;
/**
* Abstract Base Class for any Server object
*/
const CodingContracts_1 = __webpack_require__(/*! ../CodingContracts */ 93);
const Script_1 = __webpack_require__(/*! ../Script/Script */ 228);
const DirectoryHelpers_1 = __webpack_require__(/*! ../Terminal/DirectoryHelpers */ 86);
const TextFile_1 = __webpack_require__(/*! ../TextFile */ 137);
const ScriptHelpersTS_1 = __webpack_require__(/*! ../Script/ScriptHelpersTS */ 66);
const IPAddress_1 = __webpack_require__(/*! ../../utils/IPAddress */ 399);
const compareArrays_1 = __webpack_require__(/*! ../../utils/helpers/compareArrays */ 195);
class BaseServer {
constructor(params = { hostname: "", ip: IPAddress_1.createRandomIp() }) {
// Coding Contract files on this server
this.contracts = [];
// How many CPU cores this server has. Maximum of 8.
// Currently, this only affects hacking missions
this.cpuCores = 1;
// Flag indicating whether the FTP port is open
this.ftpPortOpen = false;
// Flag indicating whether player has admin/root access to this server
this.hasAdminRights = false;
// Hostname. Must be unique
this.hostname = "";
// Flag indicating whether HTTP Port is open
this.httpPortOpen = false;
// IP Address. Must be unique
this.ip = "";
// Flag indicating whether player is curently connected to this server
this.isConnectedTo = false;
// RAM (GB) available on this server
this.maxRam = 0;
// Message files AND Literature files on this Server
// For Literature files, this array contains only the filename (string)
// For Messages, it contains the actual Message object
// TODO Separate literature files into its own property
this.messages = [];
// Name of company/faction/etc. that this server belongs to.
// Optional, not applicable to all Servers
this.organizationName = "";
// Programs on this servers. Contains only the names of the programs
this.programs = [];
// RAM (GB) used. i.e. unavailable RAM
this.ramUsed = 0;
// RunningScript files on this server
this.runningScripts = [];
// Script files on this Server
this.scripts = [];
// Contains the IP Addresses of all servers that are immediately
// reachable from this one
this.serversOnNetwork = [];
// Flag indicating whether SMTP Port is open
this.smtpPortOpen = false;
// Flag indicating whether SQL Port is open
this.sqlPortOpen = false;
// Flag indicating whether the SSH Port is open
this.sshPortOpen = false;
// Text files on this server
this.textFiles = [];
this.ip = params.ip ? params.ip : IPAddress_1.createRandomIp();
this.hostname = params.hostname;
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;
}
addContract(contract) {
this.contracts.push(contract);
}
getContract(contractName) {
for (const contract of this.contracts) {
if (contract.fn === contractName) {
return contract;
}
}
return null;
}
/**
* Find an actively running script on this server
* @param scriptName - Filename of script to search for
* @param scriptArgs - Arguments that script is being run with
* @returns RunningScript for the specified active script
* Returns null if no such script can be found
*/
getRunningScript(scriptName, scriptArgs) {
for (const rs of this.runningScripts) {
if (rs.filename === scriptName && compareArrays_1.compareArrays(rs.args, scriptArgs)) {
return rs;
}
}
return null;
}
/**
* Given the name of the script, returns the corresponding
* Script object on the server (if it exists)
*/
getScript(scriptName) {
for (let i = 0; i < this.scripts.length; i++) {
if (this.scripts[i].filename === scriptName) {
return this.scripts[i];
}
}
return null;
}
/**
* Returns boolean indicating whether the given script is running on this server
*/
isRunning(fn) {
for (const runningScriptObj of this.runningScripts) {
if (runningScriptObj.filename === fn) {
return true;
}
}
return false;
}
removeContract(contract) {
if (contract instanceof CodingContracts_1.CodingContract) {
this.contracts = this.contracts.filter((c) => {
return c.fn !== contract.fn;
});
}
else {
this.contracts = this.contracts.filter((c) => {
return c.fn !== contract;
});
}
}
/**
* Remove a file from the server
* @param fn {string} Name of file to be deleted
* @returns {IReturnStatus} Return status object indicating whether or not file was deleted
*/
removeFile(fn) {
if (fn.endsWith(".exe") || fn.match(/^.+\.exe-\d+(?:\.\d*)?%-INC$/) != null) {
for (let i = 0; i < this.programs.length; ++i) {
if (this.programs[i] === fn) {
this.programs.splice(i, 1);
return { res: true };
}
}
}
else if (ScriptHelpersTS_1.isScriptFilename(fn)) {
for (let i = 0; i < this.scripts.length; ++i) {
if (this.scripts[i].filename === fn) {
if (this.isRunning(fn)) {
return {
res: false,
msg: "Cannot delete a script that is currently running!",
};
}
this.scripts.splice(i, 1);
return { res: true };
}
}
}
else if (fn.endsWith(".lit")) {
for (let i = 0; i < this.messages.length; ++i) {
const f = this.messages[i];
if (typeof f === "string" && f === fn) {
this.messages.splice(i, 1);
return { res: true };
}
}
}
else if (fn.endsWith(".txt")) {
for (let i = 0; i < this.textFiles.length; ++i) {
if (this.textFiles[i].fn === fn) {
this.textFiles.splice(i, 1);
return { res: true };
}
}
}
else if (fn.endsWith(".cct")) {
for (let i = 0; i < this.contracts.length; ++i) {
if (this.contracts[i].fn === fn) {
this.contracts.splice(i, 1);
return { res: true };
}
}
}
return { res: false, msg: "No such file exists" };
}
/**
* Called when a script is run on this server.
* All this function does is add a RunningScript object to the
* `runningScripts` array. It does NOT check whether the script actually can
* be run.
*/
runScript(script) {
this.runningScripts.push(script);
}
setMaxRam(ram) {
this.maxRam = ram;
}
/**
* Write to a script file
* Overwrites existing files. Creates new files if the script does not eixst
*/
writeToScriptFile(fn, code) {
const ret = { success: false, overwritten: false };
if (!DirectoryHelpers_1.isValidFilePath(fn) || !ScriptHelpersTS_1.isScriptFilename(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) {
const script = this.scripts[i];
script.code = code;
script.updateRamUsage(this.scripts);
script.markUpdated();
ret.overwritten = true;
ret.success = true;
return ret;
}
}
// Otherwise, create a new script
const newScript = new Script_1.Script(fn, code, this.ip, this.scripts);
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
writeToTextFile(fn, txt) {
const ret = { success: false, overwritten: false };
if (!DirectoryHelpers_1.isValidFilePath(fn) || !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
const newFile = new TextFile_1.TextFile(fn, txt);
this.textFiles.push(newFile);
ret.success = true;
return ret;
}
}
exports.BaseServer = BaseServer;
/***/ }),
/* 681 */
/*!*******************************************!*\
!*** ./src/ui/React/PopupCloseButton.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PopupCloseButton = void 0;
/**
* Close button for popup dialog boxes
* It creates an event handler such that pressing Esc will close the binded popup
*
* Should only be used in other React components, otherwise it may not be properly
* unmounted
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ 21));
const removeElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElement */ 224);
const PopupButton_1 = __webpack_require__(/*! ./PopupButton */ 1068);
class PopupCloseButton extends PopupButton_1.PopupButton {
constructor(props) {
super(props);
this.closePopup = this.closePopup.bind(this);
}
closePopup() {
if (this.props.onClose)
this.props.onClose();
let popup;
if (typeof this.props.popup === "string") {
popup = document.getElementById(this.props.popup);
}
else {
popup = this.props.popup;
}
// TODO Check if this is okay? This is essentially calling to unmount a
// parent component
if (popup instanceof HTMLElement) {
// Removes everything inside the wrapper container
ReactDOM.unmountComponentAtNode(popup);
removeElement_1.removeElement(popup); // Removes the wrapper container
}
}
render() {
const className = this.props.class ? this.props.class : "std-button";
return (React.createElement("button", { className: className, onClick: this.closePopup, style: this.props.style }, this.props.text));
}
}
exports.PopupCloseButton = PopupCloseButton;
/***/ }),
/* 682 */
/*!****************************!*\
!*** ./src/Crime/Crime.ts ***!
\****************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Crime = void 0;
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
class Crime {
constructor(name = "", type = "", time = 0, money = 0, difficulty = 0, karma = 0, params = {}) {
// Number representing the difficulty of the crime. Used for success chance calculations
this.difficulty = 0;
// Amount of karma lost for SUCCESSFULLY committing this crime
this.karma = 0;
// How many people die as a result of this crime
this.kills = 0;
// How much money is given by the
this.money = 0;
// Name of crime
this.name = "";
// Milliseconds it takes to attempt the crime
this.time = 0;
// Corresponding type in CONSTANTS. Contains a description for the crime activity
this.type = "";
// Weighting factors that determine how stats affect the success rate of this crime
this.hacking_success_weight = 0;
this.strength_success_weight = 0;
this.defense_success_weight = 0;
this.dexterity_success_weight = 0;
this.agility_success_weight = 0;
this.charisma_success_weight = 0;
// How much stat experience is granted by this crime
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.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;
}
commit(p, div = 1, singParams = null) {
if (div <= 0) {
div = 1;
}
p.startCrime(this.type, 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;
}
successRate(p) {
let chance = (this.hacking_success_weight * p.hacking_skill +
this.strength_success_weight * p.strength +
this.defense_success_weight * p.defense +
this.dexterity_success_weight * p.dexterity +
this.agility_success_weight * p.agility +
this.charisma_success_weight * p.charisma +
Constants_1.CONSTANTS.IntelligenceCrimeWeight * p.intelligence);
chance /= Constants_1.CONSTANTS.MaxSkillLevel;
chance /= this.difficulty;
chance *= p.crime_success_mult;
chance *= p.getIntelligenceBonus(1);
return Math.min(chance, 1);
}
}
exports.Crime = Crime;
/***/ }),
/* 683 */
/*!*************************************!*\
!*** ./src/PersonObjects/Person.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Person = exports.createTaskTracker = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
const CityNames_1 = __webpack_require__(/*! ../Locations/data/CityNames */ 42);
const Constants_1 = __webpack_require__(/*! ../Constants */ 11);
const skill_1 = __webpack_require__(/*! ./formulas/skill */ 121);
const intelligence_1 = __webpack_require__(/*! ./formulas/intelligence */ 411);
function createTaskTracker() {
return {
hack: 0,
str: 0,
def: 0,
dex: 0,
agi: 0,
cha: 0,
money: 0,
};
}
exports.createTaskTracker = createTaskTracker;
class Person {
constructor() {
/**
* Stats
*/
this.hacking_skill = 1;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
this.charisma = 1;
this.intelligence = 1;
this.hp = 10;
this.max_hp = 10;
/**
* Experience
*/
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;
/**
* Multipliers
*/
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.hacking_chance_mult = 1;
this.hacking_speed_mult = 1;
this.hacking_money_mult = 1;
this.hacking_grow_mult = 1;
this.company_rep_mult = 1;
this.faction_rep_mult = 1;
this.crime_money_mult = 1;
this.crime_success_mult = 1;
this.work_money_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.bladeburner_max_stamina_mult = 1;
this.bladeburner_stamina_gain_mult = 1;
this.bladeburner_analysis_mult = 1;
this.bladeburner_success_chance_mult = 1;
/**
* Augmentations
*/
this.augmentations = [];
this.queuedAugmentations = [];
/**
* City that the person is in
*/
this.city = CityNames_1.CityName.Sector12;
}
/**
* Updates this object's multipliers for the given augmentation
*/
applyAugmentation(aug) {
for (const mult in aug.mults) {
if (this[mult] == null) {
console.warn(`Augmentation has unrecognized multiplier property: ${mult}`);
}
else {
this[mult] *= aug.mults[mult];
}
}
}
/**
* Given an experience amount and stat multiplier, calculates the
* stat level. Stat-agnostic (same formula for every stat)
*/
calculateStat(exp, mult = 1) {
return skill_1.calculateSkill(exp, mult);
}
/**
* Calculate and return the amount of faction reputation earned per cycle
* when doing Field Work for a faction
*/
getFactionFieldWorkRepGain() {
const t = 0.9 * (this.hacking_skill / Constants_1.CONSTANTS.MaxSkillLevel +
this.strength / Constants_1.CONSTANTS.MaxSkillLevel +
this.defense / Constants_1.CONSTANTS.MaxSkillLevel +
this.dexterity / Constants_1.CONSTANTS.MaxSkillLevel +
this.agility / Constants_1.CONSTANTS.MaxSkillLevel +
this.charisma / Constants_1.CONSTANTS.MaxSkillLevel) / 5.5;
return t * this.faction_rep_mult;
}
/**
* Calculate and return the amount of faction reputation earned per cycle
* when doing Hacking Work for a faction
*/
getFactionHackingWorkRepGain() {
return this.hacking_skill / Constants_1.CONSTANTS.MaxSkillLevel * this.faction_rep_mult;
}
/**
* Calculate and return the amount of faction reputation earned per cycle
* when doing Security Work for a faction
*/
getFactionSecurityWorkRepGain() {
const t = 0.9 * (this.hacking_skill / Constants_1.CONSTANTS.MaxSkillLevel +
this.strength / Constants_1.CONSTANTS.MaxSkillLevel +
this.defense / Constants_1.CONSTANTS.MaxSkillLevel +
this.dexterity / Constants_1.CONSTANTS.MaxSkillLevel +
this.agility / Constants_1.CONSTANTS.MaxSkillLevel) / 4.5;
return t * this.faction_rep_mult;
}
/**
* Reset all multipliers to 1
*/
resetMultipliers() {
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.work_money_mult = 1;
}
/**
* Update all stat levels
*/
updateStatLevels() {
this.hacking_skill = Math.max(1, Math.floor(this.calculateStat(this.hacking_exp, this.hacking_mult * BitNodeMultipliers_1.BitNodeMultipliers.HackingLevelMultiplier)));
this.strength = Math.max(1, Math.floor(this.calculateStat(this.strength_exp, this.strength_mult * BitNodeMultipliers_1.BitNodeMultipliers.StrengthLevelMultiplier)));
this.defense = Math.max(1, Math.floor(this.calculateStat(this.defense_exp, this.defense_mult * BitNodeMultipliers_1.BitNodeMultipliers.DefenseLevelMultiplier)));
this.dexterity = Math.max(1, Math.floor(this.calculateStat(this.dexterity_exp, this.dexterity_mult * BitNodeMultipliers_1.BitNodeMultipliers.DexterityLevelMultiplier)));
this.agility = Math.max(1, Math.floor(this.calculateStat(this.agility_exp, this.agility_mult * BitNodeMultipliers_1.BitNodeMultipliers.AgilityLevelMultiplier)));
this.charisma = Math.max(1, Math.floor(this.calculateStat(this.charisma_exp, this.charisma_mult * BitNodeMultipliers_1.BitNodeMultipliers.CharismaLevelMultiplier)));
const ratio = this.hp / this.max_hp;
this.max_hp = Math.floor(10 + this.defense / 10);
this.hp = Math.round(this.max_hp * ratio);
}
getIntelligenceBonus(weight) {
return intelligence_1.calculateIntelligenceBonus(this.intelligence, weight);
}
}
exports.Person = Person;
/***/ }),
/* 684 */
/*!*************************************************************!*\
!*** ./src/PersonObjects/Sleeve/SleeveCovenantPurchases.ts ***!
\*************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSleevePurchasesFromCovenantPopup = exports.PopupId = exports.BaseCostPerSleeve = exports.MaxSleevesFromCovenant = void 0;
const CovenantPurchasesRoot_1 = __webpack_require__(/*! ./ui/CovenantPurchasesRoot */ 1072);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
exports.MaxSleevesFromCovenant = 5;
exports.BaseCostPerSleeve = 10e12;
exports.PopupId = "covenant-sleeve-purchases-popup";
function createSleevePurchasesFromCovenantPopup(p) {
createPopup_1.createPopup(exports.PopupId, CovenantPurchasesRoot_1.CovenantPurchasesRoot, { p: p, closeFn: () => createPopup_1.removePopup(exports.PopupId) });
}
exports.createSleevePurchasesFromCovenantPopup = createSleevePurchasesFromCovenantPopup;
/***/ }),
/* 685 */
/*!********************************!*\
!*** ./src/ui/React/Favor.tsx ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Favor = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function Favor(favor) {
return React.createElement("span", { className: "light-yellow samefont" }, typeof favor === 'number' ? numeralFormat_1.numeralWrapper.formatFavor(favor) : favor);
}
exports.Favor = Favor;
/***/ }),
/* 686 */
/*!**********************************!*\
!*** ./src/Bladeburner/Skill.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Skill = void 0;
const BitNodeMultipliers_1 = __webpack_require__(/*! ../BitNode/BitNodeMultipliers */ 19);
class Skill {
constructor(params = { name: "foo", desc: "foo" }) {
// Cost is in Skill Points
this.baseCost = 1;
// Additive cost increase per level
this.costInc = 1;
this.maxLvl = 0;
/**
* These benefits are additive. So total multiplier will be level (handled externally) times the
* effects below
*/
this.successChanceAll = 0;
this.successChanceStealth = 0;
this.successChanceKill = 0;
this.successChanceContract = 0;
this.successChanceOperation = 0;
/**
* This multiplier affects everything that increases synthoid population/community estimate
* e.g. Field analysis, Investigation Op, Undercover Op
*/
this.successChanceEstimate = 0;
this.actionTime = 0;
this.effHack = 0;
this.effStr = 0;
this.effDef = 0;
this.effDex = 0;
this.effAgi = 0;
this.effCha = 0;
this.stamina = 0;
this.money = 0;
this.expGain = 0;
if (!params.name) {
throw new Error("Failed to initialize Bladeburner Skill. No name was specified in ctor");
}
if (!params.desc) {
throw new Error("Failed to initialize Bladeburner Skills. No desc was specified in ctor");
}
this.name = params.name;
this.desc = params.desc;
this.baseCost = params.baseCost ? params.baseCost : 1;
this.costInc = params.costInc ? params.costInc : 1;
if (params.maxLvl) {
this.maxLvl = params.maxLvl;
}
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;
}
if (params.successChanceEstimate) {
this.successChanceEstimate = params.successChanceEstimate;
}
if (params.actionTime) {
this.actionTime = params.actionTime;
}
if (params.effHack) {
this.effHack = params.effHack;
}
if (params.effStr) {
this.effStr = params.effStr;
}
if (params.effDef) {
this.effDef = params.effDef;
}
if (params.effDex) {
this.effDex = params.effDex;
}
if (params.effAgi) {
this.effAgi = params.effAgi;
}
if (params.effCha) {
this.effCha = params.effCha;
}
if (params.stamina) {
this.stamina = params.stamina;
}
if (params.money) {
this.money = params.money;
}
if (params.expGain) {
this.expGain = params.expGain;
}
}
calculateCost(currentLevel) {
return Math.floor((this.baseCost + (currentLevel * this.costInc)) * BitNodeMultipliers_1.BitNodeMultipliers.BladeburnerSkillCost);
}
getMultiplier(name) {
if (name === "successChanceAll")
return this.successChanceAll;
if (name === "successChanceStealth")
return this.successChanceStealth;
if (name === "successChanceKill")
return this.successChanceKill;
if (name === "successChanceContract")
return this.successChanceContract;
if (name === "successChanceOperation")
return this.successChanceOperation;
if (name === "successChanceEstimate")
return this.successChanceEstimate;
if (name === "actionTime")
return this.actionTime;
if (name === "effHack")
return this.effHack;
if (name === "effStr")
return this.effStr;
if (name === "effDef")
return this.effDef;
if (name === "effDex")
return this.effDex;
if (name === "effAgi")
return this.effAgi;
if (name === "effCha")
return this.effCha;
if (name === "stamina")
return this.stamina;
if (name === "money")
return this.money;
if (name === "expGain")
return this.expGain;
return 0;
}
}
exports.Skill = Skill;
/***/ }),
/* 687 */
/*!***********************************!*\
!*** ./src/Bladeburner/Skills.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Skills = void 0;
const Skill_1 = __webpack_require__(/*! ./Skill */ 686);
const SkillNames_1 = __webpack_require__(/*! ./data/SkillNames */ 1086);
exports.Skills = {};
(function () {
exports.Skills[SkillNames_1.SkillNames.BladesIntuition] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.BladesIntuition,
desc: "Each level of this skill increases your success chance " +
"for all Contracts, Operations, and BlackOps by 3%",
baseCost: 3, costInc: 2.1,
successChanceAll: 3,
});
exports.Skills[SkillNames_1.SkillNames.Cloak] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.Cloak,
desc: "Each level of this skill increases your " +
"success chance in stealth-related Contracts, Operations, and BlackOps by 5.5%",
baseCost: 2, costInc: 1.1,
successChanceStealth: 5.5,
});
exports.Skills[SkillNames_1.SkillNames.ShortCircuit] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.ShortCircuit,
desc: "Each level of this skill increases your success chance " +
"in Contracts, Operations, and BlackOps that involve retirement by 5.5%",
baseCost: 2, costInc: 2.1,
successChanceKill: 5.5,
});
exports.Skills[SkillNames_1.SkillNames.DigitalObserver] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.DigitalObserver,
desc: "Each level of this skill increases your success chance in " +
"all Operations and BlackOps by 4%",
baseCost: 2, costInc: 2.1,
successChanceOperation: 4,
});
exports.Skills[SkillNames_1.SkillNames.Tracer] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.Tracer,
desc: "Each level of this skill increases your success chance in " +
"all Contracts by 4%",
baseCost: 2, costInc: 2.1,
successChanceContract: 4,
});
exports.Skills[SkillNames_1.SkillNames.Overclock] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.Overclock,
desc: "Each level of this skill decreases the time it takes " +
"to attempt a Contract, Operation, and BlackOp by 1% (Max Level: 90)",
baseCost: 3, costInc: 1.4, maxLvl: 90,
actionTime: 1,
});
exports.Skills[SkillNames_1.SkillNames.Reaper] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.Reaper,
desc: "Each level of this skill increases your effective combat stats for Bladeburner actions by 2%",
baseCost: 2, costInc: 2.1,
effStr: 2, effDef: 2, effDex: 2, effAgi: 2,
});
exports.Skills[SkillNames_1.SkillNames.EvasiveSystem] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.EvasiveSystem,
desc: "Each level of this skill increases your effective " +
"dexterity and agility for Bladeburner actions by 4%",
baseCost: 2, costInc: 2.1,
effDex: 4, effAgi: 4,
});
exports.Skills[SkillNames_1.SkillNames.Datamancer] = new Skill_1.Skill({
name: SkillNames_1.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,
});
exports.Skills[SkillNames_1.SkillNames.CybersEdge] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.CybersEdge,
desc: "Each level of this skill increases your max stamina by 2%",
baseCost: 1, costInc: 3,
stamina: 2,
});
exports.Skills[SkillNames_1.SkillNames.HandsOfMidas] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.HandsOfMidas,
desc: "Each level of this skill increases the amount of money you receive from Contracts by 10%",
baseCost: 2, costInc: 2.5,
money: 10,
});
exports.Skills[SkillNames_1.SkillNames.Hyperdrive] = new Skill_1.Skill({
name: SkillNames_1.SkillNames.Hyperdrive,
desc: "Each level of this skill increases the experience earned from Contracts, Operations, and BlackOps by 10%",
baseCost: 1, costInc: 2.5,
expGain: 10,
});
})();
/***/ }),
/* 688 */
/*!*******************************************!*\
!*** ./src/Bladeburner/GeneralActions.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralActions = void 0;
const Action_1 = __webpack_require__(/*! ./Action */ 490);
exports.GeneralActions = {};
(function () {
// General Actions
let actionName;
actionName = "Training";
exports.GeneralActions[actionName] = new Action_1.Action({
name: actionName,
desc: "Improve your abilities at the Bladeburner unit's specialized training " +
"center. Doing this gives experience for all combat stats and also " +
"increases your max stamina.",
});
actionName = "Field Analysis";
exports.GeneralActions[actionName] = new Action_1.Action({
name: actionName,
desc: "Mine and analyze Synthoid-related data. This improves the " +
"Bladeburner's unit intelligence on Synthoid locations and " +
"activities. Completing this action will improve the accuracy " +
"of your Synthoid population estimated in the current city.
" +
"Does NOT require stamina.",
});
actionName = "Recruitment";
exports.GeneralActions[actionName] = new Action_1.Action({
name: actionName,
desc: "Attempt to recruit members for your Bladeburner team. These members " +
"can help you conduct operations.
" +
"Does NOT require stamina.",
});
actionName = "Diplomacy";
exports.GeneralActions[actionName] = new Action_1.Action({
name: actionName,
desc: "Improve diplomatic relations with the Synthoid population. " +
"Completing this action will reduce the Chaos level in your current city.
" +
"Does NOT require stamina.",
});
actionName = "Hyperbolic Regeneration Chamber";
exports.GeneralActions[actionName] = new Action_1.Action({
name: actionName,
desc: "Enter cryogenic stasis using the Bladeburner division's hi-tech Regeneration Chamber. " +
"This will slowly heal your wounds and slightly increase your stamina.
",
});
})();
/***/ }),
/* 689 */
/*!**************************************!*\
!*** ./src/Bladeburner/Operation.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Operation = void 0;
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 142);
const Action_1 = __webpack_require__(/*! ./Action */ 490);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class Operation extends Action_1.Action {
constructor(params = null) {
super(params);
this.reqdRank = 100;
this.teamCount = 0;
if (params && params.reqdRank)
this.reqdRank = params.reqdRank;
if (params && params.teamCount)
this.teamCount = params.teamCount;
}
// For actions that have teams. To be implemented by subtypes.
getTeamSuccessBonus(inst) {
if (this.teamCount && this.teamCount > 0) {
this.teamCount = Math.min(this.teamCount, inst.teamSize);
const teamMultiplier = Math.pow(this.teamCount, 0.05);
return teamMultiplier;
}
return 1;
}
getActionTypeSkillSuccessBonus(inst) {
return inst.skillMultipliers.successChanceOperation;
}
getChaosDifficultyBonus(inst /*, params: ISuccessChanceParams*/) {
const city = inst.getCurrentCity();
if (city.chaos > Constants_1.BladeburnerConstants.ChaosThreshold) {
const diff = 1 + (city.chaos - Constants_1.BladeburnerConstants.ChaosThreshold);
const mult = Math.pow(diff, 0.1);
return mult;
}
return 1;
}
toJSON() {
return JSONReviver_1.Generic_toJSON("Operation", this);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Operation, value.data);
}
}
exports.Operation = Operation;
JSONReviver_1.Reviver.constructors.Operation = Operation;
/***/ }),
/* 690 */
/*!*******************************************!*\
!*** ./src/Bladeburner/BlackOperation.ts ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlackOperation = void 0;
const Operation_1 = __webpack_require__(/*! ./Operation */ 689);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class BlackOperation extends Operation_1.Operation {
constructor(params = null) {
super(params);
this.count = 1;
this.countGrowth = 0;
}
// To be implemented by subtypes
getActionTimePenalty() {
return 1.5;
}
getChaosCompetencePenalty( /*inst: IBladeburner, params: ISuccessChanceParams*/) {
return 1;
}
getChaosDifficultyBonus( /*inst: IBladeburner, params: ISuccessChanceParams*/) {
return 1;
}
toJSON() {
return JSONReviver_1.Generic_toJSON("BlackOperation", this);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(BlackOperation, value.data);
}
}
exports.BlackOperation = BlackOperation;
JSONReviver_1.Reviver.constructors.BlackOperation = BlackOperation;
/***/ }),
/* 691 */
/*!********************************************!*\
!*** ./src/Bladeburner/BlackOperations.ts ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlackOperations = void 0;
const BlackOperation_1 = __webpack_require__(/*! ./BlackOperation */ 690);
exports.BlackOperations = {};
(function () {
exports.BlackOperations["Operation Typhoon"] = new BlackOperation_1.BlackOperation({
name: "Operation Typhoon",
desc: "Obadiah Zenyatta is the leader of a RedWater PMC. It has long " +
"been known among the intelligence community that Zenyatta, along " +
"with the rest of the PMC, is a Synthoid.
" +
"The goal of Operation Typhoon is to find and eliminate " +
"Zenyatta and RedWater by any means necessary. After the task " +
"is completed, the actions must be covered up from the general public.",
baseDifficulty: 2000, reqdRank: 2.5e3,
rankGain: 50, rankLoss: 10, hpLoss: 100,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Zero"] = new BlackOperation_1.BlackOperation({
name: "Operation Zero",
desc: "AeroCorp is one of the world's largest defense contractors. " +
"Its leader, Steve Watataki, is thought to be a supporter of " +
"Synthoid rights. He must be removed.
" +
"The goal of Operation Zero is to covertly infiltrate AeroCorp and " +
"uncover any incriminating evidence or " +
"information against Watataki that will cause him to be removed " +
"from his position at AeroCorp. Incriminating evidence can be " +
"fabricated as a last resort. Be warned that AeroCorp has some of " +
"the most advanced security measures in the world.",
baseDifficulty: 2500, reqdRank: 5e3,
rankGain: 60, rankLoss: 15, hpLoss: 50,
weights: { hack: 0.2, str: 0.15, def: 0.15, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isStealth: true,
});
exports.BlackOperations["Operation X"] = new BlackOperation_1.BlackOperation({
name: "Operation X",
desc: "We have recently discovered an underground publication " +
"group called Samizdat. Even though most of their publications " +
"are nonsensical conspiracy theories, the average human is " +
"gullible enough to believe them. Many of their works discuss " +
"Synthoids and pose a threat to society. The publications are spreading " +
"rapidly in China and other Eastern countries.
" +
"Samizdat has done a good job of keeping hidden and anonymous. " +
"However, we've just received intelligence that their base of " +
"operations is in Ishima's underground sewer systems. Your task is to " +
"investigate the sewer systems, and eliminate Samizdat. They must " +
"never publish anything again.",
baseDifficulty: 3000, reqdRank: 7.5e3,
rankGain: 75, rankLoss: 15, hpLoss: 100,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Titan"] = new BlackOperation_1.BlackOperation({
name: "Operation Titan",
desc: "Several months ago Titan Laboratories' Bioengineering department " +
"was infiltrated by Synthoids. As far as we know, Titan Laboratories' " +
"management has no knowledge about this. We don't know what the " +
"Synthoids are up to, but the research that they could " +
"be conducting using Titan Laboraties' vast resources is potentially " +
"very dangerous.
" +
"Your goal is to enter and destroy the Bioengineering department's " +
"facility in Aevum. The task is not just to retire the Synthoids there, but " +
"also to destroy any information or research at the facility that " +
"is relevant to the Synthoids and their goals.",
baseDifficulty: 4000, reqdRank: 10e3,
rankGain: 100, rankLoss: 20, hpLoss: 100,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Ares"] = new BlackOperation_1.BlackOperation({
name: "Operation Ares",
desc: "One of our undercover agents, Agent Carter, has informed us of a " +
"massive weapons deal going down in Dubai between rogue Russian " +
"militants and a radical Synthoid community. These weapons are next-gen " +
"plasma and energy weapons. It is critical for the safety of humanity " +
"that this deal does not happen.
" +
"Your task is to intercept the deal. Leave no survivors.",
baseDifficulty: 5000, reqdRank: 12.5e3,
rankGain: 125, rankLoss: 20, hpLoss: 200,
weights: { hack: 0, str: 0.25, def: 0.25, dex: 0.25, agi: 0.25, cha: 0, int: 0 },
decays: { hack: 0, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Archangel"] = new BlackOperation_1.BlackOperation({
name: "Operation Archangel",
desc: "Our analysts have discovered that the popular Red Rabbit brothel in " +
"Amsterdam is run and 'staffed' by MK-VI Synthoids. Intelligence " +
"suggests that the profit from this brothel is used to fund a large " +
"black market arms trafficking operation.
" +
"The goal of this operation is to take out the leaders that are running " +
"the Red Rabbit brothel. Try to limit the number of other casualties, " +
"but do what you must to complete the mission.",
baseDifficulty: 7500, reqdRank: 15e3,
rankGain: 200, rankLoss: 20, hpLoss: 25,
weights: { hack: 0, str: 0.2, def: 0.2, dex: 0.3, agi: 0.3, cha: 0, int: 0 },
decays: { hack: 0, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Juggernaut"] = new BlackOperation_1.BlackOperation({
name: "Operation Juggernaut",
desc: "The CIA has just encountered a new security threat. A new " +
"criminal group, lead by a shadowy operative who calls himself " +
"Juggernaut, has been smuggling drugs and weapons (including " +
"suspected bioweapons) into Sector-12. We also have reason " +
"to believe the tried to break into one of Universal Energy's " +
"facilities in order to cause a city-wide blackout. The CIA " +
"suspects that Juggernaut is a heavily-augmented Synthoid, and " +
"have thus enlisted our help.
" +
"Your mission is to eradicate Juggernaut and his followers.",
baseDifficulty: 10e3, reqdRank: 20e3,
rankGain: 300, rankLoss: 40, hpLoss: 300,
weights: { hack: 0, str: 0.25, def: 0.25, dex: 0.25, agi: 0.25, cha: 0, int: 0 },
decays: { hack: 0, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Red Dragon"] = new BlackOperation_1.BlackOperation({
name: "Operation Red Dragon",
desc: "The Tetrads criminal organization is suspected of " +
"reverse-engineering the MK-VI Synthoid design. We believe " +
"they altered and possibly improved the design and began " +
"manufacturing their own Synthoid models in order to bolster " +
"their criminal activities.
" +
"Your task is to infiltrate and destroy the Tetrads' base of operations " +
"in Los Angeles. Intelligence tells us that their base houses " +
"one of their Synthoid manufacturing units.",
baseDifficulty: 12.5e3, reqdRank: 25e3,
rankGain: 500, rankLoss: 50, hpLoss: 500,
weights: { hack: 0.05, str: 0.2, def: 0.2, dex: 0.25, agi: 0.25, cha: 0, int: 0.05 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation K"] = new BlackOperation_1.BlackOperation({
name: "Operation K",
desc: "CODE RED SITUATION. Our intelligence tells us that VitaLife " +
"has discovered a new android cloning technology. This technology " +
"is supposedly capable of cloning Synthoid, not only physically " +
"but also their advanced AI modules. We do not believe that " +
"VitaLife is trying to use this technology illegally or " +
"maliciously, but if any Synthoids were able to infiltrate the " +
"corporation and take advantage of this technology then the " +
"results would be catastrophic.
" +
"We do not have the power or jurisdiction to shutdown this down " +
"through legal or political means, so we must resort to a covert " +
"operation. Your goal is to destroy this technology and eliminate " +
"anyone who was involved in its creation.",
baseDifficulty: 15e3, reqdRank: 30e3,
rankGain: 750, rankLoss: 60, hpLoss: 1000,
weights: { hack: 0.05, str: 0.2, def: 0.2, dex: 0.25, agi: 0.25, cha: 0, int: 0.05 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Deckard"] = new BlackOperation_1.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,
});
exports.BlackOperations["Operation Tyrell"] = new BlackOperation_1.BlackOperation({
name: "Operation Tyrell",
desc: "A week ago Blade Industries reported a small break-in at one " +
"of their Aevum Augmentation storage facitilities. We figured out " +
"that The Dark Army was behind the heist, and didn't think any more " +
"of it. However, we've just discovered that several known MK-VI Synthoids " +
"were part of that break-in group.
" +
"We cannot have Synthoids upgrading their already-enhanced abilities " +
"with Augmentations. Your task is to hunt down the associated Dark Army " +
"members and eliminate them.",
baseDifficulty: 25e3, reqdRank: 50e3,
rankGain: 1.5e3, rankLoss: 100, hpLoss: 500,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Wallace"] = new BlackOperation_1.BlackOperation({
name: "Operation Wallace",
desc: "Based on information gathered from Operation Tyrell, we've discovered " +
"that The Dark Army was well aware that there were Synthoids amongst " +
"their ranks. Even worse, we believe that The Dark Army is working " +
"together with other criminal organizations such as The Syndicate and " +
"that they are planning some sort of large-scale takeover of multiple major " +
"cities, most notably Aevum. We suspect that Synthoids have infiltrated " +
"the ranks of these criminal factions and are trying to stage another " +
"Synthoid uprising.
" +
"The best way to deal with this is to prevent it before it even happens. " +
"The goal of Operation Wallace is to destroy the Dark Army and " +
"Syndicate factions in Aevum immediately. Leave no survivors.",
baseDifficulty: 30e3, reqdRank: 75e3,
rankGain: 2e3, rankLoss: 150, hpLoss: 1500,
weights: { hack: 0, str: 0.24, def: 0.24, dex: 0.24, agi: 0.24, cha: 0, int: 0.04 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Shoulder of Orion"] = new BlackOperation_1.BlackOperation({
name: "Operation Shoulder of Orion",
desc: "China's Solaris Space Systems is secretly launching the first " +
"manned spacecraft in over a decade using Synthoids. We believe " +
"China is trying to establish the first off-world colonies.
" +
"The mission is to prevent this launch without instigating an " +
"international conflict. When you accept this mission you will be " +
"officially disavowed by the NSA and the national government until after you " +
"successfully return. In the event of failure, all of the operation's " +
"team members must not let themselves be captured alive.",
baseDifficulty: 35e3, reqdRank: 100e3,
rankGain: 2.5e3, rankLoss: 500, hpLoss: 1500,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isStealth: true,
});
exports.BlackOperations["Operation Hyron"] = new BlackOperation_1.BlackOperation({
name: "Operation Hyron",
desc: "Our intelligence tells us that Fulcrum Technologies is developing " +
"a quantum supercomputer using human brains as core " +
"processors. This supercomputer " +
"is rumored to be able to store vast amounts of data and " +
"perform computations unmatched by any other supercomputer on the " +
"planet. But more importantly, the use of organic human brains " +
"means that the supercomputer may be able to reason abstractly " +
"and become self-aware.
" +
"I do not need to remind you why sentient-level AIs pose a serious " +
"threat to all of mankind.
" +
"The research for this project is being conducted at one of Fulcrum " +
"Technologies secret facilities in Aevum, codenamed 'Alpha Ranch'. " +
"Infiltrate the compound, delete and destroy the work, and then find and kill the " +
"project lead.",
baseDifficulty: 40e3, reqdRank: 125e3,
rankGain: 3e3, rankLoss: 1e3, hpLoss: 500,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Morpheus"] = new BlackOperation_1.BlackOperation({
name: "Operation Morpheus",
desc: "DreamSense Technologies is an advertising company that uses " +
"special technology to transmit their ads into the peoples " +
"dreams and subconcious. They do this using broadcast transmitter " +
"towers. Based on information from our agents and informants in " +
"Chonqging, we have reason to believe that one of the broadcast " +
"towers there has been compromised by Synthoids and is being used " +
"to spread pro-Synthoid propaganda.
" +
"The mission is to destroy this broadcast tower. Speed and " +
"stealth are of the upmost important for this.",
baseDifficulty: 45e3, reqdRank: 150e3,
rankGain: 4e3, rankLoss: 1e3, hpLoss: 100,
weights: { hack: 0.05, str: 0.15, def: 0.15, dex: 0.3, agi: 0.3, cha: 0, int: 0.05 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isStealth: true,
});
exports.BlackOperations["Operation Ion Storm"] = new BlackOperation_1.BlackOperation({
name: "Operation Ion Storm",
desc: "Our analysts have uncovered a gathering of MK-VI Synthoids " +
"that have taken up residence in the Sector-12 Slums. We " +
"don't know if they are rogue Synthoids from the Uprising, " +
"but we do know that they have been stockpiling " +
"weapons, money, and other resources. This makes them dangerous.
" +
"This is a full-scale assault operation to find and retire all of these " +
"Synthoids in the Sector-12 Slums.",
baseDifficulty: 50e3, reqdRank: 175e3,
rankGain: 5e3, rankLoss: 1e3, hpLoss: 5000,
weights: { hack: 0, str: 0.24, def: 0.24, dex: 0.24, agi: 0.24, cha: 0, int: 0.04 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
isKill: true,
});
exports.BlackOperations["Operation Annihilus"] = new BlackOperation_1.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,
});
exports.BlackOperations["Operation Ultron"] = new BlackOperation_1.BlackOperation({
name: "Operation Ultron",
desc: "OmniTek Incorporated, the original designer and manufacturer of Synthoids, " +
"has notified us of a malfunction in their AI design. This malfunction, " +
"when triggered, causes MK-VI Synthoids to become radicalized and seek out " +
"the destruction of humanity. They say that this bug affects all MK-VI Synthoids, " +
"not just the rogue ones from the Uprising.
" +
"OmniTek has also told us they they believe someone has triggered this " +
"malfunction in a large group of MK-VI Synthoids, and that these newly-radicalized Synthoids " +
"are now amassing in Volhaven to form a terrorist group called Ultron.
" +
"Intelligence suggests Ultron is heavily armed and that their members are " +
"augmented. We believe Ultron is making moves to take control of " +
"and weaponize DeltaOne's Tactical High-Energy Satellite Laser Array (THESLA).
" +
"Throughout all of humanity's history, we have relied on " +
"technology to survive, conquer, and progress. Its advancement became our primary goal. " +
"And at the peak of human civilization technology turned into " +
"power. Global, absolute power.
" +
"It seems that the universe is not without a sense of irony.
" +
"The bits are all around us. The daemons that hold the Node " +
"together can manifest themselves in many different ways.
" +
"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)",
baseDifficulty: 75e3, reqdRank: 350e3,
rankGain: 20e3, rankLoss: 20e3, hpLoss: 20e3,
weights: { hack: 0.1, str: 0.2, def: 0.2, dex: 0.2, agi: 0.2, cha: 0, int: 0.1 },
decays: { hack: 0.6, str: 0.8, def: 0.8, dex: 0.8, agi: 0.8, cha: 0, int: 0.75 },
});
exports.BlackOperations["Operation Daedalus"] = new BlackOperation_1.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 },
});
})();
/***/ }),
/* 692 */
/*!*********************************************!*\
!*** ./src/Corporation/IndustryUpgrades.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndustryUpgrades = void 0;
// Industry upgrades
// The data structure is an array with the following format:
// [index in array, base price, price mult, benefit mult (if applicable), name, desc]
exports.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."],
};
/***/ }),
/* 693 */
/*!*****************************************************!*\
!*** ./src/Corporation/data/CorporationUpgrades.ts ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorporationUpgrades = void 0;
// Corporation Upgrades
// Upgrades for entire corporation, levelable upgrades
// The data structure is an array with the following format
// [index in Corporation upgrades array, base price, price mult, benefit mult (additive), name, desc]
exports.CorporationUpgrades = {
//Smart factories, increases production
"0": [0, 2e9, 1.06, 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.06, .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, 4e9, 1.1, .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 " +
"15 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.07, 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)."],
};
/***/ }),
/* 694 */
/*!***********************************************************!*\
!*** ./src/Corporation/data/CorporationUnlockUpgrades.ts ***!
\***********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorporationUnlockUpgrades = void 0;
// Corporation Unlock Upgrades
// Upgrades for entire corporation, unlocks features, either you have it or you dont
// The data structure is an array with the following format:
// [index in Corporation feature upgrades array, price, name, description]
exports.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, 25e9, "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 " +
"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."],
"5": [5, 500e9, "Shady Accounting",
"Utilize unscrupulous accounting practices and pay off government officials to save money " +
"on taxes. This reduces the dividend tax rate by 5%."],
"6": [6, 2e12, "Government Partnership",
"Help national governments further their agendas in exchange for lowered taxes. " +
"This reduces the dividend tax rate by 10%"],
};
/***/ }),
/* 695 */
/*!************************************!*\
!*** ./src/Faction/FactionInfo.ts ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FactionInfos = exports.FactionInfo = void 0;
/**
* 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;
}
offersWork() {
return this.offerFieldWork ||
this.offerHackingMission ||
this.offerHackingWork ||
this.offerSecurityWork;
}
}
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. " +
" " +
"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 what no other dares to do. We imagine. We create. We invent. We create what 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. " +
" " +
"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. " +
" " +
"Legal Insight - Business Instinct - Innovative Experience.", [], true, true, true, true),
"Blade Industries": new FactionInfo("Augmentation is Salvation.", [], true, true, true, true),
NWO: new FactionInfo("Humans don't truly desire freedom. They want to be observed, understood, and judged. They want to " +
"be given purpose and direction in life. That is why they created God. And that is why they 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("The Power of the Genome - Unlocked.", [], 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. It’s 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. " +
" " +
"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. " +
" " +
"So much pain. So many lives. Their darkness must end.", [], true, true, true, false),
NiteSec: new FactionInfo(" __..__ " +
" _.nITESECNIt. " +
" .-'NITESECNITESEc. " +
" .' NITESECNITESECn " +
" / NITESECNITESEC; " +
" : :NITESECNITESEC; " +
" ; $ NITESECNITESECN " +
" : _, ,N'ITESECNITESEC " +
" : .+^^`, : `NITESECNIT " +
" ) /), `-,-=,NITESECNI " +
" / ^ ,-;|NITESECN; " +
" / _.' '-';NITESECN " +
" ( , ,-''`^NITE' " +
" )` :`. .' " +
" )-- ; `- / " +
" \' _.-' : " +
" ( _.-' \. \ " +
" \------. \ \ " +
" \. \ \ " +
" \ _.nIt " +
" \ _.nITESECNi " +
" nITESECNIT^' \ " +
" NITE^' ___ \ " +
" / .gP''''Tp. \ " +
" : d' . `b \ " +
" ; d' o `b ; " +
" / d; `b| " +
" /, $; @ `: " +
" /' $$ ; " +
" .' $$b o | " +
" .' d$$$; : " +
" / .d$$$$; , ; " +
" d .dNITESEC $ | " +
" :bp.__.gNITESEC$$ :$ ; " +
" NITESECNITESECNIT $$b : ", [], 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, Honor, 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 only cares 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. " +
" " +
"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 righteously.", [], true, true, false, true),
CyberSec: new FactionInfo("The Internet is the first thing that was built that we don't fully understand, the largest " +
"experiment in anarchy that we have ever had. And as the world becomes increasingly dominated by it, " +
"society approaches the brink of total chaos. We serve only to protect society, to protect humanity, to " +
"protect the world from imminent collapse.", [], true, true, false, false),
// Special Factions
Bladeburners: new FactionInfo("It's too bad they won't live. But then again, who does?
);*/
const work = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
className: "character-divider"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
colSpan: "2"
}, "Work progress:")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
colSpan: "2"
}, "+", Object(_Reputation__WEBPACK_IMPORTED_MODULE_3__["Reputation"])(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].workRepGained), " rep")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
colSpan: "2"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
onClick: () => _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].startFocusing(),
id: "character-overview-options-button",
className: "character-overview-btn"
}, "Focus"))));
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-hp-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-hp-cell"
}, "HP:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-hp-text",
className: "character-hp-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatHp(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hp) + " / " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatHp(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].max_hp))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-money-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-money-cell"
}, "Money:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-money-text",
className: "character-money-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatMoney(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].money.toNumber()))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-hack-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-hack-cell"
}, "Hack:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-hack-text",
className: "character-hack-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-str-wrapper",
className: "character-divider"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-combat-cell"
}, "Str:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-str-text",
className: "character-combat-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].strength))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-def-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-combat-cell"
}, "Def:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-def-text",
className: "character-combat-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].defense))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-dex-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-combat-cell"
}, "Dex:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-dex-text",
className: "character-combat-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-agi-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-combat-cell"
}, "Agi:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-agi-text",
className: "character-combat-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].agility))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", {
id: "character-cha-wrapper",
className: "character-divider"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
className: "character-cha-cell"
}, "Cha:\xA0"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", {
id: "character-cha-text",
className: "character-cha-cell character-stat-cell"
}, _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_2__["numeralWrapper"].formatSkill(_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma))), _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence >= 1 && intelligence, _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].isWorking && !_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].focus && work)));
}
}
/***/ }),
/* 768 */
/*!**************************************!*\
!*** ./utils/helpers/clearObject.ts ***!
\**************************************/
/*! no static exports found */
/*! exports used: clearObject */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearObject = void 0;
/**
* 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
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
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;
/***/ }),
/* 769 */
/*!***************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectServerMethods.ts ***!
\***************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHacknetServer = exports.getUpgradeHomeRamCost = exports.getHomeComputer = exports.getCurrentServer = exports.hasTorRouter = void 0;
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
const HacknetServer_1 = __webpack_require__(/*! ../../Hacknet/HacknetServer */ 78);
const AllServers_1 = __webpack_require__(/*! ../../Server/AllServers */ 20);
const SpecialServerIps_1 = __webpack_require__(/*! ../../Server/SpecialServerIps */ 38);
function hasTorRouter() {
return SpecialServerIps_1.SpecialServerIps.hasOwnProperty("Darkweb Server");
}
exports.hasTorRouter = hasTorRouter;
function getCurrentServer() {
return AllServers_1.AllServers[this.currentServer];
}
exports.getCurrentServer = getCurrentServer;
function getHomeComputer() {
return AllServers_1.AllServers[this.homeComputer];
}
exports.getHomeComputer = getHomeComputer;
function getUpgradeHomeRamCost() {
//Calculate how many times ram has been upgraded (doubled)
const currentRam = this.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);
const cost = currentRam * Constants_1.CONSTANTS.BaseCostFor1GBOfRamHome * mult * BitNodeMultipliers_1.BitNodeMultipliers.HomeComputerRamCost;
return cost;
}
exports.getUpgradeHomeRamCost = getUpgradeHomeRamCost;
function createHacknetServer() {
const numOwned = this.hacknetNodes.length;
const name = `hacknet-node-${numOwned}`;
const server = new HacknetServer_1.HacknetServer({
adminRights: true,
hostname: name,
ip: AllServers_1.createUniqueRandomIp(),
// player: this,
});
this.hacknetNodes.push(server.ip);
// Configure the HacknetServer to actually act as a Server
AllServers_1.AddToAllServers(server);
const homeComputer = this.getHomeComputer();
homeComputer.serversOnNetwork.push(server.ip);
server.serversOnNetwork.push(homeComputer.ip);
return server;
}
exports.createHacknetServer = createHacknetServer;
/***/ }),
/* 770 */
/*!***************************************!*\
!*** ./src/Exploits/applyExploits.ts ***!
\***************************************/
/*! no static exports found */
/*! exports used: applyExploit */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyExploit = void 0;
const Player_1 = __webpack_require__(/*! ../Player */ 2);
function applyExploit() {
if (Player_1.Player.exploits && Player_1.Player.exploits.length === 0) {
return;
}
const inc = Math.pow(1.001, Player_1.Player.exploits.length);
const dec = Math.pow(0.999, Player_1.Player.exploits.length);
Player_1.Player.hacking_chance_mult *= inc;
Player_1.Player.hacking_speed_mult *= inc;
Player_1.Player.hacking_money_mult *= inc;
Player_1.Player.hacking_grow_mult *= inc;
Player_1.Player.hacking_mult *= inc;
Player_1.Player.strength_mult *= inc;
Player_1.Player.defense_mult *= inc;
Player_1.Player.dexterity_mult *= inc;
Player_1.Player.agility_mult *= inc;
Player_1.Player.charisma_mult *= inc;
Player_1.Player.hacking_exp_mult *= inc;
Player_1.Player.strength_exp_mult *= inc;
Player_1.Player.defense_exp_mult *= inc;
Player_1.Player.dexterity_exp_mult *= inc;
Player_1.Player.agility_exp_mult *= inc;
Player_1.Player.charisma_exp_mult *= inc;
Player_1.Player.company_rep_mult *= inc;
Player_1.Player.faction_rep_mult *= inc;
Player_1.Player.crime_money_mult *= inc;
Player_1.Player.crime_success_mult *= inc;
Player_1.Player.hacknet_node_money_mult *= inc;
Player_1.Player.hacknet_node_purchase_cost_mult *= dec;
Player_1.Player.hacknet_node_ram_cost_mult *= dec;
Player_1.Player.hacknet_node_core_cost_mult *= dec;
Player_1.Player.hacknet_node_level_cost_mult *= dec;
Player_1.Player.work_money_mult *= inc;
}
exports.applyExploit = applyExploit;
/***/ }),
/* 771 */
/*!*******************************************!*\
!*** ./src/SourceFile/applySourceFile.ts ***!
\*******************************************/
/*! no static exports found */
/*! exports used: applySourceFile */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applySourceFile = void 0;
const SourceFiles_1 = __webpack_require__(/*! ./SourceFiles */ 227);
const Player_1 = __webpack_require__(/*! ../Player */ 2);
function applySourceFile(srcFile) {
const srcFileKey = "SourceFile" + srcFile.n;
const sourceFileObject = SourceFiles_1.SourceFiles[srcFileKey];
if (sourceFileObject == null) {
console.error(`Invalid source file number: ${srcFile.n}`);
return;
}
switch (srcFile.n) {
case 1: { // The Source Genesis
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (16 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
const decMult = 1 - (mult / 100);
Player_1.Player.hacking_chance_mult *= incMult;
Player_1.Player.hacking_speed_mult *= incMult;
Player_1.Player.hacking_money_mult *= incMult;
Player_1.Player.hacking_grow_mult *= incMult;
Player_1.Player.hacking_mult *= incMult;
Player_1.Player.strength_mult *= incMult;
Player_1.Player.defense_mult *= incMult;
Player_1.Player.dexterity_mult *= incMult;
Player_1.Player.agility_mult *= incMult;
Player_1.Player.charisma_mult *= incMult;
Player_1.Player.hacking_exp_mult *= incMult;
Player_1.Player.strength_exp_mult *= incMult;
Player_1.Player.defense_exp_mult *= incMult;
Player_1.Player.dexterity_exp_mult *= incMult;
Player_1.Player.agility_exp_mult *= incMult;
Player_1.Player.charisma_exp_mult *= incMult;
Player_1.Player.company_rep_mult *= incMult;
Player_1.Player.faction_rep_mult *= incMult;
Player_1.Player.crime_money_mult *= incMult;
Player_1.Player.crime_success_mult *= incMult;
Player_1.Player.hacknet_node_money_mult *= incMult;
Player_1.Player.hacknet_node_purchase_cost_mult *= decMult;
Player_1.Player.hacknet_node_ram_cost_mult *= decMult;
Player_1.Player.hacknet_node_core_cost_mult *= decMult;
Player_1.Player.hacknet_node_level_cost_mult *= decMult;
Player_1.Player.work_money_mult *= incMult;
break;
}
case 2: { // Rise of the Underworld
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (24 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.crime_money_mult *= incMult;
Player_1.Player.crime_success_mult *= incMult;
Player_1.Player.charisma_mult *= incMult;
break;
}
case 3: { // Corporatocracy
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.charisma_mult *= incMult;
Player_1.Player.work_money_mult *= incMult;
break;
}
case 4: { // The Singularity
// No effects, just gives access to Singularity functions
break;
}
case 5: { // Artificial Intelligence
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.hacking_chance_mult *= incMult;
Player_1.Player.hacking_speed_mult *= incMult;
Player_1.Player.hacking_money_mult *= incMult;
Player_1.Player.hacking_grow_mult *= incMult;
Player_1.Player.hacking_mult *= incMult;
Player_1.Player.hacking_exp_mult *= incMult;
break;
}
case 6: { // Bladeburner
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.strength_exp_mult *= incMult;
Player_1.Player.defense_exp_mult *= incMult;
Player_1.Player.dexterity_exp_mult *= incMult;
Player_1.Player.agility_exp_mult *= incMult;
Player_1.Player.strength_mult *= incMult;
Player_1.Player.defense_mult *= incMult;
Player_1.Player.dexterity_mult *= incMult;
Player_1.Player.agility_mult *= incMult;
break;
}
case 7: { // Bladeburner 2079
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (8 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.bladeburner_max_stamina_mult *= incMult;
Player_1.Player.bladeburner_stamina_gain_mult *= incMult;
Player_1.Player.bladeburner_analysis_mult *= incMult;
Player_1.Player.bladeburner_success_chance_mult *= incMult;
break;
}
case 8: { // Ghost of Wall Street
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (12 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.hacking_grow_mult *= incMult;
break;
}
case 9: { // Hacktocracy
// This has non-multiplier effects
break;
}
case 10: { // Digital Carbon
// No effects, just grants sleeves
break;
}
case 11: { // The Big Crash
let mult = 0;
for (let i = 0; i < srcFile.lvl; ++i) {
mult += (32 / (Math.pow(2, i)));
}
const incMult = 1 + (mult / 100);
Player_1.Player.work_money_mult *= incMult;
Player_1.Player.company_rep_mult *= incMult;
break;
}
case 12: // The Recursion
// No effects, grants neuroflux.
break;
default:
console.error(`Invalid source file number: ${srcFile.n}`);
break;
}
sourceFileObject.owned = true;
}
exports.applySourceFile = applySourceFile;
/***/ }),
/* 772 */
/*!*****************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectGeneralMethods.jsx ***!
\*****************************************************************/
/*! exports provided: init, prestigeAugmentation, prestigeSourceFile, receiveInvite, calculateSkill, updateSkillLevels, resetMultipliers, hasProgram, setMoney, gainMoney, loseMoney, canAfford, recordMoneySource, gainHackingExp, gainStrengthExp, gainDefenseExp, gainDexterityExp, gainAgilityExp, gainCharismaExp, gainIntelligenceExp, queryStatFromString, resetWorkStatus, processWorkEarnings, startWork, cancelationPenalty, work, finishWork, startWorkPartTime, workPartTime, finishWorkPartTime, startFocusing, stopFocusing, startFactionWork, startFactionHackWork, startFactionFieldWork, startFactionSecurityWork, workForFaction, finishFactionWork, getWorkMoneyGain, getWorkHackExpGain, getWorkStrExpGain, getWorkDefExpGain, getWorkDexExpGain, getWorkAgiExpGain, getWorkChaExpGain, getWorkRepGain, startCreateProgramWork, createProgramWork, finishCreateProgramWork, startClass, takeClass, finishClass, startCrime, commitCrime, finishCrime, singularityStopWork, takeDamage, regenerateHp, hospitalize, applyForJob, getNextCompanyPosition, quitJob, applyForSoftwareJob, applyForSoftwareConsultantJob, applyForItJob, applyForSecurityEngineerJob, applyForNetworkEngineerJob, applyForBusinessJob, applyForBusinessConsultantJob, applyForSecurityJob, applyForAgentJob, applyForEmployeeJob, applyForPartTimeEmployeeJob, applyForWaiterJob, applyForPartTimeWaiterJob, isQualified, reapplyAllAugmentations, reapplyAllSourceFiles, checkForFactionInvitations, setBitNodeNumber, queueAugmentation, gainCodingContractReward, travel, gotoLocation, canAccessResleeving, giveExploit, getIntelligenceBonus, getCasinoWinnings */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeAugmentation", function() { return prestigeAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeSourceFile", function() { return prestigeSourceFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "receiveInvite", function() { return receiveInvite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateSkill", function() { return calculateSkill; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateSkillLevels", function() { return updateSkillLevels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetMultipliers", function() { return resetMultipliers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasProgram", function() { return hasProgram; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMoney", function() { return setMoney; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainMoney", function() { return gainMoney; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loseMoney", function() { return loseMoney; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canAfford", function() { return canAfford; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recordMoneySource", function() { return recordMoneySource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainHackingExp", function() { return gainHackingExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainStrengthExp", function() { return gainStrengthExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainDefenseExp", function() { return gainDefenseExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainDexterityExp", function() { return gainDexterityExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainAgilityExp", function() { return gainAgilityExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainCharismaExp", function() { return gainCharismaExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainIntelligenceExp", function() { return gainIntelligenceExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryStatFromString", function() { return queryStatFromString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetWorkStatus", function() { return resetWorkStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processWorkEarnings", function() { return processWorkEarnings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startWork", function() { return startWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cancelationPenalty", function() { return cancelationPenalty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "work", function() { return work; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishWork", function() { return finishWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startWorkPartTime", function() { return startWorkPartTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workPartTime", function() { return workPartTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishWorkPartTime", function() { return finishWorkPartTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startFocusing", function() { return startFocusing; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stopFocusing", function() { return stopFocusing; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startFactionWork", function() { return startFactionWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startFactionHackWork", function() { return startFactionHackWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startFactionFieldWork", function() { return startFactionFieldWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startFactionSecurityWork", function() { return startFactionSecurityWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workForFaction", function() { return workForFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishFactionWork", function() { return finishFactionWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkMoneyGain", function() { return getWorkMoneyGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkHackExpGain", function() { return getWorkHackExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkStrExpGain", function() { return getWorkStrExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkDefExpGain", function() { return getWorkDefExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkDexExpGain", function() { return getWorkDexExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkAgiExpGain", function() { return getWorkAgiExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkChaExpGain", function() { return getWorkChaExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWorkRepGain", function() { return getWorkRepGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startCreateProgramWork", function() { return startCreateProgramWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createProgramWork", function() { return createProgramWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishCreateProgramWork", function() { return finishCreateProgramWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startClass", function() { return startClass; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeClass", function() { return takeClass; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishClass", function() { return finishClass; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startCrime", function() { return startCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitCrime", function() { return commitCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finishCrime", function() { return finishCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "singularityStopWork", function() { return singularityStopWork; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeDamage", function() { return takeDamage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "regenerateHp", function() { return regenerateHp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hospitalize", function() { return hospitalize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForJob", function() { return applyForJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextCompanyPosition", function() { return getNextCompanyPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "quitJob", function() { return quitJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForSoftwareJob", function() { return applyForSoftwareJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForSoftwareConsultantJob", function() { return applyForSoftwareConsultantJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForItJob", function() { return applyForItJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForSecurityEngineerJob", function() { return applyForSecurityEngineerJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForNetworkEngineerJob", function() { return applyForNetworkEngineerJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForBusinessJob", function() { return applyForBusinessJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForBusinessConsultantJob", function() { return applyForBusinessConsultantJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForSecurityJob", function() { return applyForSecurityJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForAgentJob", function() { return applyForAgentJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForEmployeeJob", function() { return applyForEmployeeJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForPartTimeEmployeeJob", function() { return applyForPartTimeEmployeeJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForWaiterJob", function() { return applyForWaiterJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyForPartTimeWaiterJob", function() { return applyForPartTimeWaiterJob; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isQualified", function() { return isQualified; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reapplyAllAugmentations", function() { return reapplyAllAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reapplyAllSourceFiles", function() { return reapplyAllSourceFiles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkForFactionInvitations", function() { return checkForFactionInvitations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBitNodeNumber", function() { return setBitNodeNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queueAugmentation", function() { return queueAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gainCodingContractReward", function() { return gainCodingContractReward; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "travel", function() { return travel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gotoLocation", function() { return gotoLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canAccessResleeving", function() { return canAccessResleeving; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "giveExploit", function() { return giveExploit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIntelligenceBonus", function() { return getIntelligenceBonus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCasinoWinnings", function() { return getCasinoWinnings; });
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
/* harmony import */ var _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Augmentation/AugmentationHelpers */ 79);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Augmentation/PlayerOwnedAugmentation */ 196);
/* harmony import */ var _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
/* harmony import */ var _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../CodingContracts */ 93);
/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Company/Company */ 138);
/* harmony import */ var _Company_Company__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Company_Company__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Company/Companies */ 33);
/* harmony import */ var _Company_Companies__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Company_Companies__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Company/GetNextCompanyPosition */ 456);
/* harmony import */ var _Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Company/GetJobRequirementText */ 442);
/* harmony import */ var _Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Company_GetJobRequirementText__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Company/CompanyPositions */ 52);
/* harmony import */ var _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Company/data/companypositionnames */ 58);
/* harmony import */ var _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Constants */ 11);
/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_Constants__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Programs/Programs */ 30);
/* harmony import */ var _Programs_Programs__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Crime/CrimeHelpers */ 246);
/* harmony import */ var _Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Crime_Crimes__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Crime/Crimes */ 169);
/* harmony import */ var _Crime_Crimes__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_Crime_Crimes__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../engine */ 15);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Faction/Faction */ 125);
/* harmony import */ var _Faction_Faction__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Faction_Faction__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Faction/FactionHelpers */ 71);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Gang/AllGangs */ 85);
/* harmony import */ var _Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Hacknet/HacknetHelpers */ 25);
/* harmony import */ var _Locations_Cities__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Locations/Cities */ 192);
/* harmony import */ var _Locations_Cities__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_Locations_Cities__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _Locations_Locations__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Locations/Locations */ 408);
/* harmony import */ var _Locations_Locations__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_Locations_Locations__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Locations/data/CityNames */ 42);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Locations/data/LocationNames */ 40);
/* harmony import */ var _Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../PersonObjects/Sleeve/Sleeve */ 178);
/* harmony import */ var _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _formulas_skill__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../formulas/skill */ 121);
/* harmony import */ var _formulas_skill__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _formulas_intelligence__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../formulas/intelligence */ 411);
/* harmony import */ var _formulas_intelligence__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_formulas_intelligence__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _formulas_reputation__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../formulas/reputation */ 109);
/* harmony import */ var _formulas_reputation__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../../Server/AllServers */ 20);
/* harmony import */ var _Server_AllServers__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_Server_AllServers__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../../Server/ServerHelpers */ 22);
/* harmony import */ var _Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../../Settings/Settings */ 24);
/* harmony import */ var _Settings_Settings__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_Settings_Settings__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../../Server/SpecialServerIps */ 38);
/* harmony import */ var _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _SourceFile_applySourceFile__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../../SourceFile/applySourceFile */ 771);
/* harmony import */ var _SourceFile_applySourceFile__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_applySourceFile__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _Exploits_applyExploits__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ../../Exploits/applyExploits */ 770);
/* harmony import */ var _Exploits_applyExploits__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_Exploits_applyExploits__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../../SourceFile/SourceFiles */ 227);
/* harmony import */ var _SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFiles__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var _StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ../../StockMarket/PlayerInfluencing */ 300);
/* harmony import */ var _StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _Hospital_Hospital__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ../../Hospital/Hospital */ 412);
/* harmony import */ var _Hospital_Hospital__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_Hospital_Hospital__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! decimal.js */ 65);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../../utils/MoneySourceTracker */ 179);
/* harmony import */ var _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ../../../utils/uiHelpers/clearEventListeners */ 49);
/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ../../ui/React/Reputation */ 59);
/* harmony import */ var _ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ../../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _ui_React_ReputationRate__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ../../ui/React/ReputationRate */ 441);
/* harmony import */ var _ui_React_ReputationRate__WEBPACK_IMPORTED_MODULE_49___default = /*#__PURE__*/__webpack_require__.n(_ui_React_ReputationRate__WEBPACK_IMPORTED_MODULE_49__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! react-dom */ 21);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_51__);
const CYCLES_PER_SEC = 1000 / _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MilliPerCycle;
function init() {
/* Initialize Player's home computer */
var t_homeComp = Object(_Server_ServerHelpers__WEBPACK_IMPORTED_MODULE_31__["safetlyCreateUniqueServer"])({
adminRights: true,
hostname: "home",
ip: Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["createUniqueRandomIp"])(),
isConnectedTo: true,
maxRam: 8,
organizationName: "Home PC",
purchasedByPlayer: true
});
this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
Object(_Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AddToAllServers"])(t_homeComp);
this.getHomeComputer().programs.push(_Programs_Programs__WEBPACK_IMPORTED_MODULE_13__["Programs"].NukeProgram.name);
}
function prestigeAugmentation() {
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_40__["default"](1000);
this.city = _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Sector12;
this.location = "";
this.companyName = "";
this.jobs = {};
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.resleeves = [];
for (let i = 0; i < this.sleeves.length; ++i) {
if (this.sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26__["Sleeve"]) {
if (this.sleeves[i].shock >= 100) {
this.sleeves[i].synchronize(this);
} else {
this.sleeves[i].shockRecovery(this);
}
}
}
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(); // Statistics Trackers
this.playtimeSinceLastAug = 0;
this.scriptProdSinceLastAug = 0;
this.moneySourceA.reset();
this.hacknetNodes.length = 0;
this.hashManager.prestige(); // Re-calculate skills and reset HP
this.updateSkillLevels();
this.hp = this.max_hp;
}
function prestigeSourceFile() {
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_40__["default"](1000);
this.city = _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Sector12;
this.location = "";
this.companyName = "";
this.jobs = {};
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.augmentations = [];
this.resleeves = []; // Duplicate sleeves are reset to level 1 every Bit Node (but the number of sleeves you have persists)
this.sleeves.length = _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__["SourceFileFlags"][10] + this.sleevesFromCovenant;
for (let i = 0; i < this.sleeves.length; ++i) {
if (this.sleeves[i] instanceof _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26__["Sleeve"]) {
this.sleeves[i].prestige(this);
} else {
this.sleeves[i] = new _PersonObjects_Sleeve_Sleeve__WEBPACK_IMPORTED_MODULE_26__["Sleeve"](this);
}
}
const characterMenuHeader = document.getElementById("character-menu-header");
if (characterMenuHeader instanceof HTMLElement) {
characterMenuHeader.click();
characterMenuHeader.click();
}
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.hashManager.prestige(); // Gang
this.gang = null;
Object(_Gang_AllGangs__WEBPACK_IMPORTED_MODULE_20__["resetGangs"])(); // Reset Stock market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
this.has4SData = false;
this.has4SDataTixApi = false; // BitNode 3: Corporatocracy
this.corporation = 0; // Statistics trackers
this.playtimeSinceLastAug = 0;
this.playtimeSinceLastBitnode = 0;
this.scriptProdSinceLastAug = 0;
this.moneySourceA.reset();
this.moneySourceB.reset();
this.updateSkillLevels();
this.hp = this.max_hp;
}
function receiveInvite(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
function calculateSkill(exp, mult = 1) {
return Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(exp, mult);
}
function updateSkillLevels() {
this.hacking_skill = Math.max(1, Math.floor(this.calculateSkill(this.hacking_exp, this.hacking_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].HackingLevelMultiplier)));
this.strength = Math.max(1, Math.floor(this.calculateSkill(this.strength_exp, this.strength_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].StrengthLevelMultiplier)));
this.defense = Math.max(1, Math.floor(this.calculateSkill(this.defense_exp, this.defense_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].DefenseLevelMultiplier)));
this.dexterity = Math.max(1, Math.floor(this.calculateSkill(this.dexterity_exp, this.dexterity_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].DexterityLevelMultiplier)));
this.agility = Math.max(1, Math.floor(this.calculateSkill(this.agility_exp, this.agility_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].AgilityLevelMultiplier)));
this.charisma = Math.max(1, Math.floor(this.calculateSkill(this.charisma_exp, this.charisma_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CharismaLevelMultiplier)));
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);
this.hp = Math.round(this.max_hp * ratio);
}
function resetMultipliers() {
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;
}
function hasProgram(programName) {
const home = this.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;
}
function setMoney(money) {
if (isNaN(money)) {
console.error("NaN passed into Player.setMoney()");
return;
}
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_40__["default"](money);
}
function gainMoney(money) {
if (isNaN(money)) {
console.error("NaN passed into Player.gainMoney()");
return;
}
this.money = this.money.plus(money);
}
function loseMoney(money) {
if (isNaN(money)) {
console.error("NaN passed into Player.loseMoney()");
return;
}
if (this.money.eq(Infinity) && money === Infinity) return;
this.money = this.money.minus(money);
}
function canAfford(cost) {
if (isNaN(cost)) {
console.error(`NaN passed into Player.canAfford()`);
return false;
}
return this.money.gte(cost);
}
function recordMoneySource(amt, source) {
if (!(this.moneySourceA instanceof _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__["MoneySourceTracker"])) {
console.warn(`Player.moneySourceA was not properly initialized. Resetting`);
this.moneySourceA = new _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__["MoneySourceTracker"]();
}
if (!(this.moneySourceB instanceof _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__["MoneySourceTracker"])) {
console.warn(`Player.moneySourceB was not properly initialized. Resetting`);
this.moneySourceB = new _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_42__["MoneySourceTracker"]();
}
this.moneySourceA.record(amt, source);
this.moneySourceB.record(amt, source);
}
function gainHackingExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into Player.gainHackingExp()");
return;
}
this.hacking_exp += exp;
if (this.hacking_exp < 0) {
this.hacking_exp = 0;
}
this.hacking_skill = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.hacking_exp, this.hacking_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].HackingLevelMultiplier);
}
function gainStrengthExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into Player.gainStrengthExp()");
return;
}
this.strength_exp += exp;
if (this.strength_exp < 0) {
this.strength_exp = 0;
}
this.strength = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.strength_exp, this.strength_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].StrengthLevelMultiplier);
}
function gainDefenseExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into player.gainDefenseExp()");
return;
}
this.defense_exp += exp;
if (this.defense_exp < 0) {
this.defense_exp = 0;
}
this.defense = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.defense_exp, this.defense_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].DefenseLevelMultiplier);
}
function gainDexterityExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into Player.gainDexterityExp()");
return;
}
this.dexterity_exp += exp;
if (this.dexterity_exp < 0) {
this.dexterity_exp = 0;
}
this.dexterity = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.dexterity_exp, this.dexterity_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].DexterityLevelMultiplier);
}
function gainAgilityExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into Player.gainAgilityExp()");
return;
}
this.agility_exp += exp;
if (this.agility_exp < 0) {
this.agility_exp = 0;
}
this.agility = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.agility_exp, this.agility_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].AgilityLevelMultiplier);
}
function gainCharismaExp(exp) {
if (isNaN(exp)) {
console.error("ERR: NaN passed into Player.gainCharismaExp()");
return;
}
this.charisma_exp += exp;
if (this.charisma_exp < 0) {
this.charisma_exp = 0;
}
this.charisma = Object(_formulas_skill__WEBPACK_IMPORTED_MODULE_27__["calculateSkill"])(this.charisma_exp, this.charisma_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CharismaLevelMultiplier);
}
function gainIntelligenceExp(exp) {
if (isNaN(exp)) {
console.error("ERROR: NaN passed into Player.gainIntelligenceExp()");
return;
}
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__["SourceFileFlags"][5] > 0 || this.intelligence > 0) {
this.intelligence_exp += exp;
}
} //Given a string expression like "str" or "strength", returns the given stat
function queryStatFromString(str) {
const tempStr = str.toLowerCase();
if (tempStr.includes("hack")) {
return this.hacking_skill;
}
if (tempStr.includes("str")) {
return this.strength;
}
if (tempStr.includes("def")) {
return this.defense;
}
if (tempStr.includes("dex")) {
return this.dexterity;
}
if (tempStr.includes("agi")) {
return this.agility;
}
if (tempStr.includes("cha")) {
return this.charisma;
}
if (tempStr.includes("int")) {
return this.intelligence;
}
}
/******* Working functions *******/
function resetWorkStatus(generalType, group, workType) {
if (generalType === this.workType && group === this.companyName) return;
if (generalType === this.workType && group === this.currentWorkFactionName && workType === this.factionWorkType) return;
if (this.isWorking) this.singularityStopWork();
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 = "";
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.unmountComponentAtNode(document.getElementById("work-in-progress-text"));
}
function processWorkEarnings(numCycles = 1) {
const focusBonus = this.focus ? 1 : 0.8;
const hackExpGain = focusBonus * this.workHackExpGainRate * numCycles;
const strExpGain = focusBonus * this.workStrExpGainRate * numCycles;
const defExpGain = focusBonus * this.workDefExpGainRate * numCycles;
const dexExpGain = focusBonus * this.workDexExpGainRate * numCycles;
const agiExpGain = focusBonus * this.workAgiExpGainRate * numCycles;
const chaExpGain = focusBonus * 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);
if (this.className) {
this.recordMoneySource(moneyGain, "class");
} else {
this.recordMoneySource(moneyGain, "work");
}
this.workHackExpGained += hackExpGain;
this.workStrExpGained += strExpGain;
this.workDefExpGained += defExpGain;
this.workDexExpGained += dexExpGain;
this.workAgiExpGained += agiExpGain;
this.workChaExpGained += chaExpGain;
this.workRepGained += focusBonus * this.workRepGainRate * numCycles;
this.workMoneyGained += focusBonus * this.workMoneyGainRate * numCycles;
this.workMoneyGained -= focusBonus * this.workMoneyLossRate * numCycles;
}
/* Working for Company */
function startWork(companyName) {
this.resetWorkStatus(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCompany, companyName);
this.isWorking = true;
this.focus = true;
this.companyName = companyName;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["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_12__["CONSTANTS"].MillisecondsPer8Hours; //Remove all old event listeners from Cancel button
var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Cancel Work";
newCancelButton.addEventListener("click", () => {
this.finishWork(true);
return false;
});
const focusButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-something-else-button");
focusButton.style.visibility = "visible";
focusButton.innerHTML = "Do something else simultaneously";
focusButton.addEventListener("click", () => {
this.stopFocusing();
return false;
}); //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function cancelationPenalty() {
const specialIp = _Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][this.companyName];
if (specialIp) {
const server = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][specialIp];
if (server && server.backdoorInstalled) return 0.75;
}
return 0.5;
}
function work(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_16__["Engine"]._idleSpeed * numCycles >= _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer8Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_16__["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_12__["CONSTANTS"].MillisecondsPer8Hours) {
return this.finishWork(false);
}
const comp = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
let companyRep = "0";
if (comp == null || !(comp instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_6__["Company"])) {
console.error(`Could not find Company: ${this.companyName}`);
} else {
companyRep = comp.playerReputation;
}
Object(_StockMarket_PlayerInfluencing__WEBPACK_IMPORTED_MODULE_38__["influenceStockThroughCompanyWork"])(comp, this.workRepGainRate, numCycles);
const position = this.jobs[this.companyName];
const penalty = this.cancelationPenalty();
const penaltyString = penalty === 0.5 ? 'half' : 'three-quarters';
var elem = document.getElementById("work-in-progress-text");
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.render(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You are currently working as a ", position, " at ", this.companyName, " (Current Company Reputation: ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(companyRep), ")", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have been working for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have earned: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), " (", Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__["MoneyRate"])(this.workMoneyGainRate * CYCLES_PER_SEC), ") ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " (", Object(_ui_React_ReputationRate__WEBPACK_IMPORTED_MODULE_49__["ReputationRate"])(this.workRepGainRate * CYCLES_PER_SEC), ") reputation for this company ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGainRate * CYCLES_PER_SEC)} / sec`, ") hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGainRate * CYCLES_PER_SEC)} / sec`, ") strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGainRate * CYCLES_PER_SEC)} / sec`, ") defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGainRate * CYCLES_PER_SEC)} / sec`, ") dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGainRate * CYCLES_PER_SEC)} / sec`, ") agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGainRate * CYCLES_PER_SEC)} / sec`, ") charisma exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You will automatically finish after working for 8 hours. You can cancel earlier if you wish, but you will only gain ", penaltyString, " of the reputation you've earned so far."), elem);
}
function finishWork(cancelled, sing = false) {
//Since the work was cancelled early, player only gains half of what they've earned so far
if (cancelled) {
this.workRepGained *= this.cancelationPenalty();
}
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
company.playerReputation += this.workRepGained;
this.updateSkillLevels();
let content = react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You earned a total of: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " reputation for the company ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " charisma exp", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null));
if (cancelled) {
content = react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You worked a short shift of ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), " ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "Since you cancelled your work early, you only gained half of the reputation you earned. ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), content);
} else {
content = react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You worked a full shift of 8 hours! ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), content);
}
if (!sing) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(content);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadLocationContent(false);
if (sing) {
var res = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + "earned $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatMoney(this.workMoneyGained) + ", " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatReputation(this.workRepGained) + " reputation, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hacking exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " strength exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " defense exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dexterity exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agility exp, and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " charisma exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
function startWorkPartTime(companyName) {
this.resetWorkStatus(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCompanyPartTime, companyName);
this.isWorking = true;
this.focus = true;
this.companyName = companyName;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["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_12__["CONSTANTS"].MillisecondsPer8Hours;
var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Stop Working";
newCancelButton.addEventListener("click", () => {
this.finishWorkPartTime();
return false;
}); //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function workPartTime(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_16__["Engine"]._idleSpeed * numCycles >= _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer8Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_16__["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_12__["CONSTANTS"].MillisecondsPer8Hours) {
return this.finishWorkPartTime();
}
var comp = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName],
companyRep = "0";
if (comp == null || !(comp instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_6__["Company"])) {
console.error(`Could not find Company: ${this.companyName}`);
} else {
companyRep = comp.playerReputation;
}
const position = this.jobs[this.companyName];
const elem = document.getElementById("work-in-progress-text");
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.render(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You are currently working as a ", position, " at ", this.companyName, " (Current Company Reputation: ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(companyRep), ")", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have been working for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have earned: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), " (", Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__["MoneyRate"])(this.workMoneyGainRate * CYCLES_PER_SEC), ") ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " (", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(`${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workRepGainRate * CYCLES_PER_SEC)} / sec`), ") reputation for this company ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGainRate * CYCLES_PER_SEC)} / sec`, ") hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGainRate * CYCLES_PER_SEC)} / sec`, ") strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGainRate * CYCLES_PER_SEC)} / sec`, ") defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGainRate * CYCLES_PER_SEC)} / sec`, ") dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGainRate * CYCLES_PER_SEC)} / sec`, ") agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " (", `${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGainRate * CYCLES_PER_SEC)} / sec`, ") charisma exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You will automatically finish after working for 8 hours. You can cancel earlier if you wish, and there will be no penalty because this is a part-time job."), elem);
}
function finishWorkPartTime(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
company.playerReputation += this.workRepGained;
this.updateSkillLevels();
const content = react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You worked for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You earned a total of: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " reputation for the company ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " charisma exp", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null));
if (!sing) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(content);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadLocationContent(false);
if (sing) {
var res = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + "earned a total of " + "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatMoney(this.workMoneyGained) + ", " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatReputation(this.workRepGained) + " reputation, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hacking exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " strength exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " defense exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dexterity exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agility exp, and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
function startFocusing() {
const mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
this.focus = true;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function stopFocusing() {
const mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.focus = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadTerminalContent();
}
/* Working for Faction */
function startFactionWork(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 *= _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkRepGain;
this.isWorking = true;
this.focus = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeFaction;
this.currentWorkFactionName = faction.name;
this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer20Hours;
const cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Stop Faction Work";
cancelButton.addEventListener("click", () => {
this.finishFactionWork(true);
return false;
});
const focusButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-something-else-button");
focusButton.style.visibility = "visible";
focusButton.innerHTML = "Do something else simultaneously";
focusButton.addEventListener("click", () => {
this.stopFocusing();
return false;
}); //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function startFactionHackWork(faction) {
this.resetWorkStatus(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeFaction, faction.name, _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkHacking);
this.workHackExpGainRate = .15 * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult * this.getIntelligenceBonus(0.5);
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkHacking;
this.currentWorkFactionDescription = "carrying out hacking contracts";
this.startFactionWork(faction);
}
function startFactionFieldWork(faction) {
this.resetWorkStatus(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeFaction, faction.name, _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkField);
this.workHackExpGainRate = .1 * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = .1 * this.strength_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = .1 * this.defense_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = .1 * this.dexterity_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = .1 * this.agility_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = .1 * this.charisma_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = Object(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__["getFactionFieldWorkRepGain"])(this, faction);
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkField;
this.currentWorkFactionDescription = "carrying out field missions";
this.startFactionWork(faction);
}
function startFactionSecurityWork(faction) {
this.resetWorkStatus(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeFaction, faction.name, _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkSecurity);
this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = 0.15 * this.strength_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = 0.15 * this.defense_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = Object(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__["getFactionSecurityWorkRepGain"])(this, faction);
this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkSecurity;
this.currentWorkFactionDescription = "performing security detail";
this.startFactionWork(faction);
}
function workForFaction(numCycles) {
const faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"][this.currentWorkFactionName]; //Constantly update the rep gain rate
switch (this.factionWorkType) {
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkHacking:
this.workRepGainRate = Object(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__["getHackingWorkRepGain"])(this, faction);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkField:
this.workRepGainRate = Object(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__["getFactionFieldWorkRepGain"])(this, faction);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].FactionWorkSecurity:
this.workRepGainRate = Object(_formulas_reputation__WEBPACK_IMPORTED_MODULE_29__["getFactionSecurityWorkRepGain"])(this, faction);
break;
default:
break;
} //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_16__["Engine"]._idleSpeed * numCycles >= _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer20Hours) {
overMax = true;
numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].MillisecondsPer20Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed);
}
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_16__["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_12__["CONSTANTS"].MillisecondsPer20Hours) {
return this.finishFactionWork(false);
}
const elem = document.getElementById("work-in-progress-text");
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.render(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You are currently ", this.currentWorkFactionDescription, " for your faction ", faction.name, react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "(Current Faction Reputation: ", Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(faction.playerReputation), "). ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have been doing this for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have earned: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), " (", Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__["MoneyRate"])(this.workMoneyGainRate * CYCLES_PER_SEC), ") ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " (", Object(_ui_React_ReputationRate__WEBPACK_IMPORTED_MODULE_49__["ReputationRate"])(this.workRepGainRate * CYCLES_PER_SEC), ") reputation for this faction ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGainRate * CYCLES_PER_SEC), " / sec) hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGainRate * CYCLES_PER_SEC), " / sec) strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGainRate * CYCLES_PER_SEC), " / sec) defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGainRate * CYCLES_PER_SEC), " / sec) dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGainRate * CYCLES_PER_SEC), " / sec) agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGainRate * CYCLES_PER_SEC), " / sec) charisma exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You will automatically finish after working for 20 hours. You can cancel earlier if you wish.", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "There is no penalty for cancelling earlier."), elem);
}
function finishFactionWork(cancelled, sing = false) {
var faction = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"][this.currentWorkFactionName];
faction.playerReputation += this.workRepGained;
this.updateSkillLevels();
if (!sing) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You worked for your faction ", faction.name, " for a total of ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), " ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You earned a total of: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Reputation__WEBPACK_IMPORTED_MODULE_46__["Reputation"])(this.workRepGained), " reputation for the faction ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " charisma exp", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null)));
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadFactionContent();
Object(_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_19__["displayFactionContent"])(faction.name);
if (sing) {
var res = "You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ". " + "You earned " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatReputation(this.workRepGained) + " rep, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hacking exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " str exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " def exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dex exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agi exp, and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " cha exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
} //Money gained per game cycle
function getWorkMoneyGain() {
// If player has SF-11, calculate salary multiplier from favor
let bn11Mult = 1;
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__["SourceFileFlags"][11] > 0) {
bn11Mult = 1 + company.favor / 100;
} // Get base salary
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (companyPosition == null) {
console.error(`Could not find CompanyPosition object for ${companyPositionName}. Work salary will be 0`);
return 0;
}
return companyPosition.baseSalary * company.salaryMultiplier * this.work_money_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkMoney * bn11Mult;
} //Hack exp gained per game cycle
function getWorkHackExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work hack exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.hackingExpGain * company.expMultiplier * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Str exp gained per game cycle
function getWorkStrExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work str exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.strengthExpGain * company.expMultiplier * this.strength_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Def exp gained per game cycle
function getWorkDefExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work def exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.defenseExpGain * company.expMultiplier * this.defense_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Dex exp gained per game cycle
function getWorkDexExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work dex exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.dexterityExpGain * company.expMultiplier * this.dexterity_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Agi exp gained per game cycle
function getWorkAgiExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work agi exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.agilityExpGain * company.expMultiplier * this.agility_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Charisma exp gained per game cycle
function getWorkChaExpGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `Work cha exp gain will be 0`].join(" "));
return 0;
}
return companyPosition.charismaExpGain * company.expMultiplier * this.charisma_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CompanyWorkExpGain;
} //Reputation gained per game cycle
function getWorkRepGain() {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
const companyPositionName = this.jobs[this.companyName];
const companyPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][companyPositionName];
if (company == null || companyPosition == null) {
console.error([`Could not find Company object for ${this.companyName}`, `or CompanyPosition object for ${companyPositionName}.`, `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_12__["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;
} // export function getFactionSecurityWorkRepGain() {
// var t = 0.9 * (this.hacking_skill / CONSTANTS.MaxSkillLevel +
// this.strength / CONSTANTS.MaxSkillLevel +
// this.defense / CONSTANTS.MaxSkillLevel +
// this.dexterity / CONSTANTS.MaxSkillLevel +
// this.agility / CONSTANTS.MaxSkillLevel) / 4.5;
// return t * this.faction_rep_mult;
// }
// export function getFactionFieldWorkRepGain() {
// var t = 0.9 * (this.hacking_skill / CONSTANTS.MaxSkillLevel +
// this.strength / CONSTANTS.MaxSkillLevel +
// this.defense / CONSTANTS.MaxSkillLevel +
// this.dexterity / CONSTANTS.MaxSkillLevel +
// this.agility / CONSTANTS.MaxSkillLevel +
// this.charisma / CONSTANTS.MaxSkillLevel +
// this.intelligence / CONSTANTS.MaxSkillLevel) / 5.5;
// return t * this.faction_rep_mult;
// }
/* Creating a Program */
function startCreateProgramWork(programName, time, reqLevel) {
this.resetWorkStatus();
this.isWorking = true;
this.focus = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["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_44__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Cancel work on creating program";
cancelButton.addEventListener("click", () => {
this.finishCreateProgramWork(true);
return false;
});
const focusButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-something-else-button");
focusButton.style.visibility = "hidden"; //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function createProgramWork(numCycles) {
//Higher hacking skill will allow you to create programs faster
var reqLvl = this.createProgramReqLvl;
var skillMult = this.hacking_skill / reqLvl * this.getIntelligenceBonus(3); //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_16__["Engine"]._idleSpeed * numCycles;
this.timeWorkedCreateProgram += _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed * numCycles * skillMult;
var programName = this.createProgramName;
if (this.timeWorkedCreateProgram >= this.timeNeededToCompleteWork) {
this.finishCreateProgramWork(false);
}
const elem = document.getElementById("work-in-progress-text");
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.render(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You are currently working on coding ", programName, ".", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have been working for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "The program is ", (this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 100).toFixed(2), "% complete. ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "If you cancel, your work will be saved and you can come back to complete the program later."), elem);
}
function finishCreateProgramWork(cancelled) {
var programName = this.createProgramName;
if (cancelled === false) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("You've finished creating " + programName + "! " + "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_12__["CONSTANTS"].IntelligenceProgramBaseExpGain);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadTerminalContent();
this.resetWorkStatus();
}
/* Studying/Taking Classes */
function startClass(costMult, expMult, className) {
this.resetWorkStatus();
this.isWorking = true;
this.focus = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeStudyClass;
this.className = className;
const gameCPS = 1000 / _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed; //Find cost and exp gain per game cycle
var cost = 0;
var hackExp = 0,
strExp = 0,
defExp = 0,
dexExp = 0,
agiExp = 0,
chaExp = 0;
const hashManager = this.hashManager;
switch (className) {
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassStudyComputerScience:
hackExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassStudyComputerScienceBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassDataStructures:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassDataStructuresBaseCost * costMult / gameCPS;
hackExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassDataStructuresBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassNetworks:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassNetworksBaseCost * costMult / gameCPS;
hackExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassNetworksBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassAlgorithms:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassAlgorithmsBaseCost * costMult / gameCPS;
hackExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassAlgorithmsBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassManagement:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassManagementBaseCost * costMult / gameCPS;
chaExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassManagementBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassLeadership:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassLeadershipBaseCost * costMult / gameCPS;
chaExp = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassLeadershipBaseExp * expMult / gameCPS * hashManager.getStudyMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymStrength:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
strExp = expMult / gameCPS * hashManager.getTrainingMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymDefense:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
defExp = expMult / gameCPS * hashManager.getTrainingMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymDexterity:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
dexExp = expMult / gameCPS * hashManager.getTrainingMult();
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymAgility:
cost = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
agiExp = expMult / gameCPS * hashManager.getTrainingMult();
break;
default:
throw new Error("ERR: Invalid/unrecognized class name");
return;
}
this.workMoneyLossRate = cost;
this.workHackExpGainRate = hackExp * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
this.workStrExpGainRate = strExp * this.strength_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
this.workDefExpGainRate = defExp * this.defense_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
this.workDexExpGainRate = dexExp * this.dexterity_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
this.workAgiExpGainRate = agiExp * this.agility_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
this.workChaExpGainRate = chaExp * this.charisma_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].ClassGymExpGain;
var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-cancel-button");
if (className == _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymStrength || className == _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymDefense || className == _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymDexterity || className == _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].ClassGymAgility) {
cancelButton.innerHTML = "Stop training at gym";
} else {
cancelButton.innerHTML = "Stop taking course";
}
cancelButton.addEventListener("click", () => {
this.finishClass();
return false;
});
const focusButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-something-else-button");
focusButton.style.visibility = "hidden"; //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function takeClass(numCycles) {
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_16__["Engine"]._idleSpeed * numCycles;
var className = this.className;
this.processWorkEarnings(numCycles);
const elem = document.getElementById("work-in-progress-text");
react_dom__WEBPACK_IMPORTED_MODULE_51___default.a.render(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You have been ", className, " for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "This has cost you: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(-this.workMoneyGained), " (", Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_48__["MoneyRate"])(this.workMoneyLossRate * CYCLES_PER_SEC), ") ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You have gained: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGainRate * CYCLES_PER_SEC), " / sec) hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGainRate * CYCLES_PER_SEC), " / sec) strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGainRate * CYCLES_PER_SEC), " / sec) defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGainRate * CYCLES_PER_SEC), " / sec) dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGainRate * CYCLES_PER_SEC), " / sec) agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " (", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGainRate * CYCLES_PER_SEC), " / sec) charisma exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You may cancel at any time"), elem);
} //The 'sing' argument defines whether or not this function was called
//through a Singularity Netscript function
function finishClass(sing = false) {
this.gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].IntelligenceClassBaseExpGain * Math.round(this.timeWorked / 1000));
if (this.workMoneyGained > 0) {
throw new Error("ERR: Somehow gained money while taking class");
}
this.updateSkillLevels();
if (!sing) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "After ", this.className, " for ", Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked), ", ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "you spent a total of ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained * -1), ". ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You earned a total of: ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility exp ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " charisma exp", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null)));
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadLocationContent(false);
if (sing) {
var res = "After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ", " + "you spent a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatMoney(this.workMoneyGained * -1) + ". " + "You earned a total of: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hacking exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " strength exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " defense exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dexterity exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agility exp, and " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
} //The EXP and $ gains are hardcoded. Time is in ms
function startCrime(crimeType, hackExp, strExp, defExp, dexExp, agiExp, chaExp, money, time, singParams = null) {
this.crimeType = crimeType;
this.resetWorkStatus();
this.isWorking = true;
this.focus = true;
this.workType = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCrime;
if (singParams && singParams.workerscript) {
this.committingCrimeThruSingFn = true;
this.singFnCrimeWorkerScript = singParams.workerscript;
}
this.workHackExpGained = hackExp * this.hacking_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workStrExpGained = strExp * this.strength_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workDefExpGained = defExp * this.defense_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workDexExpGained = dexExp * this.dexterity_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workAgiExpGained = agiExp * this.agility_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workChaExpGained = chaExp * this.charisma_exp_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeExpGain;
this.workMoneyGained = money * this.crime_money_mult * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CrimeMoney;
this.timeNeededToCompleteWork = time; //Remove all old event listeners from Cancel button
const newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Cancel crime";
newCancelButton.addEventListener("click", () => {
this.finishCrime(true);
return false;
});
const focusButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_44__["clearEventListeners"])("work-in-progress-something-else-button");
focusButton.style.visibility = "hidden"; //Display Work In Progress Screen
_engine__WEBPACK_IMPORTED_MODULE_16__["Engine"].loadWorkInProgressContent();
}
function commitCrime(numCycles) {
this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_16__["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 + ". " + "Time remaining: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_45__["convertTimeMsToTimeElapsedString"])(this.timeNeededToCompleteWork - this.timeWorked) + " " + progressBar.replace(/ /g, " ");
}
function finishCrime(cancelled) {
//Determine crime success/failure
if (!cancelled) {
if (Object(_Crime_CrimeHelpers__WEBPACK_IMPORTED_MODULE_14__["determineCrimeSuccess"])(this, this.crimeType)) {
//Handle Karma and crime statistics
let crime = null;
for (const i in _Crime_Crimes__WEBPACK_IMPORTED_MODULE_15__["Crimes"]) {
if (_Crime_Crimes__WEBPACK_IMPORTED_MODULE_15__["Crimes"][i].type == this.crimeType) {
crime = _Crime_Crimes__WEBPACK_IMPORTED_MODULE_15__["Crimes"][i];
break;
}
}
if (crime == null) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(`ERR: Unrecognized crime type (${this.crimeType}). This is probably a bug please contact the developer`);
}
this.gainMoney(this.workMoneyGained);
this.recordMoneySource(this.workMoneyGained, "crime");
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_41__["numeralWrapper"].formatMoney(this.workMoneyGained) + ", " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hack exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " str exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " def exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dex exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agi exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " cha exp.");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "Crime successful!", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You gained:", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(this.workMoneyGained), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking experience ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " 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_41__["numeralWrapper"].formatExp(this.workHackExpGained) + " hack exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained) + " str exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained) + " def exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained) + " dex exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained) + " agi exp, " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained) + " cha exp.");
}
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "Crime failed!", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), "You gained:", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workHackExpGained), " hacking experience ", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workStrExpGained), " strength experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDefExpGained), " defense experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workDexExpGained), " dexterity experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workAgiExpGained), " agility experience", react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement("br", null), _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatExp(this.workChaExpGained), " 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_16__["Engine"].loadLocationContent(false);
} //Cancels the player's current "work" assignment and gives the proper rewards
//Used only for Singularity functions, so no popups are created
function singularityStopWork() {
if (!this.isWorking) {
return "";
}
var res; //Earnings text for work
switch (this.workType) {
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeStudyClass:
res = this.finishClass(true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCompany:
res = this.finishWork(true, true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCompanyPartTime:
res = this.finishWorkPartTime(true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeFaction:
res = this.finishFactionWork(true, true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCreateProgram:
res = this.finishCreateProgramWork(true);
break;
case _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].WorkTypeCrime:
res = this.finishCrime(true);
break;
default:
console.error(`Unrecognized work type (${this.workType})`);
return "";
}
return res;
} // Returns true if hospitalized, false otherwise
function takeDamage(amt) {
if (typeof amt !== "number") {
console.warn(`Player.takeDamage() called without a numeric argument: ${amt}`);
return;
}
this.hp -= amt;
if (this.hp <= 0) {
this.hospitalize();
return true;
} else {
return false;
}
}
function regenerateHp(amt) {
if (typeof amt !== "number") {
console.warn(`Player.regenerateHp() called without a numeric argument: ${amt}`);
return;
}
this.hp += amt;
if (this.hp > this.max_hp) {
this.hp = this.max_hp;
}
}
function hospitalize() {
const cost = Object(_Hospital_Hospital__WEBPACK_IMPORTED_MODULE_39__["getHospitalizationCost"])(this);
if (_Settings_Settings__WEBPACK_IMPORTED_MODULE_32__["Settings"].SuppressHospitalizationPopup === false) {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])(react__WEBPACK_IMPORTED_MODULE_50___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_50___default.a.Fragment, null, "You were in critical condition! You were taken to the hospital where luckily they were able to save your life. You were charged\xA0", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_47__["Money"])(cost)));
}
this.loseMoney(cost);
this.recordMoneySource(-1 * cost, "hospitalization");
this.hp = this.max_hp;
return cost;
}
/********* 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
function applyForJob(entryPosType, sing = false) {
// Get current company and job
let currCompany = null;
if (this.companyName !== "") {
currCompany = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.companyName];
}
const currPositionName = this.jobs[this.companyName]; // Get company that's being applied to
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (!(company instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_6__["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_9__["getJobRequirementText"])(company, pos);
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position " + reqText);
return;
}
while (true) {
let newPos = Object(_Company_GetNextCompanyPosition__WEBPACK_IMPORTED_MODULE_8__["getNextCompanyPositionHelper"])(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_8__["getNextCompanyPositionHelper"])(pos);
if (nextPos == null) {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["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_9__["getJobRequirementText"])(company, nextPos);
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unfortunately, you do not qualify for a promotion " + reqText);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available");
}
return; //Same job, do nothing
}
}
this.jobs[company.name] = pos.name;
this.companyName = this.location;
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {
return true;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.name + "!");
} //Returns your next position at a company given the field (software, business, etc.)
function getNextCompanyPosition(company, entryPosType) {
var currCompany = null;
if (this.companyName !== "") {
currCompany = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["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 currentPositionName = this.jobs[this.companyName];
const currentPosition = _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][currentPositionName];
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_8__["getNextCompanyPositionHelper"])(currentPosition);
}
return entryPosType;
}
function quitJob(company) {
this.isWorking = false;
this.companyName = "";
delete this.jobs[company];
}
function applyForSoftwareJob(sing = false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["SoftwareCompanyPositions"][0]], sing);
}
function applyForSoftwareConsultantJob(sing = false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["SoftwareConsultantCompanyPositions"][0]], sing);
}
function applyForItJob(sing = false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["ITCompanyPositions"][0]], sing);
}
function applyForSecurityEngineerJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["SecurityEngineerCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["SecurityEngineerCompanyPositions"][0]], sing);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForNetworkEngineerJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["NetworkEngineerCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["NetworkEngineerCompanyPositions"][0]], sing);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForBusinessJob(sing = false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["BusinessCompanyPositions"][0]], sing);
}
function applyForBusinessConsultantJob(sing = false) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["BusinessConsultantCompanyPositions"][0]], sing);
}
function applyForSecurityJob(sing = false) {
// TODO Police Jobs
// Indexing starts at 2 because 0 is for police officer
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["SecurityCompanyPositions"][2]], sing);
}
function applyForAgentJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["AgentCompanyPositions"][0]])) {
return this.applyForJob(_Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["AgentCompanyPositions"][0]], sing);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForEmployeeJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["MiscCompanyPositions"][1]])) {
this.companyName = company.name;
this.jobs[company.name] = _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["MiscCompanyPositions"][1];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {
return true;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Congratulations, you are now employed at " + this.companyName);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForPartTimeEmployeeJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["PartTimeCompanyPositions"][1]])) {
this.jobs[company.name] = _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["PartTimeCompanyPositions"][1];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {
return true;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Congratulations, you are now employed part-time at " + this.companyName);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForWaiterJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["MiscCompanyPositions"][0]])) {
this.companyName = company.name;
this.jobs[company.name] = _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["MiscCompanyPositions"][0];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {
return true;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Congratulations, you are now employed as a waiter at " + this.companyName);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
function applyForPartTimeWaiterJob(sing = false) {
var company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_CompanyPositions__WEBPACK_IMPORTED_MODULE_10__["CompanyPositions"][_Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["PartTimeCompanyPositions"][0]])) {
this.companyName = company.name;
this.jobs[company.name] = _Company_data_companypositionnames__WEBPACK_IMPORTED_MODULE_11__["PartTimeCompanyPositions"][0];
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
if (sing) {
return true;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Congratulations, you are now employed as a part-time waiter at " + this.companyName);
} else {
if (sing) {
return false;
}
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_43__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
} //Checks if the Player is qualified for a certain position
function isQualified(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 ***********/
function reapplyAllAugmentations(resetMultipliers = true) {
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 = _Augmentation_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName];
if (aug == null) {
console.warn(`Invalid augmentation name in Player.reapplyAllAugmentations(). Aug ${augName} will be skipped`);
continue;
}
aug.owned = true;
if (aug.name == _Augmentation_data_AugmentationNames__WEBPACK_IMPORTED_MODULE_3__["AugmentationNames"].NeuroFluxGovernor) {
for (let j = 0; j < aug.level; ++j) {
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* applyAugmentation */ "a"])(this.augmentations[i], true);
}
continue;
}
Object(_Augmentation_AugmentationHelpers__WEBPACK_IMPORTED_MODULE_1__[/* applyAugmentation */ "a"])(this.augmentations[i], true);
}
}
function reapplyAllSourceFiles() {
//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_SourceFiles__WEBPACK_IMPORTED_MODULE_36__["SourceFiles"][srcFileKey];
if (sourceFileObject == null) {
console.error(`Invalid source file number: ${this.sourceFiles[i].n}`);
continue;
}
Object(_SourceFile_applySourceFile__WEBPACK_IMPORTED_MODULE_34__["applySourceFile"])(this.sourceFiles[i]);
}
Object(_Exploits_applyExploits__WEBPACK_IMPORTED_MODULE_35__["applyExploit"])();
}
/*************** 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
function checkForFactionInvitations() {
let invitedFactions = []; //Array which will hold all Factions the player should be invited to
var numAugmentations = this.augmentations.length;
const allCompanies = Object.keys(this.jobs);
const allPositions = Object.values(this.jobs); // Given a company name, safely returns the reputation (returns 0 if invalid company is specified)
function getCompanyRep(companyName) {
const company = _Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][companyName];
if (company == null) {
return 0;
} else {
return company.playerReputation;
}
} // Helper function that returns a boolean indicating whether the Player meets
// the requirements for the specified company. There are two requirements:
// 1. High enough reputation
// 2. Player is employed at the company
function checkMegacorpRequirements(companyName, repNeeded = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].CorpFactionRepRequirement) {
return allCompanies.includes(companyName) && getCompanyRep(companyName) > repNeeded;
} //Illuminati
var illuminatiFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["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_18__["Factions"]["Daedalus"];
if (!daedalusFac.isBanned && !daedalusFac.isMember && !daedalusFac.alreadyInvited && numAugmentations >= Math.round(30 * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].DaedalusAugsRequirement) && 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_18__["Factions"]["The Covenant"];
if (!covenantFac.isBanned && !covenantFac.isMember && !covenantFac.alreadyInvited && numAugmentations >= 20 && 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_18__["Factions"]["ECorp"];
if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].AevumECorp)) {
invitedFactions.push(ecorpFac);
} //MegaCorp
var megacorpFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["MegaCorp"];
if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12MegaCorp)) {
invitedFactions.push(megacorpFac);
} //Bachman & Associates
var bachmanandassociatesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Bachman & Associates"];
if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember && !bachmanandassociatesFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].AevumBachmanAndAssociates)) {
invitedFactions.push(bachmanandassociatesFac);
} //Blade Industries
var bladeindustriesFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Blade Industries"];
if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12BladeIndustries)) {
invitedFactions.push(bladeindustriesFac);
} //NWO
var nwoFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["NWO"];
if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].VolhavenNWO)) {
invitedFactions.push(nwoFac);
} //Clarke Incorporated
var clarkeincorporatedFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Clarke Incorporated"];
if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].AevumClarkeIncorporated)) {
invitedFactions.push(clarkeincorporatedFac);
} //OmniTek Incorporated
var omnitekincorporatedFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["OmniTek Incorporated"];
if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].VolhavenOmniTekIncorporated)) {
invitedFactions.push(omnitekincorporatedFac);
} //Four Sigma
var foursigmaFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Four Sigma"];
if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12FourSigma)) {
invitedFactions.push(foursigmaFac);
} //KuaiGong International
var kuaigonginternationalFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["KuaiGong International"];
if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember && !kuaigonginternationalFac.alreadyInvited && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].ChongqingKuaiGongInternational)) {
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_18__["Factions"]["Fulcrum Secret Technologies"];
var fulcrumSecretServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerNames"].FulcrumSecretTechnologies]];
if (fulcrumSecretServer == null) {
console.error("Could not find Fulcrum Secret Technologies Server");
} else {
if (!fulcrumsecrettechonologiesFac.isBanned && !fulcrumsecrettechonologiesFac.isMember && !fulcrumsecrettechonologiesFac.alreadyInvited && fulcrumSecretServer.backdoorInstalled && checkMegacorpRequirements(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].AevumFulcrumTechnologies, 250e3)) {
invitedFactions.push(fulcrumsecrettechonologiesFac);
}
} //BitRunners
var bitrunnersFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["BitRunners"];
var homeComp = this.getHomeComputer();
var bitrunnersServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerNames"].BitRunnersServer]];
if (bitrunnersServer == null) {
console.error("Could not find BitRunners Server");
} else if (!bitrunnersFac.isBanned && !bitrunnersFac.isMember && bitrunnersServer.backdoorInstalled && !bitrunnersFac.alreadyInvited && homeComp.maxRam >= 128) {
invitedFactions.push(bitrunnersFac);
} //The Black Hand
var theblackhandFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["The Black Hand"];
var blackhandServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerNames"].TheBlackHandServer]];
if (blackhandServer == null) {
console.error("Could not find The Black Hand Server");
} else if (!theblackhandFac.isBanned && !theblackhandFac.isMember && blackhandServer.backdoorInstalled && !theblackhandFac.alreadyInvited && homeComp.maxRam >= 64) {
invitedFactions.push(theblackhandFac);
} //NiteSec
var nitesecFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["NiteSec"];
var nitesecServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerNames"].NiteSecServer]];
if (nitesecServer == null) {
console.error("Could not find NiteSec Server");
} else if (!nitesecFac.isBanned && !nitesecFac.isMember && nitesecServer.backdoorInstalled && !nitesecFac.alreadyInvited && homeComp.maxRam >= 32) {
invitedFactions.push(nitesecFac);
} //Chongqing
var chongqingFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Chongqing"];
if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited && this.money.gte(20000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Chongqing) {
invitedFactions.push(chongqingFac);
} //Sector-12
var sector12Fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Sector-12"];
if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited && this.money.gte(15000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Sector12) {
invitedFactions.push(sector12Fac);
} //New Tokyo
var newtokyoFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["New Tokyo"];
if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited && this.money.gte(20000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].NewTokyo) {
invitedFactions.push(newtokyoFac);
} //Aevum
var aevumFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Aevum"];
if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited && this.money.gte(40000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Aevum) {
invitedFactions.push(aevumFac);
} //Ishima
var ishimaFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Ishima"];
if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited && this.money.gte(30000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Ishima) {
invitedFactions.push(ishimaFac);
} //Volhaven
var volhavenFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Volhaven"];
if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited && this.money.gte(50000000) && this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Volhaven) {
invitedFactions.push(volhavenFac);
} //Speakers for the Dead
var speakersforthedeadFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["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 && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12CIA) && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12NSA)) {
invitedFactions.push(speakersforthedeadFac);
} //The Dark Army
var thedarkarmyFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["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_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Chongqing && this.numPeopleKilled >= 5 && this.karma <= -45 && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12CIA) && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12NSA)) {
invitedFactions.push(thedarkarmyFac);
} //The Syndicate
var thesyndicateFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["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_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Aevum || this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Sector12) && this.money.gte(10000000) && this.karma <= -90 && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12CIA) && !allCompanies.includes(_Locations_data_LocationNames__WEBPACK_IMPORTED_MODULE_25__["LocationName"].Sector12NSA)) {
invitedFactions.push(thesyndicateFac);
} //Silhouette
var silhouetteFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Silhouette"];
if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited && (allPositions.includes("Chief Technology Officer") || allPositions.includes("Chief Financial Officer") || allPositions.includes("Chief Executive Officer")) && this.money.gte(15000000) && this.karma <= -22) {
invitedFactions.push(silhouetteFac);
} //Tetrads
var tetradsFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["Tetrads"];
if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited && (this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Chongqing || this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].NewTokyo || this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].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_18__["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_18__["Factions"]["Netburners"];
var totalHacknetRam = 0;
var totalHacknetCores = 0;
var totalHacknetLevels = 0;
for (let i = 0; i < this.hacknetNodes.length; ++i) {
if (Object(_Hacknet_HacknetHelpers__WEBPACK_IMPORTED_MODULE_21__[/* hasHacknetServers */ "h"])()) {
const hserver = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][this.hacknetNodes[i]];
if (hserver) {
totalHacknetLevels += hserver.level;
totalHacknetRam += hserver.maxRam;
totalHacknetCores += hserver.cores;
}
} else {
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_18__["Factions"]["Tian Di Hui"];
if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited && this.money.gte(1000000) && this.hacking_skill >= 50 && (this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Chongqing || this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].NewTokyo || this.city == _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_24__["CityName"].Ishima)) {
invitedFactions.push(tiandihuiFac);
} //CyberSec
var cybersecFac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"]["CyberSec"];
var cybersecServer = _Server_AllServers__WEBPACK_IMPORTED_MODULE_30__["AllServers"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerIps"][_Server_SpecialServerIps__WEBPACK_IMPORTED_MODULE_33__["SpecialServerNames"].CyberSecServer]];
if (cybersecServer == null) {
console.error("Could not find CyberSec Server");
} else if (!cybersecFac.isBanned && !cybersecFac.isMember && cybersecServer.backdoorInstalled && !cybersecFac.alreadyInvited) {
invitedFactions.push(cybersecFac);
}
return invitedFactions;
}
/************* BitNodes **************/
function setBitNodeNumber(n) {
this.bitNodeN = n;
}
function queueAugmentation(name) {
for (const i in this.queuedAugmentations) {
if (this.queuedAugmentations[i].name == name) {
console.warn(`tried to queue ${name} twice, this may be a bug`);
return;
}
}
for (const i in this.augmentations) {
if (this.augmentations[i].name == name) {
console.warn(`tried to queue ${name} twice, this may be a bug`);
return;
}
}
this.firstAugPurchased = true;
this.queuedAugmentations.push(new _Augmentation_PlayerOwnedAugmentation__WEBPACK_IMPORTED_MODULE_2__["PlayerOwnedAugmentation"](name));
}
/************* Coding Contracts **************/
function gainCodingContractReward(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_5__["CodingContractRewardType"].FactionReputation:
if (reward.name == null || !(_Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"][reward.name] instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_17__["Faction"])) {
// If no/invalid faction was designated, just give rewards to all factions
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_5__["CodingContractRewardType"].FactionReputationAll;
return this.gainCodingContractReward(reward);
}
var repGain = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].CodingContractBaseFactionRepGain * difficulty;
_Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"][reward.name].playerReputation += repGain;
return `Gained ${repGain} faction reputation for ${reward.name}`;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_5__["CodingContractRewardType"].FactionReputationAll:
const totalGain = _Constants__WEBPACK_IMPORTED_MODULE_12__["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_5__["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_18__["Factions"][facName] instanceof _Faction_Faction__WEBPACK_IMPORTED_MODULE_17__["Faction"])) {
continue;
}
_Faction_Factions__WEBPACK_IMPORTED_MODULE_18__["Factions"][facName].playerReputation += gainPerFaction;
}
return `Gained ${gainPerFaction} reputation for each of the following factions: ${factions.toString()}`;
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_5__["CodingContractRewardType"].CompanyReputation:
if (reward.name == null || !(_Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][reward.name] instanceof _Company_Company__WEBPACK_IMPORTED_MODULE_6__["Company"])) {
//If no/invalid company was designated, just give rewards to all factions
reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_5__["CodingContractRewardType"].FactionReputationAll;
return this.gainCodingContractReward(reward);
}
var repGain = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].CodingContractBaseCompanyRepGain * difficulty;
_Company_Companies__WEBPACK_IMPORTED_MODULE_7__["Companies"][reward.name].playerReputation += repGain;
return `Gained ${repGain} company reputation for ${reward.name}`;
break;
case _CodingContracts__WEBPACK_IMPORTED_MODULE_5__["CodingContractRewardType"].Money:
default:
var moneyGain = _Constants__WEBPACK_IMPORTED_MODULE_12__["CONSTANTS"].CodingContractBaseMoneyGain * difficulty * _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_4__["BitNodeMultipliers"].CodingContractMoney;
this.gainMoney(moneyGain);
this.recordMoneySource(moneyGain, "codingcontract");
return `Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_41__["numeralWrapper"].formatMoney(moneyGain)}`;
break;
}
/* eslint-enable no-case-declarations */
}
function travel(to) {
if (_Locations_Cities__WEBPACK_IMPORTED_MODULE_22__["Cities"][to] == null) {
console.warn(`Player.travel() called with invalid city: ${to}`);
return false;
}
this.city = to;
return true;
}
function gotoLocation(to) {
if (_Locations_Locations__WEBPACK_IMPORTED_MODULE_23__["Locations"][to] == null) {
console.warn(`Player.gotoLocation() called with invalid location: ${to}`);
return false;
}
this.location = to;
return true;
}
function canAccessResleeving() {
return this.bitNodeN === 10 || _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_37__["SourceFileFlags"][10] > 0;
}
function giveExploit(exploit) {
if (!this.exploits.includes(exploit)) {
this.exploits.push(exploit);
}
}
function getIntelligenceBonus(weight) {
return Object(_formulas_intelligence__WEBPACK_IMPORTED_MODULE_28__["calculateIntelligenceBonus"])(this.intelligence, weight);
}
function getCasinoWinnings() {
return this.moneySourceA.casino;
}
/***/ }),
/* 773 */
/*!*************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectGangMethods.js ***!
\*************************************************************/
/*! exports provided: canAccessGang, getGangFaction, getGangName, hasGangWith, inGang, startGang */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canAccessGang", function() { return canAccessGang; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGangFaction", function() { return getGangFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGangName", function() { return getGangName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasGangWith", function() { return hasGangWith; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inGang", function() { return inGang; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startGang", function() { return startGang; });
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Faction/Factions */ 17);
/* harmony import */ var _Faction_Factions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Faction_Factions__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Gang_Gang__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Gang/Gang */ 301);
/* harmony import */ var _Gang_Gang__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Gang_Gang__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
/* harmony import */ var _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_3__);
// Amount of negative karma needed to manage a gang in BitNodes other than 2
const GangKarmaRequirement = -54000;
function canAccessGang() {
if (this.bitNodeN === 2) { return true; }
if (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_2__["SourceFileFlags"][2] <= 0) { return false; }
return (this.karma <= _BitNode_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_3__["BitNodeMultipliers"].GangKarmaRequirement*GangKarmaRequirement);
}
function getGangFaction() {
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_0__["Factions"][this.gang.facName];
if (fac == null) {
throw new Error(`Gang has invalid faction name: ${this.gang.facName}`);
}
return fac;
}
function getGangName() {
return this.inGang() ? this.gang.facName : "";
}
function hasGangWith(facName) {
return this.inGang() && this.gang.facName === facName;
}
function inGang() {
if (this.gang == null || this.gang == undefined) { return false; }
return (this.gang instanceof _Gang_Gang__WEBPACK_IMPORTED_MODULE_1__["Gang"]);
}
function startGang(factionName, hacking) {
this.gang = new _Gang_Gang__WEBPACK_IMPORTED_MODULE_1__["Gang"](factionName, hacking);
const fac = _Faction_Factions__WEBPACK_IMPORTED_MODULE_0__["Factions"][factionName];
if (fac == null) {
throw new Error(`Invalid faction name when creating gang: ${factionName}`);
}
fac.playerReputation = 0;
}
/***/ }),
/* 774 */
/*!********************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectCorporationMethods.js ***!
\********************************************************************/
/*! exports provided: canAccessCorporation, hasCorporation, startCorporation */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canAccessCorporation", function() { return canAccessCorporation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCorporation", function() { return hasCorporation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startCorporation", function() { return startCorporation; });
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Corporation/Corporation */ 122);
/* harmony import */ var _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__);
function canAccessCorporation() {
return this.bitNodeN === 3 || (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__["SourceFileFlags"][3] > 0);
}
function hasCorporation() {
if (this.corporation == null) { return false; }
return (this.corporation instanceof _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__["Corporation"]);
}
function startCorporation(corpName, additionalShares=0) {
this.corporation = new _Corporation_Corporation__WEBPACK_IMPORTED_MODULE_0__["Corporation"]({
name: corpName,
});
this.corporation.totalShares += additionalShares;
}
/***/ }),
/* 775 */
/*!*********************************!*\
!*** ./src/Script/ScriptUrl.ts ***!
\*********************************/
/*! no static exports found */
/*! exports used: ScriptUrl */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScriptUrl = void 0;
class ScriptUrl {
constructor(filename, url) {
this.filename = filename;
this.url = url;
}
}
exports.ScriptUrl = ScriptUrl;
/***/ }),
/* 776 */
/*!*************************************!*\
!*** ./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 */ 68);
/* harmony import */ var _Script_ScriptUrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Script/ScriptUrl */ 775);
/* harmony import */ var _Script_ScriptUrl__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Script_ScriptUrl__WEBPACK_IMPORTED_MODULE_1__);
// 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 urls = null;
let script = workerScript.getScript();
if (shouldCompile(script, scripts)) {
// 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.
script.markUpdated();
urls = _getScriptUrls(script, scripts, []);
script.url = urls[urls.length - 1].url;
script.module = new Promise(resolve => resolve(eval('import(urls[urls.length - 1].url)')));
script.dependencies = urls;
}
loadedModule = await 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 */ "b"])(workerScript, `${script.filename} cannot be run because it does not have a main function.`);
}
return loadedModule.main(ns);
} finally {
// Revoke the generated URLs
if (urls != null) {
for (const b in urls) URL.revokeObjectURL(b.url);
}
}
}
/** Returns whether we should compile the script parameter.
*
* @param {Script} script
* @param {Script[]} scripts
*/
function shouldCompile(script, scripts) {
if (script.module === "") return true;
return script.dependencies.some(dep => {
const depScript = scripts.find(s => s.filename == dep.filename);
// If the script is not present on the server, we should recompile, if only to get any necessary
// compilation errors.
if (!depScript) return true;
const depIsMoreRecent = depScript.moduleSequenceNumber > script.moduleSequenceNumber;
return depIsMoreRecent;
});
}
// 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.
/**
* @param {Script} script
* @param {Script[]} scripts
* @param {Script[]} seen
* @returns {ScriptUrl[]} All of the compiled scripts, with the final one
* in the list containing the blob corresponding to
* the script parameter.
*/
// BUG: apparently seen is never consulted. Oops.
function _getScriptUrls(script, scripts, seen) {
// Inspired by: https://stackoverflow.com/a/43834063/91401
/** @type {ScriptUrl[]} */
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://"
//
// 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].url, 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(new _Script_ScriptUrl__WEBPACK_IMPORTED_MODULE_1__["ScriptUrl"](script.filename, 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();
}
}
/***/ }),
/* 777 */
/*!****************************************!*\
!*** ./src/utils/helpers/is2DArray.ts ***!
\****************************************/
/*! no static exports found */
/*! exports used: is2DArray */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.is2DArray = void 0;
// Checks whether an array is a 2D array.
// For this, a 2D array is an array which contains only other arrays.
// If one element in the array is a number or string, it is NOT a 2D array
function is2DArray(arr) {
if (arr.constructor !== Array) {
return false;
}
return arr.every((e) => { return e.constructor === Array; });
}
exports.is2DArray = is2DArray;
/***/ }),
/* 778 */,
/* 779 */,
/* 780 */,
/* 781 */
/*!***************************************!*\
!*** ./src/Terminal/tabCompletion.ts ***!
\***************************************/
/*! no static exports found */
/*! exports used: tabCompletion */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tabCompletion = void 0;
const postToTerminal_1 = __webpack_require__(/*! ../ui/postToTerminal */ 8);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 23);
/**
* Implements tab completion for the Terminal
*
* @param command {string} Terminal command, excluding the last incomplete argument
* @param arg {string} Last argument that is being completed
* @param allPossibilities {string[]} All values that `arg` can complete to
*/
function tabCompletion(command, arg, allPossibilities) {
if (!(allPossibilities.constructor === Array)) {
return;
}
if (!StringHelperFunctions_1.containsAllStrings(allPossibilities)) {
return;
}
// Remove all options in allPossibilities that do not match the current string
// that we are attempting to autocomplete
if (arg === "") {
for (let i = allPossibilities.length - 1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(command.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
}
else {
for (let i = allPossibilities.length - 1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(arg.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
}
const textBoxElem = document.getElementById("terminal-input-text-box");
if (textBoxElem == null) {
console.warn(`Couldn't find terminal input DOM element (id=terminal-input-text-box) when trying to autocomplete`);
return;
}
const textBox = textBoxElem;
const oldValue = textBox.value;
const semiColonIndex = oldValue.lastIndexOf(";");
let val = "";
if (allPossibilities.length === 0) {
return;
}
else if (allPossibilities.length === 1) {
if (arg === "") {
//Autocomplete command
val = allPossibilities[0] + " ";
}
else {
val = command + " " + allPossibilities[0];
}
if (semiColonIndex === -1) {
// No semicolon, so replace the whole command
textBox.value = val;
}
else {
// Replace only after the last semicolon
textBox.value = textBox.value.slice(0, semiColonIndex + 1) + " " + val;
}
textBox.focus();
}
else {
const longestStartSubstr = StringHelperFunctions_1.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
*/
let allOptionsStr = "";
for (let i = 0; i < allPossibilities.length; ++i) {
allOptionsStr += allPossibilities[i];
allOptionsStr += " ";
}
if (arg === "") {
if (longestStartSubstr === command) {
postToTerminal_1.post("> " + command);
postToTerminal_1.post(allOptionsStr);
}
else {
if (semiColonIndex === -1) {
// No semicolon, so replace the whole command
textBox.value = longestStartSubstr;
}
else {
// Replace only after the last semicolon
textBox.value = `${textBox.value.slice(0, semiColonIndex + 1)} ${longestStartSubstr}`;
}
textBox.focus();
}
}
else {
if (longestStartSubstr === arg) {
// List all possible options
postToTerminal_1.post("> " + command + " " + arg);
postToTerminal_1.post(allOptionsStr);
}
else {
if (semiColonIndex == -1) {
// No semicolon, so replace the whole command
textBox.value = `${command} ${longestStartSubstr}`;
}
else {
// Replace only after the last semicolon
textBox.value = `${textBox.value.slice(0, semiColonIndex + 1)} ${command} ${longestStartSubstr}`;
}
textBox.focus();
}
}
}
}
exports.tabCompletion = tabCompletion;
/***/ }),
/* 782 */
/*!*******************************************************************!*\
!*** ./src/Terminal/determineAllPossibilitiesForTabCompletion.ts ***!
\*******************************************************************/
/*! no static exports found */
/*! exports used: determineAllPossibilitiesForTabCompletion */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.determineAllPossibilitiesForTabCompletion = void 0;
const DirectoryHelpers_1 = __webpack_require__(/*! ./DirectoryHelpers */ 86);
const DirectoryServerHelpers_1 = __webpack_require__(/*! ./DirectoryServerHelpers */ 1052);
const Alias_1 = __webpack_require__(/*! ../Alias */ 67);
const DarkWebItems_1 = __webpack_require__(/*! ../DarkWeb/DarkWebItems */ 289);
const Message_1 = __webpack_require__(/*! ../Message/Message */ 73);
const AllServers_1 = __webpack_require__(/*! ../Server/AllServers */ 20);
// An array of all Terminal commands
const commands = [
"alias",
"analyze",
"backdoor",
"cat",
"cd",
"check",
"clear",
"cls",
"connect",
"download",
"expr",
"free",
"hack",
"help",
"home",
"hostname",
"ifconfig",
"kill",
"killall",
"ls",
"lscpu",
"mem",
"mv",
"nano",
"ps",
"rm",
"run",
"scan",
"scan-analyze",
"scp",
"sudov",
"tail",
"theme",
"top",
];
function determineAllPossibilitiesForTabCompletion(p, input, index, currPath = "") {
let allPos = [];
allPos = allPos.concat(Object.keys(Alias_1.GlobalAliases));
const currServ = p.getCurrentServer();
const homeComputer = p.getHomeComputer();
let parentDirPath = "";
let evaledParentDirPath = null;
// Helper functions
function addAllCodingContracts() {
for (const cct of currServ.contracts) {
allPos.push(cct.fn);
}
}
function addAllLitFiles() {
for (const file of currServ.messages) {
if (!(file instanceof Message_1.Message)) {
allPos.push(file);
}
}
}
function addAllMessages() {
for (const file of currServ.messages) {
if (file instanceof Message_1.Message) {
allPos.push(file.filename);
}
}
}
function addAllPrograms() {
for (const program of homeComputer.programs) {
allPos.push(program);
}
}
function addAllScripts() {
for (const script of currServ.scripts) {
const res = processFilepath(script.filename);
if (res) {
allPos.push(res);
}
}
}
function addAllTextFiles() {
for (const txt of currServ.textFiles) {
const res = processFilepath(txt.fn);
if (res) {
allPos.push(res);
}
}
}
function addAllDirectories() {
// Directories are based on the currently evaluated path
const subdirs = DirectoryServerHelpers_1.getSubdirectories(currServ, evaledParentDirPath == null ? "/" : evaledParentDirPath);
for (let i = 0; i < subdirs.length; ++i) {
const assembledDirPath = (evaledParentDirPath == null ? subdirs[i] : evaledParentDirPath + subdirs[i]);
const res = processFilepath(assembledDirPath);
if (res != null) {
subdirs[i] = res;
}
}
allPos = allPos.concat(subdirs);
}
// Convert from the real absolute path back to the original path used in the input
function convertParentPath(filepath) {
if (parentDirPath == null || evaledParentDirPath == null) {
console.warn(`convertParentPath() called when paths are null`);
return filepath;
}
if (!filepath.startsWith(evaledParentDirPath)) {
console.warn(`convertParentPath() called for invalid path. (filepath=${filepath}) (evaledParentDirPath=${evaledParentDirPath})`);
return filepath;
}
return parentDirPath + filepath.slice(evaledParentDirPath.length);
}
// Given an a full, absolute filepath, converts it to the proper value
// for autocompletion purposes
function processFilepath(filepath) {
if (evaledParentDirPath) {
if (filepath.startsWith(evaledParentDirPath)) {
return convertParentPath(filepath);
}
}
else if (parentDirPath !== "") {
// If the parent directory is the root directory, but we're not searching
// it from the root directory, we have to add the original path
let t_parentDirPath = parentDirPath;
if (!t_parentDirPath.endsWith("/")) {
t_parentDirPath += "/";
}
return parentDirPath + filepath;
}
else {
return filepath;
}
return null;
}
function isCommand(cmd) {
let t_cmd = cmd;
if (!t_cmd.endsWith(" ")) {
t_cmd += " ";
}
return input.startsWith(t_cmd);
}
/**
* 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 (isCommand("./") && index == -1) {
//All programs and scripts
for (let i = 0; i < currServ.scripts.length; ++i) {
allPos.push("./" + currServ.scripts[i].filename);
}
//Programs are on home computer
for (let i = 0; i < homeComputer.programs.length; ++i) {
allPos.push("./" + homeComputer.programs[i]);
}
return allPos;
}
// Autocomplete the command
if (index === -1) {
return commands.concat(Object.keys(Alias_1.Aliases)).concat(Object.keys(Alias_1.GlobalAliases));
}
// Since we're autocompleting an argument and not a command, the argument might
// be a file/directory path. We have to account for that when autocompleting
const commandArray = input.split(" ");
if (commandArray.length === 0) {
console.warn(`Tab autocompletion logic reached invalid branch`);
return allPos;
}
const arg = commandArray[commandArray.length - 1];
parentDirPath = DirectoryHelpers_1.getAllParentDirectories(arg);
evaledParentDirPath = DirectoryHelpers_1.evaluateDirectoryPath(parentDirPath, currPath);
if (evaledParentDirPath === "/") {
evaledParentDirPath = null;
}
else if (evaledParentDirPath == null) {
return allPos; // Invalid path
}
else {
evaledParentDirPath += "/";
}
if (isCommand("buy")) {
const options = [];
for (const i in DarkWebItems_1.DarkWebItems) {
const item = DarkWebItems_1.DarkWebItems[i];
options.push(item.program);
}
return options.concat(Object.keys(Alias_1.GlobalAliases));
}
if (isCommand("scp") && index === 1) {
for (const iphostname in AllServers_1.AllServers) {
allPos.push(AllServers_1.AllServers[iphostname].ip);
allPos.push(AllServers_1.AllServers[iphostname].hostname);
}
return allPos;
}
if (isCommand("scp") && index === 0) {
addAllScripts();
addAllLitFiles();
addAllTextFiles();
addAllDirectories();
return allPos;
}
if (isCommand("connect")) {
// All network connections
for (let i = 0; i < currServ.serversOnNetwork.length; ++i) {
const serv = AllServers_1.AllServers[currServ.serversOnNetwork[i]];
if (serv == null) {
continue;
}
allPos.push(serv.ip);
allPos.push(serv.hostname);
}
return allPos;
}
if (isCommand("kill") || isCommand("tail") || isCommand("mem") || isCommand("check")) {
addAllScripts();
addAllDirectories();
return allPos;
}
if (isCommand("nano")) {
addAllScripts();
addAllTextFiles();
allPos.push(".fconf");
addAllDirectories();
return allPos;
}
if (isCommand("rm")) {
addAllScripts();
addAllPrograms();
addAllLitFiles();
addAllTextFiles();
addAllCodingContracts();
addAllDirectories();
return allPos;
}
if (isCommand("run")) {
addAllScripts();
addAllPrograms();
addAllCodingContracts();
addAllDirectories();
return allPos;
}
if (isCommand("cat")) {
addAllMessages();
addAllLitFiles();
addAllTextFiles();
addAllDirectories();
return allPos;
}
if (isCommand("download") || isCommand("mv")) {
addAllScripts();
addAllTextFiles();
addAllDirectories();
return allPos;
}
if (isCommand("cd")) {
addAllDirectories();
return allPos;
}
if (isCommand("ls") && index === 0) {
addAllDirectories();
}
return allPos;
}
exports.determineAllPossibilitiesForTabCompletion = determineAllPossibilitiesForTabCompletion;
/***/ }),
/* 783 */
/*!*******************************************!*\
!*** ./src/Hacknet/ui/PurchaseButton.jsx ***!
\*******************************************/
/*! exports provided: PurchaseButton */
/*! exports used: PurchaseButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PurchaseButton; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_3__);
/**
* React Component for the button that is used to purchase new Hacknet Nodes
*/
function PurchaseButton(props) {
if (props.multiplier == null || props.onClick == null) {
throw new Error(`PurchaseButton constructed without required props`);
}
const cost = props.cost;
let className = _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].canAfford(cost) ? "std-button" : "std-button-disabled";
let text;
let style = null;
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* hasHacknetServers */ "h"])()) {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* hasMaxNumberHacknetServers */ "i"])()) {
className = "std-button-disabled";
text = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Hacknet Server limit reached");
style = {
color: "red"
};
} else {
text = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Purchase Hacknet Server - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_3__["Money"])(cost));
}
} else {
text = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Purchase Hacknet Node - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_3__["Money"])(cost));
}
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: className,
onClick: props.onClick,
style: style
}, text);
}
/***/ }),
/* 784 */
/*!***************************************!*\
!*** ./src/Hacknet/ui/PlayerInfo.jsx ***!
\***************************************/
/*! exports provided: PlayerInfo */
/*! exports used: PlayerInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerInfo; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _ui_React_HashRate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../ui/React/HashRate */ 448);
/* harmony import */ var _ui_React_HashRate__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_ui_React_HashRate__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../ui/React/Hashes */ 126);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_6__);
/**
* React Component for displaying Player info and stats on the Hacknet Node UI.
* This includes:
* - Player's money
* - Player's production from Hacknet Nodes
*/
function PlayerInfo(props) {
const hasServers = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* hasHacknetServers */ "h"])();
let prod;
if (hasServers) {
prod = Object(_ui_React_HashRate__WEBPACK_IMPORTED_MODULE_5__["HashRate"])(props.totalProduction);
} else {
prod = Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_4__["MoneyRate"])(props.totalProduction);
}
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
id: "hacknet-nodes-money"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, "Money: "), Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_3__["Money"])(_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].money.toNumber()), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), hasServers && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, "Hashes: ", Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_6__["Hashes"])(_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hashManager.hashes), " / ", Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_6__["Hashes"])(_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hashManager.capacity)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, "Total Hacknet ", hasServers ? 'Server' : 'Node', " Production: "), prod);
}
/***/ }),
/* 785 */
/*!**********************************************!*\
!*** ./src/Hacknet/ui/MultiplierButtons.jsx ***!
\**********************************************/
/*! exports provided: MultiplierButtons */
/*! exports used: MultiplierButtons */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MultiplierButtons; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Root__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Root */ 449);
/**
* React Component for the Multiplier buttons on the Hacknet page.
* These buttons let the player control how many Nodes/Upgrades they're
* purchasing when using the UI (x1, x5, x10, MAX)
*/
function MultiplierButton(props) {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: props.className,
onClick: props.onClick
}, props.text);
}
function MultiplierButtons(props) {
if (props.purchaseMultiplier == null) {
throw new Error(`MultiplierButtons constructed without required props`);
}
const mults = ["x1", "x5", "x10", "MAX"];
const onClicks = props.onClicks;
const buttons = [];
for (let i = 0; i < mults.length; ++i) {
const mult = mults[i];
const btnProps = {
className: props.purchaseMultiplier === _Root__WEBPACK_IMPORTED_MODULE_1__[/* PurchaseMultipliers */ "b"][mult] ? "std-button-disabled" : "std-button",
key: mult,
onClick: onClicks[i],
text: mult
};
buttons.push(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(MultiplierButton, btnProps));
}
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
id: "hacknet-nodes-multipliers"
}, buttons);
}
/***/ }),
/* 786 */
/*!*********************************************!*\
!*** ./src/Hacknet/ui/HashUpgradePopup.jsx ***!
\*********************************************/
/*! exports provided: HashUpgradePopup */
/*! exports used: HashUpgradePopup */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HashUpgradePopup; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../HashManager */ 177);
/* harmony import */ var _HashManager__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_HashManager__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../HashUpgrades */ 241);
/* harmony import */ var _HashUpgrades__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_HashUpgrades__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ui_React_ServerDropdown__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../ui/React/ServerDropdown */ 534);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _ui_React_CopyableText__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
/* harmony import */ var _ui_React_CopyableText__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_ui_React_CopyableText__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../ui/React/Hashes */ 126);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_9__);
/**
* Create the pop-up for purchasing upgrades with hashes
*/
class HashUpgrade extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
constructor(props) {
super(props);
this.state = {
selectedServer: "ecorp"
};
this.changeTargetServer = this.changeTargetServer.bind(this);
this.purchase = this.purchase.bind(this, this.props.hashManager, this.props.upg);
}
changeTargetServer(e) {
this.setState({
selectedServer: e.target.value
});
}
purchase(hashManager, upg) {
const canPurchase = hashManager.hashes >= hashManager.getUpgradeCost(upg.name);
if (canPurchase) {
const res = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* purchaseHashUpgrade */ "n"])(upg.name, this.state.selectedServer);
if (res) {
this.props.rerender();
} else {
Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Failed to purchase upgrade. This may be because you do not have enough hashes, " + "or because you do not have access to the feature this upgrade affects.");
}
}
}
render() {
const hashManager = this.props.hashManager;
const upg = this.props.upg;
const cost = hashManager.getUpgradeCost(upg.name);
const level = hashManager.upgrades[upg.name];
const effect = upg.effectText(level); // Purchase button
const canPurchase = hashManager.hashes >= cost;
const btnClass = canPurchase ? "std-button" : "std-button-disabled"; // We'll reuse a Bladeburner css class
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "bladeburner-action"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_ui_React_CopyableText__WEBPACK_IMPORTED_MODULE_8__["CopyableText"], {
value: upg.name
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Cost: ", Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_9__["Hashes"])(cost), ", Bought: ", level, " times"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, upg.desc), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: btnClass,
onClick: this.purchase
}, "Purchase"), level > 0 && effect && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, effect), upg.hasTargetServer && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_ui_React_ServerDropdown__WEBPACK_IMPORTED_MODULE_6__[/* ServerDropdown */ "a"], {
serverType: _ui_React_ServerDropdown__WEBPACK_IMPORTED_MODULE_6__[/* ServerType */ "b"].Foreign,
onChange: this.changeTargetServer,
style: {
margin: "5px"
}
}));
}
}
class HashUpgradePopup extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
constructor(props) {
super(props);
this.state = {
totalHashes: _Player__WEBPACK_IMPORTED_MODULE_4__["Player"].hashManager.hashes
};
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1e3);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState({
totalHashes: _Player__WEBPACK_IMPORTED_MODULE_4__["Player"].hashManager.hashes
});
}
render() {
const rerender = this.props.rerender;
const hashManager = _Player__WEBPACK_IMPORTED_MODULE_4__["Player"].hashManager;
if (!(hashManager instanceof _HashManager__WEBPACK_IMPORTED_MODULE_2__["HashManager"])) {
throw new Error(`Player does not have a HashManager)`);
}
const upgradeElems = Object.keys(_HashUpgrades__WEBPACK_IMPORTED_MODULE_3__["HashUpgrades"]).map(upgName => {
const upg = _HashUpgrades__WEBPACK_IMPORTED_MODULE_3__["HashUpgrades"][upgName];
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(HashUpgrade, {
upg: upg,
hashManager: hashManager,
key: upg.name,
rerender: rerender
});
});
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Spend your hashes on a variety of different upgrades"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Hashes: ", _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_5__["numeralWrapper"].formatHashes(this.state.totalHashes)), upgradeElems);
}
}
/***/ }),
/* 787 */
/*!******************************************!*\
!*** ./src/Hacknet/ui/HacknetServer.jsx ***!
\******************************************/
/*! exports provided: HacknetServer */
/*! exports used: HacknetServer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HacknetServer; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../data/Constants */ 34);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_data_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../ui/React/Hashes */ 126);
/* harmony import */ var _ui_React_Hashes__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ui_React_HashRate__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../ui/React/HashRate */ 448);
/* harmony import */ var _ui_React_HashRate__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_ui_React_HashRate__WEBPACK_IMPORTED_MODULE_6__);
/**
* React Component for the Hacknet Node UI.
* This Component displays the panel for a single Hacknet Node
*/
class HacknetServer extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
render() {
const node = this.props.node;
const purchaseMult = this.props.purchaseMultiplier;
const recalculate = this.props.recalculate; // Upgrade Level Button
let upgradeLevelContent, upgradeLevelClass;
if (node.level >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxLevel) {
upgradeLevelContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX LEVEL");
upgradeLevelClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberLevelUpgrades */ "f"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxLevel);
} else {
const levelsToMax = _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxLevel - node.level;
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeLevelCost = node.calculateLevelUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_level_cost_mult);
upgradeLevelContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeLevelCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeLevelCost)) {
upgradeLevelClass = "std-button-disabled";
} else {
upgradeLevelClass = "std-button";
}
}
const upgradeLevelOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberLevelUpgrades */ "f"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxLevel);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseLevelUpgrade */ "o"])(node, numUpgrades);
recalculate();
return false;
}; // Upgrade RAM Button
let upgradeRamContent, upgradeRamClass;
if (node.maxRam >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxRam) {
upgradeRamContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX RAM");
upgradeRamClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberRamUpgrades */ "g"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxRam);
} else {
const levelsToMax = Math.round(Math.log2(_data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxRam / node.maxRam));
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeRamCost = node.calculateRamUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_ram_cost_mult);
upgradeRamContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeRamCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeRamCost)) {
upgradeRamClass = "std-button-disabled";
} else {
upgradeRamClass = "std-button";
}
}
const upgradeRamOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberRamUpgrades */ "g"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxRam);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseRamUpgrade */ "p"])(node, numUpgrades);
recalculate();
return false;
}; // Upgrade Cores Button
let upgradeCoresContent, upgradeCoresClass;
if (node.cores >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCores) {
upgradeCoresContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX CORES");
upgradeCoresClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCoreUpgrades */ "e"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCores);
} else {
const levelsToMax = _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCores - node.cores;
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeCoreCost = node.calculateCoreUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_core_cost_mult);
upgradeCoresContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeCoreCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeCoreCost)) {
upgradeCoresClass = "std-button-disabled";
} else {
upgradeCoresClass = "std-button";
}
}
const upgradeCoresOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCoreUpgrades */ "e"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCores);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseCoreUpgrade */ "l"])(node, numUpgrades);
recalculate();
return false;
}; // Upgrade Cache button
let upgradeCacheContent, upgradeCacheClass;
if (node.cache >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCache) {
upgradeCacheContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX CACHE");
upgradeCacheClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCacheUpgrades */ "d"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCache);
} else {
const levelsToMax = _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCache - node.cache;
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeCacheCost = node.calculateCacheUpgradeCost(multiplier);
upgradeCacheContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeCacheCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeCacheCost)) {
upgradeCacheClass = "std-button-disabled";
} else {
upgradeCacheClass = "std-button";
}
}
const upgradeCacheOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCacheUpgrades */ "d"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetServerConstants"].MaxCache);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseCacheUpgrade */ "k"])(node, numUpgrades);
recalculate();
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* updateHashManagerCapacity */ "r"])();
return false;
};
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", {
className: "hacknet-node"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "hacknet-node-container"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
style: {
"fontSize": "1em"
}
}, node.hostname)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Production:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text money-gold"
}, Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_5__["Hashes"])(node.totalHashesGenerated), " (", Object(_ui_React_HashRate__WEBPACK_IMPORTED_MODULE_6__["HashRate"])(node.hashRate), ")")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Hash Capacity:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text"
}, Object(_ui_React_Hashes__WEBPACK_IMPORTED_MODULE_5__["Hashes"])(node.hashCapacity))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Level:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.level), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeLevelClass,
onClick: upgradeLevelOnClick
}, upgradeLevelContent)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "RAM:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.maxRam, "GB"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeRamClass,
onClick: upgradeRamOnClick
}, upgradeRamContent)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Cores:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.cores), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeCoresClass,
onClick: upgradeCoresOnClick
}, upgradeCoresContent)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Cache Level:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.cache), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeCacheClass,
onClick: upgradeCacheOnClick
}, upgradeCacheContent))));
}
}
/***/ }),
/* 788 */
/*!****************************************!*\
!*** ./src/Hacknet/ui/HacknetNode.jsx ***!
\****************************************/
/*! exports provided: HacknetNode */
/*! exports used: HacknetNode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HacknetNode; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../data/Constants */ 34);
/* harmony import */ var _data_Constants__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_data_Constants__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Player */ 2);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../ui/React/Money */ 27);
/* harmony import */ var _ui_React_Money__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
/* harmony import */ var _ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_5__);
/**
* React Component for the Hacknet Node UI.
* This Component displays the panel for a single Hacknet Node
*/
class HacknetNode extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
render() {
const node = this.props.node;
const purchaseMult = this.props.purchaseMultiplier;
const recalculate = this.props.recalculate; // Upgrade Level Button
let upgradeLevelContent, upgradeLevelClass;
if (node.level >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxLevel) {
upgradeLevelContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX LEVEL");
upgradeLevelClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberLevelUpgrades */ "f"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxLevel);
} else {
const levelsToMax = _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxLevel - node.level;
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeLevelCost = node.calculateLevelUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_level_cost_mult);
upgradeLevelContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeLevelCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeLevelCost)) {
upgradeLevelClass = "std-button-disabled";
} else {
upgradeLevelClass = "std-button";
}
}
const upgradeLevelOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberLevelUpgrades */ "f"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxLevel);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseLevelUpgrade */ "o"])(node, numUpgrades);
recalculate();
return false;
};
let upgradeRamContent, upgradeRamClass;
if (node.ram >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxRam) {
upgradeRamContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX RAM");
upgradeRamClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberRamUpgrades */ "g"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxRam);
} else {
const levelsToMax = Math.round(Math.log2(_data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxRam / node.ram));
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeRamCost = node.calculateRamUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_ram_cost_mult);
upgradeRamContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeRamCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeRamCost)) {
upgradeRamClass = "std-button-disabled";
} else {
upgradeRamClass = "std-button";
}
}
const upgradeRamOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberRamUpgrades */ "g"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxRam);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseRamUpgrade */ "p"])(node, numUpgrades);
recalculate();
return false;
};
let upgradeCoresContent, upgradeCoresClass;
if (node.cores >= _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxCores) {
upgradeCoresContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "MAX CORES");
upgradeCoresClass = "std-button-disabled";
} else {
let multiplier = 0;
if (purchaseMult === "MAX") {
multiplier = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCoreUpgrades */ "e"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxCores);
} else {
const levelsToMax = _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxCores - node.cores;
multiplier = Math.min(levelsToMax, purchaseMult);
}
const upgradeCoreCost = node.calculateCoreUpgradeCost(multiplier, _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacknet_node_core_cost_mult);
upgradeCoresContent = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, "Upgrade x", multiplier, " - ", Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(upgradeCoreCost));
if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upgradeCoreCost)) {
upgradeCoresClass = "std-button-disabled";
} else {
upgradeCoresClass = "std-button";
}
}
const upgradeCoresOnClick = () => {
let numUpgrades = purchaseMult;
if (purchaseMult === "MAX") {
numUpgrades = Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* getMaxNumberCoreUpgrades */ "e"])(node, _data_Constants__WEBPACK_IMPORTED_MODULE_1__["HacknetNodeConstants"].MaxCores);
}
Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_2__[/* purchaseCoreUpgrade */ "l"])(node, numUpgrades);
recalculate();
return false;
};
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", {
className: "hacknet-node"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "hacknet-node-container"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
style: {
"fontSize": "1em"
}
}, node.name)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Production:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text money-gold"
}, Object(_ui_React_Money__WEBPACK_IMPORTED_MODULE_4__["Money"])(node.totalMoneyGenerated), " (", Object(_ui_React_MoneyRate__WEBPACK_IMPORTED_MODULE_5__["MoneyRate"])(node.moneyGainRatePerSecond), ")")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Level:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.level), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeLevelClass,
onClick: upgradeLevelOnClick
}, upgradeLevelContent)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "RAM:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.ram, "GB"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeRamClass,
onClick: upgradeRamOnClick
}, upgradeRamContent)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "Cores:"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
className: "text upgradable-info"
}, node.cores), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
className: upgradeCoresClass,
onClick: upgradeCoresOnClick
}, upgradeCoresContent))));
}
}
/***/ }),
/* 789 */
/*!****************************************!*\
!*** ./src/Hacknet/ui/GeneralInfo.jsx ***!
\****************************************/
/*! exports provided: GeneralInfo */
/*! exports used: GeneralInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GeneralInfo; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ 0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../HacknetHelpers */ 25);
/**
* React Component for the Hacknet Node UI
*
* Displays general information about Hacknet Nodes
*/
class GeneralInfo extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
getSecondParagraph() {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* hasHacknetServers */ "h"])()) {
return `Here, you can purchase a Hacknet Server, an upgraded version of the Hacknet Node. ` + `Hacknet Servers will perform computations and operations on the network, earning ` + `you hashes. Hashes can be spent on a variety of different upgrades.`;
} else {
return `Here, you can purchase a Hacknet Node, a specialized machine that can connect ` + `and contribute its resources to the Hacknet network. This allows you to take ` + `a small percentage of profits from hacks performed on the network. Essentially, ` + `you are renting out your Node's computing power.`;
}
}
getThirdParagraph() {
if (Object(_HacknetHelpers__WEBPACK_IMPORTED_MODULE_1__[/* hasHacknetServers */ "h"])()) {
return `Hacknet Servers can also be used as servers to run scripts. However, running scripts ` + `on a server will reduce its hash rate (hashes generated per second). A Hacknet Server's hash ` + `rate will be reduced by the percentage of RAM that is being used by that Server to run ` + `scripts.`;
} else {
return `Each Hacknet Node you purchase will passively earn you money. Each Hacknet Node ` + `can be upgraded in order to increase its computing power and thereby increase ` + `the profit you earn from it.`;
}
}
render() {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
className: "hacknet-general-info"
}, "The Hacknet is a global, decentralized network of machines. It is used by hackers all around the world to anonymously share computing power and perform distributed cyberattacks without the fear of being traced."), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
className: "hacknet-general-info"
}, this.getSecondParagraph()), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
className: "hacknet-general-info"
}, this.getThirdParagraph()));
}
}
/***/ }),
/* 790 */
/*!***************************************!*\
!*** ./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 */ 71);
/* harmony import */ var _src_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../src/engine */ 15);
/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Player */ 2);
/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 49);
/* 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 */ 18);
/* 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;
}
//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"].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"].factionInvitations.findIndex((facName)=>{return facName === faction.name});
if (i === -1) {
console.error("Could not find faction in Player.factionInvitations");
}
Object(_src_Faction_FactionHelpers__WEBPACK_IMPORTED_MODULE_0__["joinFaction"])(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();
}
/***/ }),
/* 791 */
/*!*********************************!*\
!*** ./src/Faction/ui/Root.tsx ***!
\*********************************/
/*! no static exports found */
/*! exports used: FactionRoot */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FactionRoot = void 0;
/**
* Root React Component for displaying a Faction's UI.
* This is the component for displaying a single faction's UI, not the list of all
* accessible factions
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const AugmentationsPage_1 = __webpack_require__(/*! ./AugmentationsPage */ 1080);
const DonateOption_1 = __webpack_require__(/*! ./DonateOption */ 1077);
const Info_1 = __webpack_require__(/*! ./Info */ 1076);
const Option_1 = __webpack_require__(/*! ./Option */ 1073);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
const SleeveCovenantPurchases_1 = __webpack_require__(/*! ../../PersonObjects/Sleeve/SleeveCovenantPurchases */ 684);
const SourceFileFlags_1 = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
const YesNoBox_1 = __webpack_require__(/*! ../../../utils/YesNoBox */ 61);
// Info text for all options on the UI
const gangInfo = "Create and manage a gang for this Faction. Gangs will earn you money and " +
"faction reputation";
const hackingMissionInfo = "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+)";
const hackingContractsInfo = "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.";
const fieldWorkInfo = "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.";
const securityWorkInfo = "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.";
const augmentationsInfo = "As your reputation with this faction rises, you will " +
"unlock Augmentations, which you can purchase to enhance " +
"your abilities.";
const sleevePurchasesInfo = "Purchase Duplicate Sleeves and upgrades. These are permanent!";
const GangNames = [
"Slum Snakes",
"Tetrads",
"The Syndicate",
"The Dark Army",
"Speakers for the Dead",
"NiteSec",
"The Black Hand",
];
class FactionRoot extends React.Component {
constructor(props) {
super(props);
this.state = {
rerenderFlag: false,
purchasingAugs: props.initiallyOnAugmentationsPage ? props.initiallyOnAugmentationsPage : false,
};
this.manageGang = this.manageGang.bind(this);
this.rerender = this.rerender.bind(this);
this.routeToMain = this.routeToMain.bind(this);
this.routeToPurchaseAugs = this.routeToPurchaseAugs.bind(this);
this.sleevePurchases = this.sleevePurchases.bind(this);
this.startFieldWork = this.startFieldWork.bind(this);
this.startHackingContracts = this.startHackingContracts.bind(this);
this.startHackingMission = this.startHackingMission.bind(this);
this.startSecurityWork = this.startSecurityWork.bind(this);
}
manageGang() {
// If player already has a gang, just go to the gang UI
if (this.props.p.inGang()) {
return this.props.engine.loadGangContent();
}
// Otherwise, we have to create the gang
const facName = this.props.faction.name;
let isHacking = false;
if (facName === "NiteSec" || facName === "The Black Hand") {
isHacking = true;
}
// A Yes/No popup box will allow the player to confirm gang creation
const yesBtn = YesNoBox_1.yesNoBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
return;
}
yesBtn.innerHTML = "Create Gang";
yesBtn.addEventListener("click", () => {
this.props.p.startGang(facName, isHacking);
const worldMenuHeader = document.getElementById("world-menu-header");
if (worldMenuHeader instanceof HTMLElement) {
worldMenuHeader.click();
worldMenuHeader.click();
}
this.props.engine.loadGangContent();
YesNoBox_1.yesNoBoxClose();
});
noBtn.innerHTML = "Cancel";
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
});
// Pop-up text
let gangTypeText = "";
if (isHacking) {
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.
";
}
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.
";
}
YesNoBox_1.yesNoBoxCreate(`Would you like to create a new Gang with ${facName}?
` +
"Note that this will prevent you from creating a Gang with any other Faction until " +
"this BitNode is destroyed. It also resets your reputation with this faction.
" +
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.");
}
rerender() {
this.setState((prevState) => {
return {
rerenderFlag: !prevState.rerenderFlag,
};
});
}
// Route to the main faction page
routeToMain() {
this.setState({ purchasingAugs: false });
}
// Route to the purchase augmentation UI for this faction
routeToPurchaseAugs() {
this.setState({ purchasingAugs: true });
}
sleevePurchases() {
SleeveCovenantPurchases_1.createSleevePurchasesFromCovenantPopup(this.props.p);
}
startFieldWork() {
this.props.p.startFactionFieldWork(this.props.faction);
}
startHackingContracts() {
this.props.p.startFactionHackWork(this.props.faction);
}
startHackingMission() {
const fac = this.props.faction;
this.props.p.singularityStopWork();
this.props.engine.loadMissionContent();
this.props.startHackingMissionFn(fac);
}
startSecurityWork() {
this.props.p.startFactionSecurityWork(this.props.faction);
}
render() {
return this.state.purchasingAugs ? this.renderAugmentationsPage() : this.renderMainPage();
}
renderMainPage() {
const p = this.props.p;
const faction = this.props.faction;
const factionInfo = faction.getInfo();
// We have a special flag for whether the player this faction is the player's
// gang faction because if the player has a gang, they cannot do any other action
const isPlayersGang = p.inGang() && (p.getGangName() === faction.name);
// Flags for whether special options (gang, sleeve purchases, donate, etc.)
// should be shown
const favorToDonate = Math.floor(Constants_1.CONSTANTS.BaseFavorToDonate * BitNodeMultipliers_1.BitNodeMultipliers.RepToDonateToFaction);
const canDonate = faction.favor >= favorToDonate;
const canPurchaseSleeves = (faction.name === "The Covenant" && p.bitNodeN >= 10 && SourceFileFlags_1.SourceFileFlags[10]);
let canAccessGang = (p.canAccessGang() && GangNames.includes(faction.name));
if (p.inGang()) {
if (p.getGangName() !== faction.name) {
canAccessGang = false;
}
else if (p.getGangName() === faction.name) {
canAccessGang = true;
}
}
return (React.createElement("div", null,
React.createElement("h1", null, faction.name),
React.createElement(Info_1.Info, { faction: faction, factionInfo: factionInfo }),
canAccessGang &&
React.createElement(Option_1.Option, { buttonText: "Manage Gang", infoText: gangInfo, onClick: this.manageGang }),
(!isPlayersGang && factionInfo.offerHackingMission) &&
React.createElement(Option_1.Option, { buttonText: "Hacking Mission", infoText: hackingMissionInfo, onClick: this.startHackingMission }),
(!isPlayersGang && factionInfo.offerHackingWork) &&
React.createElement(Option_1.Option, { buttonText: "Hacking Contracts", infoText: hackingContractsInfo, onClick: this.startHackingContracts }),
(!isPlayersGang && factionInfo.offerFieldWork) &&
React.createElement(Option_1.Option, { buttonText: "Field Work", infoText: fieldWorkInfo, onClick: this.startFieldWork }),
(!isPlayersGang && factionInfo.offerSecurityWork) &&
React.createElement(Option_1.Option, { buttonText: "Security Work", infoText: securityWorkInfo, onClick: this.startSecurityWork }),
!isPlayersGang && factionInfo.offersWork() &&
React.createElement(DonateOption_1.DonateOption, { faction: this.props.faction, p: this.props.p, rerender: this.rerender, favorToDonate: favorToDonate, disabled: !canDonate }),
React.createElement(Option_1.Option, { buttonText: "Purchase Augmentations", infoText: augmentationsInfo, onClick: this.routeToPurchaseAugs }),
canPurchaseSleeves &&
React.createElement(Option_1.Option, { buttonText: "Purchase & Upgrade Duplicate Sleeves", infoText: sleevePurchasesInfo, onClick: this.sleevePurchases })));
}
renderAugmentationsPage() {
return (React.createElement("div", null,
React.createElement(AugmentationsPage_1.AugmentationsPage, { faction: this.props.faction, p: this.props.p, routeToMainPage: this.routeToMain })));
}
}
exports.FactionRoot = FactionRoot;
/***/ }),
/* 792 */
/*!********************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectBladeburnerMethods.js ***!
\********************************************************************/
/*! exports provided: canAccessBladeburner, inBladeburner, startBladeburner */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canAccessBladeburner", function() { return canAccessBladeburner; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inBladeburner", function() { return inBladeburner; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startBladeburner", function() { return startBladeburner; });
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Bladeburner/Bladeburner */ 94);
/* harmony import */ var _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
/* harmony import */ var _SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__);
function canAccessBladeburner() {
if (this.bitNodeN === 8) { return false; }
return (this.bitNodeN === 6) || (this.bitNodeN === 7) || (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__["SourceFileFlags"][6] > 0) || (_SourceFile_SourceFileFlags__WEBPACK_IMPORTED_MODULE_1__["SourceFileFlags"][7] > 0);
}
function inBladeburner() {
if (this.bladeburner == null) { return false; }
return (this.bladeburner instanceof _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_0__["Bladeburner"]);
}
function startBladeburner() {
this.bladeburner = new _Bladeburner_Bladeburner__WEBPACK_IMPORTED_MODULE_0__["Bladeburner"](this);
}
/***/ }),
/* 793 */
/*!*********************************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObjectAugmentationMethods.ts ***!
\*********************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasAugmentation = void 0;
const Augmentation_1 = __webpack_require__(/*! ../../Augmentation/Augmentation */ 16);
function hasAugmentation(aug) {
const augName = (aug instanceof Augmentation_1.Augmentation) ? aug.name : aug;
for (const owned of this.augmentations) {
if (owned.name === augName) {
return true;
}
}
for (const owned of this.queuedAugmentations) {
if (owned.name === augName) {
return true;
}
}
return false;
}
exports.hasAugmentation = hasAugmentation;
/***/ }),
/* 794 */
/*!**************************************************!*\
!*** ./src/PersonObjects/Player/PlayerObject.js ***!
\**************************************************/
/*! exports provided: PlayerObject */
/*! exports used: PlayerObject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerObject; });
/* harmony import */ var _PlayerObjectAugmentationMethods__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./PlayerObjectAugmentationMethods */ 793);
/* harmony import */ var _PlayerObjectAugmentationMethods__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_PlayerObjectAugmentationMethods__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _PlayerObjectBladeburnerMethods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./PlayerObjectBladeburnerMethods */ 792);
/* harmony import */ var _PlayerObjectCorporationMethods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PlayerObjectCorporationMethods */ 774);
/* harmony import */ var _PlayerObjectGangMethods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./PlayerObjectGangMethods */ 773);
/* harmony import */ var _PlayerObjectGeneralMethods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./PlayerObjectGeneralMethods */ 772);
/* harmony import */ var _PlayerObjectServerMethods__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./PlayerObjectServerMethods */ 769);
/* harmony import */ var _PlayerObjectServerMethods__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_PlayerObjectServerMethods__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _Hacknet_HashManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Hacknet/HashManager */ 177);
/* harmony import */ var _Hacknet_HashManager__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Hacknet_HashManager__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Locations/data/CityNames */ 42);
/* harmony import */ var _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../utils/MoneySourceTracker */ 179);
/* harmony import */ var _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../utils/JSONReviver */ 29);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! decimal.js */ 65);
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_10__["default"](1000);
//IP Address of Starting (home) computer
this.homeComputer = "";
//Location information
this.city = _Locations_data_CityNames__WEBPACK_IMPORTED_MODULE_7__["CityName"].Sector12;
this.location = "";
// Jobs that the player holds
// Map of company name (key) -> name of company position (value. Just the name, not the CompanyPosition object)
// The CompanyPosition name must match a key value in CompanyPositions
this.jobs = {};
// Company at which player is CURRENTLY working (only valid when the player is actively working)
this.companyName = ""; // Name of Company. Must match a key value in Companies map
// Servers
this.currentServer = ""; //IP address of Server currently being accessed through terminal
this.purchasedServers = []; //IP Addresses of purchased servers
// Hacknet Nodes/Servers
this.hacknetNodes = []; // Note: For Hacknet Servers, this array holds the IP addresses of the servers
this.hashManager = new _Hacknet_HashManager__WEBPACK_IMPORTED_MODULE_6__["HashManager"]();
//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.focus = 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;
// Sleeves & Re-sleeving
this.sleeves = [];
this.resleeves = [];
this.sleevesFromCovenant = 0; // # of Duplicate sleeves purchased from the covenant
//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;
// Keep track of where money comes from
this.moneySourceA = new _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_8__["MoneySourceTracker"](); // Where money comes from since last-installed Augmentation
this.moneySourceB = new _utils_MoneySourceTracker__WEBPACK_IMPORTED_MODULE_8__["MoneySourceTracker"](); // Where money comes from for this entire BitNode run
// Production since last Augmentation installation
this.scriptProdSinceLastAug = 0;
this.exploits = [];
}
// Apply player methods to the prototype using Object.assign()
Object.assign(
PlayerObject.prototype,
_PlayerObjectGeneralMethods__WEBPACK_IMPORTED_MODULE_4__,
_PlayerObjectServerMethods__WEBPACK_IMPORTED_MODULE_5__,
_PlayerObjectBladeburnerMethods__WEBPACK_IMPORTED_MODULE_1__,
_PlayerObjectCorporationMethods__WEBPACK_IMPORTED_MODULE_2__,
_PlayerObjectGangMethods__WEBPACK_IMPORTED_MODULE_3__,
_PlayerObjectAugmentationMethods__WEBPACK_IMPORTED_MODULE_0__,
);
PlayerObject.prototype.toJSON = function() {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("PlayerObject", this);
}
PlayerObject.fromJSON = function(value) {
return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(PlayerObject, value.data);
}
_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.PlayerObject = PlayerObject;
/***/ }),
/* 795 */
/*!**************************************!*\
!*** ./src/Augmentation/ui/Root.tsx ***!
\**************************************/
/*! no static exports found */
/*! exports used: AugmentationsRoot */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AugmentationsRoot = void 0;
/**
* Root React component for the Augmentations UI page that display all of your
* owned and purchased Augmentations and Source-Files.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const InstalledAugmentationsAndSourceFiles_1 = __webpack_require__(/*! ./InstalledAugmentationsAndSourceFiles */ 1144);
const PlayerMultipliers_1 = __webpack_require__(/*! ./PlayerMultipliers */ 959);
const PurchasedAugmentations_1 = __webpack_require__(/*! ./PurchasedAugmentations */ 958);
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const ExportBonus_1 = __webpack_require__(/*! ../../ExportBonus */ 150);
class AugmentationsRoot extends React.Component {
constructor(props) {
super(props);
this.state = {
rerender: false,
};
this.export = this.export.bind(this);
}
export() {
this.props.exportGameFn();
this.setState({
rerender: !this.state.rerender,
});
}
render() {
function exportBonusStr() {
if (ExportBonus_1.canGetBonus())
return "(+1 favor to all factions)";
return "";
}
return (React.createElement("div", { id: "augmentations-content" },
React.createElement("h1", null, "Purchased Augmentations"),
React.createElement("p", null, "Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them."),
React.createElement("p", null, "WARNING: Installing your Augmentations resets most of your progress, including:"),
React.createElement("br", null),
React.createElement("p", null, "- Stats/Skill levels and Experience"),
React.createElement("p", null, "- Money"),
React.createElement("p", null, "- Scripts on every computer but your home computer"),
React.createElement("p", null, "- Purchased servers"),
React.createElement("p", null, "- Hacknet Nodes"),
React.createElement("p", null, "- Faction/Company reputation"),
React.createElement("p", null, "- Stocks"),
React.createElement("br", null),
React.createElement("p", null, "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)"),
React.createElement(StdButton_1.StdButton, { onClick: this.props.installAugmentationsFn, text: "Install Augmentations", tooltip: "'I never asked for this'" }),
React.createElement(StdButton_1.StdButton, { addClasses: "flashing-button", onClick: this.export, text: `Backup Save ${exportBonusStr()}`, tooltip: "It's always a good idea to backup/export your save!" }),
React.createElement(PurchasedAugmentations_1.PurchasedAugmentations, null),
React.createElement("h1", null, "Installed Augmentations"),
React.createElement("p", null, `List of all Augmentations ${Player_1.Player.sourceFiles.length > 0 ? "and Source Files " : ""} ` +
`that have been installed. You have gained the effects of these.`),
React.createElement(InstalledAugmentationsAndSourceFiles_1.InstalledAugmentationsAndSourceFiles, null),
React.createElement("br", null),
" ",
React.createElement("br", null),
React.createElement(PlayerMultipliers_1.PlayerMultipliers, null)));
}
}
exports.AugmentationsRoot = AugmentationsRoot;
/***/ }),
/* 796 */,
/* 797 */,
/* 798 */,
/* 799 */,
/* 800 */,
/* 801 */,
/* 802 */,
/* 803 */,
/* 804 */,
/* 805 */,
/* 806 */,
/* 807 */,
/* 808 */,
/* 809 */,
/* 810 */,
/* 811 */,
/* 812 */,
/* 813 */,
/* 814 */,
/* 815 */,
/* 816 */,
/* 817 */,
/* 818 */,
/* 819 */,
/* 820 */,
/* 821 */,
/* 822 */,
/* 823 */,
/* 824 */,
/* 825 */,
/* 826 */,
/* 827 */,
/* 828 */,
/* 829 */,
/* 830 */,
/* 831 */,
/* 832 */,
/* 833 */,
/* 834 */,
/* 835 */,
/* 836 */,
/* 837 */,
/* 838 */,
/* 839 */,
/* 840 */,
/* 841 */,
/* 842 */,
/* 843 */,
/* 844 */,
/* 845 */,
/* 846 */,
/* 847 */,
/* 848 */,
/* 849 */,
/* 850 */,
/* 851 */,
/* 852 */,
/* 853 */,
/* 854 */,
/* 855 */,
/* 856 */,
/* 857 */,
/* 858 */,
/* 859 */,
/* 860 */,
/* 861 */,
/* 862 */
/*!*************************************!*\
!*** ./src/Exploits/unclickable.ts ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const Exploit_1 = __webpack_require__(/*! ./Exploit */ 168);
(function () {
function clickTheUnclickable(event) {
if (!event.target || !(event.target instanceof Element))
return;
const display = window.getComputedStyle(event.target).display;
if (display === 'none' && event.isTrusted)
Player_1.Player.giveExploit(Exploit_1.Exploit.Unclickable);
}
function targetElement() {
const elem = document.getElementById('unclickable');
if (elem == null) {
console.error('Could not find the unclickable elem for the related exploit.');
return;
}
elem.addEventListener("click", clickTheUnclickable);
document.removeEventListener('DOMContentLoaded', targetElement);
}
document.addEventListener('DOMContentLoaded', targetElement);
})();
/***/ }),
/* 863 */
/*!***********************************!*\
!*** ./src/Exploits/tampering.ts ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Player_1 = __webpack_require__(/*! ../Player */ 2);
const Exploit_1 = __webpack_require__(/*! ./Exploit */ 168);
(function () {
const a = 55;
setInterval(function () {
if (a.toExponential() !== "5.5e+1") {
Player_1.Player.giveExploit(Exploit_1.Exploit.PrototypeTampering);
}
}, 15 * 60 * 1000); // 15 minutes
})();
/***/ }),
/* 864 */
/*!*********************************************************!*\
!*** ./src/ui/ActiveScripts/ServerAccordionContent.tsx ***!
\*********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerAccordionContentPaginated = exports.ServerAccordionContent = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const WorkerScriptAccordion_1 = __webpack_require__(/*! ./WorkerScriptAccordion */ 539);
const AccordionButton_1 = __webpack_require__(/*! ../React/AccordionButton */ 538);
const pageSize = 20;
function ServerAccordionContent(props) {
if (props.workerScripts.length > pageSize) {
return react_1.default.createElement(ServerAccordionContentPaginated, { workerScripts: props.workerScripts });
}
const scripts = props.workerScripts.map((ws) => {
return (react_1.default.createElement(WorkerScriptAccordion_1.WorkerScriptAccordion, { key: `${ws.name}_${ws.args}`, workerScript: ws }));
});
return (react_1.default.createElement("ul", null, scripts));
}
exports.ServerAccordionContent = ServerAccordionContent;
function ServerAccordionContentPaginated(props) {
const [page, setPage] = react_1.useState(0);
const scripts = [];
const maxPage = Math.ceil(props.workerScripts.length / pageSize);
const maxScript = Math.min((page + 1) * pageSize, props.workerScripts.length);
for (let i = page * pageSize; i < maxScript; i++) {
const ws = props.workerScripts[i];
scripts.push(react_1.default.createElement(WorkerScriptAccordion_1.WorkerScriptAccordion, { key: `${ws.name}_${ws.args}`, workerScript: ws }));
}
function capPage(page) {
if (page < 0) {
page = 0;
}
if (maxPage - 1 < page) {
page = maxPage - 1;
}
return page;
}
// in case we're on an invalid page number because scripts were killed.
const capped = capPage(page);
if (capped !== page)
setPage(capped);
function changePage(n) {
setPage(newPage => {
newPage += n;
newPage = Math.round(newPage);
return capPage(newPage);
});
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("ul", null, scripts),
react_1.default.createElement(AccordionButton_1.AccordionButton, { onClick: () => changePage(-1e99), text: "<<" }),
react_1.default.createElement(AccordionButton_1.AccordionButton, { onClick: () => changePage(-1), text: "<" }),
react_1.default.createElement("span", { className: "text" },
page + 1,
" / ",
maxPage),
react_1.default.createElement(AccordionButton_1.AccordionButton, { onClick: () => changePage(1), text: ">" }),
react_1.default.createElement(AccordionButton_1.AccordionButton, { onClick: () => changePage(1e99), text: ">>" })));
}
exports.ServerAccordionContentPaginated = ServerAccordionContentPaginated;
/***/ }),
/* 865 */
/*!**************************************************!*\
!*** ./src/ui/ActiveScripts/ServerAccordion.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerAccordion = void 0;
/**
* React Component for rendering the Accordion element for a single
* server in the 'Active Scripts' UI page
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const WorkerScriptAccordion_1 = __webpack_require__(/*! ./WorkerScriptAccordion */ 539);
const Accordion_1 = __webpack_require__(/*! ../React/Accordion */ 161);
const ServerAccordionContent_1 = __webpack_require__(/*! ./ServerAccordionContent */ 864);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
function ServerAccordion(props) {
const server = props.server;
// Accordion's header text
// 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,
};
const headerTxt = `${paddedName} ${createProgressBarText_1.createProgressBarText(barOptions)}`;
const scripts = props.workerScripts.map((ws) => {
return (React.createElement(WorkerScriptAccordion_1.WorkerScriptAccordion, { key: `${ws.name}_${ws.args}`, workerScript: ws }));
});
return (React.createElement(Accordion_1.Accordion, { headerContent: React.createElement("pre", null, headerTxt), panelContent: React.createElement(ServerAccordionContent_1.ServerAccordionContent, { workerScripts: props.workerScripts }) }));
}
exports.ServerAccordion = ServerAccordion;
/***/ }),
/* 866 */
/*!***************************************************!*\
!*** ./src/ui/ActiveScripts/ServerAccordions.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerAccordions = void 0;
/**
* React Component for rendering the Accordion elements for all servers
* on which scripts are running
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const ServerAccordion_1 = __webpack_require__(/*! ./ServerAccordion */ 865);
const WorkerScriptStartStopEventEmitter_1 = __webpack_require__(/*! ../../Netscript/WorkerScriptStartStopEventEmitter */ 147);
const ServerHelpers_1 = __webpack_require__(/*! ../../Server/ServerHelpers */ 22);
const subscriberId = "ActiveScriptsUI";
class ServerAccordions extends React.Component {
constructor(props) {
super(props);
this.serverToScriptMap = {};
this.state = {
rerenderFlag: false,
};
this.updateServerToScriptsMap();
this.rerender = this.rerender.bind(this);
}
componentDidMount() {
WorkerScriptStartStopEventEmitter_1.WorkerScriptStartStopEventEmitter.addSubscriber({
cb: this.rerender,
id: subscriberId,
});
}
componentWillUnmount() {
WorkerScriptStartStopEventEmitter_1.WorkerScriptStartStopEventEmitter.removeSubscriber(subscriberId);
}
updateServerToScriptsMap() {
const map = {};
for (const ws of this.props.workerScripts.values()) {
const server = ServerHelpers_1.getServer(ws.serverIp);
if (server == null) {
console.warn(`WorkerScript has invalid IP address: ${ws.serverIp}`);
continue;
}
if (map[server.hostname] == null) {
map[server.hostname] = {
server: server,
workerScripts: [],
};
}
map[server.hostname].workerScripts.push(ws);
}
this.serverToScriptMap = map;
}
rerender() {
this.updateServerToScriptsMap();
this.setState((prevState) => {
return { rerenderFlag: !prevState.rerenderFlag };
});
}
render() {
const elems = Object.keys(this.serverToScriptMap).map((serverName) => {
const data = this.serverToScriptMap[serverName];
return (React.createElement(ServerAccordion_1.ServerAccordion, { key: serverName, server: data.server, workerScripts: data.workerScripts }));
});
return (React.createElement("ul", { className: "active-scripts-list", id: "active-scripts-list" }, elems));
}
}
exports.ServerAccordions = ServerAccordions;
/***/ }),
/* 867 */
/*!***************************************************!*\
!*** ./src/ui/ActiveScripts/ScriptProduction.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScriptProduction = void 0;
/**
* React Component for displaying the total production and production rate
* of scripts on the 'Active Scripts' UI page
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Money_1 = __webpack_require__(/*! ../React/Money */ 27);
function ScriptProduction(props) {
const prodRateSinceLastAug = props.p.scriptProdSinceLastAug / (props.p.playtimeSinceLastAug / 1000);
let onlineProduction = 0;
for (const ws of props.workerScripts.values()) {
onlineProduction += (ws.scriptRef.onlineMoneyMade / ws.scriptRef.onlineRunningTime);
}
return (React.createElement("p", { id: "active-scripts-total-prod" },
"Total online production of Active scripts:\u00A0",
React.createElement("span", { className: "money-gold" },
React.createElement("span", { id: "active-scripts-total-production-active" }, Money_1.Money(onlineProduction)),
" / sec"),
React.createElement("br", null),
"Total online production since last Aug installation:\u00A0",
React.createElement("span", { id: "active-scripts-total-prod-aug-total", className: "money-gold" }, Money_1.Money(props.p.scriptProdSinceLastAug)),
"\u00A0(",
React.createElement("span", { className: "money-gold" },
React.createElement("span", { id: "active-scripts-total-prod-aug-avg", className: "money-gold" }, Money_1.Money(prodRateSinceLastAug)),
" / sec"),
")"));
}
exports.ScriptProduction = ScriptProduction;
/***/ }),
/* 868 */
/*!**************************************************!*\
!*** ./src/PersonObjects/Resleeving/Resleeve.ts ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Resleeve = void 0;
/**
* Implements the Resleeve class, which defines a new body
* that the player can "re-sleeve" into.
*/
const Person_1 = __webpack_require__(/*! ../Person */ 683);
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const JSONReviver_1 = __webpack_require__(/*! ../../../utils/JSONReviver */ 29);
class Resleeve extends Person_1.Person {
constructor() {
super();
}
getCost() {
// Each experience point adds this to the cost
const CostPerExp = 25e3;
// Final cost is multiplied by this constant ^ # Augs
const NumAugsExponent = 1.2;
// Get total exp in this re-sleeve
const totalExp = this.hacking_exp +
this.strength_exp +
this.defense_exp +
this.dexterity_exp +
this.agility_exp +
this.charisma_exp;
// Get total base Augmentation cost for this re-sleeve
let totalAugmentationCost = 0;
for (let i = 0; i < this.augmentations.length; ++i) {
const aug = Augmentations_1.Augmentations[this.augmentations[i].name];
if (aug == null) {
console.error(`Could not find Augmentation ${this.augmentations[i].name}`);
continue;
}
totalAugmentationCost += aug.startingCost;
}
return (totalExp * CostPerExp) + (totalAugmentationCost * Math.pow(NumAugsExponent, this.augmentations.length));
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Resleeve", this);
}
/**
* Initiatizes a Resleeve object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Resleeve, value.data);
}
}
exports.Resleeve = Resleeve;
JSONReviver_1.Reviver.constructors.Resleeve = Resleeve;
/***/ }),
/* 869 */
/*!****************************************************!*\
!*** ./src/PersonObjects/Resleeving/Resleeving.ts ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateResleeves = exports.purchaseResleeve = void 0;
/**
* Implements the Re-sleeving mechanic for BitNode-10.
* This allows the player to purchase and "use" new sleeves at VitaLife.
* These new sleeves come with different starting experience and Augmentations
* The cost of these new sleeves scales based on the exp and Augs.
*
* Note that this is different from the "Sleeve mechanic". The "Sleeve" mechanic
* provides new sleeves, essentially clones. This Re-sleeving mechanic lets
* the player purchase a new body with pre-existing Augmentations and experience
*
* As of right now, this feature is only available in BitNode 10
*/
const Resleeve_1 = __webpack_require__(/*! ./Resleeve */ 868);
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const PlayerOwnedAugmentation_1 = __webpack_require__(/*! ../../Augmentation/PlayerOwnedAugmentation */ 196);
const AugmentationNames_1 = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
const getRandomInt_1 = __webpack_require__(/*! ../../../utils/helpers/getRandomInt */ 45);
// Executes the actual re-sleeve when one is purchased
function purchaseResleeve(r, p) {
const cost = r.getCost();
if (!p.canAfford(cost)) {
return false;
}
p.loseMoney(cost);
// Set the player's exp
p.hacking_exp = r.hacking_exp;
p.strength_exp = r.strength_exp;
p.defense_exp = r.defense_exp;
p.dexterity_exp = r.dexterity_exp;
p.agility_exp = r.agility_exp;
p.charisma_exp = r.charisma_exp;
// Reset Augmentation "owned" data
for (const augKey in Augmentations_1.Augmentations) {
Augmentations_1.Augmentations[augKey].owned = false;
}
// Clear all of the player's augmentations, except the NeuroFlux Governor
// which is kept
for (let i = p.augmentations.length - 1; i >= 0; --i) {
if (p.augmentations[i].name !== AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
p.augmentations.splice(i, 1);
}
else {
// NeuroFlux Governor
Augmentations_1.Augmentations[AugmentationNames_1.AugmentationNames.NeuroFluxGovernor].owned = true;
}
}
for (let i = 0; i < r.augmentations.length; ++i) {
p.augmentations.push(new PlayerOwnedAugmentation_1.PlayerOwnedAugmentation(r.augmentations[i].name));
Augmentations_1.Augmentations[r.augmentations[i].name].owned = true;
}
// The player's purchased Augmentations should remain the same, but any purchased
// Augmentations that are given by the resleeve should be removed so there are no duplicates
for (let i = p.queuedAugmentations.length - 1; i >= 0; --i) {
const name = p.queuedAugmentations[i].name;
if (p.augmentations.filter((e) => { return e.name !== AugmentationNames_1.AugmentationNames.NeuroFluxGovernor && e.name === name; }).length >= 1) {
p.queuedAugmentations.splice(i, 1);
}
}
p.reapplyAllAugmentations(true);
p.reapplyAllSourceFiles(); //Multipliers get reset, so have to re-process source files too
return true;
}
exports.purchaseResleeve = purchaseResleeve;
// Creates all of the Re-sleeves that will be available for purchase at VitaLife
function generateResleeves() {
const NumResleeves = 40; // Total number of Resleeves to generate
const ret = [];
for (let i = 0; i < NumResleeves; ++i) {
// i will be a number indicating how "powerful" the Re-sleeve should be
const r = new Resleeve_1.Resleeve();
// Generate experience
const expMult = (5 * i) + 1;
r.hacking_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
r.strength_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
r.defense_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
r.dexterity_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
r.agility_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
r.charisma_exp = expMult * getRandomInt_1.getRandomInt(1000, 5000);
// Generate Augs
// Augmentation prequisites will be ignored for this
const baseNumAugs = Math.max(2, Math.ceil((i + 3) / 2));
const numAugs = getRandomInt_1.getRandomInt(baseNumAugs, baseNumAugs + 2);
const augKeys = Object.keys(Augmentations_1.Augmentations);
for (let a = 0; a < numAugs; ++a) {
// Get a random aug
const randIndex = getRandomInt_1.getRandomInt(0, augKeys.length - 1);
const randKey = augKeys[randIndex];
// Forbidden augmentations
if (randKey === AugmentationNames_1.AugmentationNames.TheRedPill || randKey === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
continue;
}
const randAug = Augmentations_1.Augmentations[randKey];
if (randAug === null)
throw new Error(`null augmentation: ${randKey}`);
r.augmentations.push({ name: randAug.name, level: 1 });
r.applyAugmentation(Augmentations_1.Augmentations[randKey]);
r.updateStatLevels();
// Remove Augmentation so that there are no duplicates
augKeys.splice(randIndex, 1);
}
ret.push(r);
}
return ret;
}
exports.generateResleeves = generateResleeves;
/***/ }),
/* 870 */
/*!*************************************************************!*\
!*** ./src/PersonObjects/Sleeve/ui/MoreEarningsContent.tsx ***!
\*************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoreEarningsContent = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../../../ui/React/Money */ 27);
const React = __importStar(__webpack_require__(/*! react */ 0));
const StatsTable_1 = __webpack_require__(/*! ../../../ui/React/StatsTable */ 275);
function MoreEarningsContent(sleeve) {
return (React.createElement(React.Fragment, null,
StatsTable_1.StatsTable([
['Money ', Money_1.Money(sleeve.earningsForTask.money)],
['Hacking Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.hack)],
['Strength Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.str)],
['Defense Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.def)],
['Dexterity Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.dex)],
['Agility Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.agi)],
['Charisma Exp ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForTask.cha)],
], 'Earnings for Current Task:'),
React.createElement("br", null),
StatsTable_1.StatsTable([
['Money: ', Money_1.Money(sleeve.earningsForPlayer.money)],
['Hacking Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.hack)],
['Strength Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.str)],
['Defense Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.def)],
['Dexterity Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.dex)],
['Agility Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.agi)],
['Charisma Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForPlayer.cha)],
], 'Total Earnings for Host Consciousness:'),
React.createElement("br", null),
StatsTable_1.StatsTable([
['Money: ', Money_1.Money(sleeve.earningsForSleeves.money)],
['Hacking Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.hack)],
['Strength Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.str)],
['Defense Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.def)],
['Dexterity Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.dex)],
['Agility Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.agi)],
['Charisma Exp: ', numeralFormat_1.numeralWrapper.formatExp(sleeve.earningsForSleeves.cha)],
], 'Total Earnings for Other Sleeves:'),
React.createElement("br", null)));
}
exports.MoreEarningsContent = MoreEarningsContent;
/***/ }),
/* 871 */
/*!**********************************************************!*\
!*** ./src/PersonObjects/Sleeve/ui/MoreStatsContent.tsx ***!
\**********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoreStatsContent = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../../ui/numeralFormat */ 7);
const StatsTable_1 = __webpack_require__(/*! ../../../ui/React/StatsTable */ 275);
const React = __importStar(__webpack_require__(/*! react */ 0));
function MoreStatsContent(sleeve) {
return (React.createElement(React.Fragment, null,
StatsTable_1.StatsTable([
['Hacking: ', sleeve.hacking_skill, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.hacking_exp)} exp)`],
['Strength: ', sleeve.strength, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.strength_exp)} exp)`],
['Defense: ', sleeve.defense, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.defense_exp)} exp)`],
['Dexterity: ', sleeve.dexterity, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.dexterity_exp)} exp)`],
['Agility: ', sleeve.agility, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.agility_exp)} exp)`],
['Charisma: ', sleeve.charisma, `(${numeralFormat_1.numeralWrapper.formatExp(sleeve.charisma_exp)} exp)`],
], 'Stats:'),
React.createElement("br", null),
StatsTable_1.StatsTable([
['Hacking Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.hacking_mult)],
['Hacking Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.hacking_exp_mult)],
['Strength Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.strength_mult)],
['Strength Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.strength_exp_mult)],
['Defense Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.defense_mult)],
['Defense Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.defense_exp_mult)],
['Dexterity Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.dexterity_mult)],
['Dexterity Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.dexterity_exp_mult)],
['Agility Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.agility_mult)],
['Agility Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.agility_exp_mult)],
['Charisma Level multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.charisma_mult)],
['Charisma Experience multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.charisma_exp_mult)],
['Faction Reputation Gain multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.faction_rep_mult)],
['Company Reputation Gain multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.company_rep_mult)],
['Salary multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.work_money_mult)],
['Crime Money multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.crime_money_mult)],
['Crime Success multiplier: ', numeralFormat_1.numeralWrapper.formatPercentage(sleeve.crime_success_mult)],
], 'Multipliers:')));
}
exports.MoreStatsContent = MoreStatsContent;
/***/ }),
/* 872 */
/*!******************************************************!*\
!*** ./src/PersonObjects/Sleeve/ui/StatsElement.tsx ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatsElement = void 0;
const numeralFormat_1 = __webpack_require__(/*! ../../../ui/numeralFormat */ 7);
const React = __importStar(__webpack_require__(/*! react */ 0));
function StatsElement(sleeve) {
let style = {};
style = { textAlign: "right" };
return (React.createElement(React.Fragment, null,
React.createElement("table", null,
React.createElement("tbody", null,
React.createElement("tr", null,
React.createElement("td", { className: "character-hp-cell" }, "HP: "),
React.createElement("td", { className: "character-hp-cell", style: style },
numeralFormat_1.numeralWrapper.formatHp(sleeve.hp),
" / ",
numeralFormat_1.numeralWrapper.formatHp(sleeve.max_hp))),
React.createElement("tr", null,
React.createElement("td", null, "City: "),
React.createElement("td", { style: style }, sleeve.city)),
React.createElement("tr", null,
React.createElement("td", { className: "character-hack-cell" }, "Hacking: "),
React.createElement("td", { className: "character-hack-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.hacking_skill))),
React.createElement("tr", null,
React.createElement("td", { className: "character-combat-cell" }, "Strength: "),
React.createElement("td", { className: "character-combat-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.strength))),
React.createElement("tr", null,
React.createElement("td", { className: "character-combat-cell" }, "Defense: "),
React.createElement("td", { className: "character-combat-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.defense))),
React.createElement("tr", null,
React.createElement("td", { className: "character-combat-cell" }, "Dexterity: "),
React.createElement("td", { className: "character-combat-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.dexterity))),
React.createElement("tr", null,
React.createElement("td", { className: "character-combat-cell" }, "Agility: "),
React.createElement("td", { className: "character-combat-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.agility))),
React.createElement("tr", null,
React.createElement("td", { className: "character-cha-cell" }, "Charisma: "),
React.createElement("td", { className: "character-cha-cell", style: style }, numeralFormat_1.numeralWrapper.formatSkill(sleeve.charisma))),
React.createElement("tr", null,
React.createElement("td", { className: "character-int-cell" }, "Shock: "),
React.createElement("td", { className: "character-int-cell", style: style }, numeralFormat_1.numeralWrapper.formatSleeveShock(100 - sleeve.shock))),
React.createElement("tr", null,
React.createElement("td", { className: "character-int-cell" }, "Sync: "),
React.createElement("td", { className: "character-int-cell", style: style }, numeralFormat_1.numeralWrapper.formatSleeveSynchro(sleeve.sync))),
React.createElement("tr", null,
React.createElement("td", { className: "character-int-cell" }, "Memory: "),
React.createElement("td", { className: "character-int-cell", style: style }, numeralFormat_1.numeralWrapper.formatSleeveMemory(sleeve.memory)))))));
}
exports.StatsElement = StatsElement;
/***/ }),
/* 873 */
/*!**************************************************************!*\
!*** ./src/PersonObjects/Sleeve/ui/EarningsTableElement.tsx ***!
\**************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EarningsTableElement = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
function EarningsTableElement(title, stats) {
return (React.createElement(React.Fragment, null,
React.createElement("pre", null, title),
React.createElement("table", null,
React.createElement("tbody", null, stats.map((stat, i) => React.createElement("tr", { key: i }, stat.map((s, i) => {
let style = {};
if (i !== 0) {
style = { textAlign: "right" };
}
return React.createElement("td", { style: style, key: i }, s);
})))))));
}
exports.EarningsTableElement = EarningsTableElement;
/***/ }),
/* 874 */
/*!*****************************************************!*\
!*** ./src/PersonObjects/Sleeve/data/SleeveFaq.tsx ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SleeveFaq = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
exports.SleeveFaq = (React.createElement(React.Fragment, null,
React.createElement("strong", null,
React.createElement("u", null, "How do Duplicate Sleeves work?")),
React.createElement("br", null),
"Duplicate Sleeves are essentially clones. You can use them to perform any work type action, such as working for a company/faction or committing a crime. Having sleeves perform these tasks earns you money, experience, and reputation.",
React.createElement("br", null),
React.createElement("br", null),
"Sleeves are their own individuals, which means they each have their own experience and stats.",
React.createElement("br", null),
React.createElement("br", null),
"When a sleeve earns experience, it earns experience for itself, the player's original 'consciousness', as well as all of the player's other sleeves.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "What is Synchronization (Sync)?")),
React.createElement("br", null),
"Synchronization is a measure of how aligned your consciousness is with that of your Duplicate Sleeves. It is a numerical value between 1 and 100, and it affects how much experience is earned when the sleeve is performing a task.",
React.createElement("br", null),
React.createElement("br", null),
"Let N be the sleeve's synchronization. When the sleeve earns experience by performing a task, both the sleeve and the player's original host consciousness earn N% of the amount of experience normally earned by the task. All of the player's other sleeves earn ((N/100)^2 * 100)% of the experience.",
React.createElement("br", null),
React.createElement("br", null),
"Synchronization can be increased by assigning sleeves to the 'Synchronize' task.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "What is Shock?")),
React.createElement("br", null),
"Sleeve shock is a measure of how much trauma the sleeve has due to being placed in a new body. It is a numerical value between 0 and 99, where 99 indicates full shock and 0 indicates no shock. Shock affects the amount of experience earned by the sleeve.",
React.createElement("br", null),
React.createElement("br", null),
"Sleeve shock slowly decreases over time. You can further increase the rate at which it decreases by assigning sleeves to the 'Shock Recovery' task.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "Why can't I work for this company or faction?")),
React.createElement("br", null),
"Only one of your sleeves can work for a given company/faction a time. To clarify further, if you have two sleeves they can work for two different companies, but they cannot both work for the same company.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "Why did my Sleeve stop working?")),
React.createElement("br", null),
"Sleeves are subject to the same time restrictions as you. This means that they automatically stop working at a company after 8 hours, and stop working for a faction after 20 hours.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "How do I buy Augmentations for my Sleeves?")),
React.createElement("br", null),
"Your Sleeve needs to have a Shock of 0 in order for you to buy Augmentations for it.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "Why can't I buy the X Augmentation for my sleeve?")),
React.createElement("br", null),
"Certain Augmentations, like Bladeburner-specific ones and NeuroFlux Governor, are not available for sleeves.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "Do sleeves get reset when installing Augmentations or switching BitNodes?")),
React.createElement("br", null),
"Sleeves are reset when switching BitNodes, but not when installing Augmentations.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("strong", null,
React.createElement("u", null, "What is Memory?")),
React.createElement("br", null),
"Sleeve memory dictates what a sleeve's synchronization will be when its reset by switching BitNodes. For example, if a sleeve has a memory of 25, then when you switch BitNodes its synchronization will initially be set to 25, rather than 1.",
React.createElement("br", null),
React.createElement("br", null),
"Memory can only be increased by purchasing upgrades from The Covenant. It is a persistent stat, meaning it never gets resets back to 1. The maximum possible value for a sleeve's memory is 100."));
/***/ }),
/* 875 */
/*!***********************************************************!*\
!*** ./src/PersonObjects/Sleeve/SleeveAugmentationsUI.ts ***!
\***********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSleevePurchaseAugsPopup = void 0;
const SleeveHelpers_1 = __webpack_require__(/*! ./SleeveHelpers */ 521);
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createElement */ 51);
const createPopup_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createPopup */ 129);
const createPopupCloseButton_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createPopupCloseButton */ 468);
const removeElementById_1 = __webpack_require__(/*! ../../../utils/uiHelpers/removeElementById */ 90);
const server_1 = __webpack_require__(/*! react-dom/server */ 398);
function createSleevePurchaseAugsPopup(sleeve, p) {
// Array of all owned Augmentations. Names only
const ownedAugNames = sleeve.augmentations.map((e) => { return e.name; });
// You can only purchase Augmentations that are actually available from
// your factions. I.e. you must be in a faction that has the Augmentation
// and you must also have enough rep in that faction in order to purchase it.
const availableAugs = SleeveHelpers_1.findSleevePurchasableAugs(sleeve, p);
// Create popup
const popupId = "purchase-sleeve-augs-popup";
// Close popup button
const closeBtn = createPopupCloseButton_1.createPopupCloseButton(popupId, { innerText: "Cancel" });
// General info about owned Augmentations
const ownedAugsInfo = createElement_1.createElement("p", {
display: "block",
innerHTML: "Owned Augmentations:",
});
const popupElems = [closeBtn, ownedAugsInfo];
// Show owned augmentations
// First we'll make a div with a reduced width, so the tooltips don't go off
// the edge of the popup
const ownedAugsDiv = createElement_1.createElement("div", { width: "70%" });
for (const ownedAug of ownedAugNames) {
const aug = Augmentations_1.Augmentations[ownedAug];
if (aug == null) {
console.warn(`Invalid Augmentation: ${ownedAug}`);
continue;
}
let tooltip = aug.info;
if (typeof tooltip !== 'string') {
tooltip = server_1.renderToStaticMarkup(tooltip);
}
tooltip += "
";
tooltip += server_1.renderToStaticMarkup(aug.stats);
ownedAugsDiv.appendChild(createElement_1.createElement("div", {
class: "gang-owned-upgrade",
innerText: ownedAug,
tooltip: tooltip,
}));
}
popupElems.push(ownedAugsDiv);
// General info about buying Augmentations
const info = createElement_1.createElement("p", {
innerHTML: [
`You can purchase Augmentations for your Duplicate Sleeves. These Augmentations`,
`have the same effect as they would for you. You can only purchase Augmentations`,
`that you have unlocked through Factions.
`,
`When purchasing an Augmentation for a Duplicate Sleeve, they are immediately`,
`installed. This means that the Duplicate Sleeve will immediately lose all of`,
`its stat experience.`,
].join(" "),
});
popupElems.push(info);
for (const aug of availableAugs) {
const div = createElement_1.createElement("div", {
class: "cmpy-mgmt-upgrade-div", // We'll reuse this CSS class
});
let info = aug.info;
if (typeof info !== 'string') {
info = server_1.renderToStaticMarkup(info);
}
info += "
`,
`${info}`,
].join(" "),
padding: "2px",
clickListener: () => {
if (sleeve.tryBuyAugmentation(p, aug)) {
DialogBox_1.dialogBoxCreate(`Installed ${aug.name} on Duplicate Sleeve!`, false);
removeElementById_1.removeElementById(popupId);
createSleevePurchaseAugsPopup(sleeve, p);
}
else {
DialogBox_1.dialogBoxCreate(`You cannot afford ${aug.name}`, false);
}
},
}));
popupElems.push(div);
}
createPopup_1.createPopup(popupId, popupElems);
}
exports.createSleevePurchaseAugsPopup = createSleevePurchaseAugsPopup;
/***/ }),
/* 876 */
/*!**************************************!*\
!*** ./src/Milestones/Milestones.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Milestones = void 0;
const Factions_1 = __webpack_require__(/*! ../Faction/Factions */ 17);
const ServerHelpers_1 = __webpack_require__(/*! ../Server/ServerHelpers */ 22);
function allFactionAugs(p, f) {
const factionAugs = f.augmentations.slice().filter((aug) => aug !== "NeuroFlux Governor");
for (const factionAug of factionAugs) {
if (!p.augmentations.some(aug => { return aug.name == factionAug; }))
return false;
}
return true;
}
exports.Milestones = [
{
title: "Gain root access on CSEC",
fulfilled: () => {
const server = ServerHelpers_1.GetServerByHostname("CSEC");
if (!server || !server.hasOwnProperty('hasAdminRights'))
return false;
return server.hasAdminRights;
},
},
{
title: "Install the backdoor on CSEC",
fulfilled: () => {
const server = ServerHelpers_1.GetServerByHostname("CSEC");
if (!server || !server.hasOwnProperty('backdoorInstalled'))
return false;
return server.backdoorInstalled;
},
},
{
title: "Join the faction hinted at in csec-test.msg",
fulfilled: (p) => {
return p.factions.includes("CyberSec");
},
},
{
title: "Install all the Augmentations from CyberSec",
fulfilled: (p) => {
return allFactionAugs(p, Factions_1.Factions["CyberSec"]);
},
},
{
title: "Join the faction hinted at in nitesec-test.msg",
fulfilled: (p) => {
return p.factions.includes("NiteSec");
},
},
{
title: "Install all the Augmentations from NiteSec",
fulfilled: (p) => {
return allFactionAugs(p, Factions_1.Factions["NiteSec"]);
},
},
{
title: "Join the faction hinted at in j3.msg",
fulfilled: (p) => {
return p.factions.includes("The Black Hand");
},
},
{
title: "Install all the Augmentations from The Black Hand",
fulfilled: (p) => {
return allFactionAugs(p, Factions_1.Factions["The Black Hand"]);
},
},
{
title: "Join the faction hinted at in 19dfj3l1nd.msg",
fulfilled: (p) => {
return p.factions.includes("BitRunners");
},
},
{
title: "Install all the Augmentations from BitRunners",
fulfilled: (p) => {
return allFactionAugs(p, Factions_1.Factions["BitRunners"]);
},
},
{
title: "Complete fl1ght.exe",
fulfilled: (p) => {
// technically wrong but whatever
return p.factions.includes("Daedalus");
},
},
{
title: "Install the special Augmentation from Daedalus",
fulfilled: (p) => {
return p.augmentations.some(aug => aug.name == "The Red Pill");
},
},
{
title: "Install the final backdoor and free yourself.",
fulfilled: () => {
return false;
},
},
];
/***/ }),
/* 877 */
/*!************************************!*\
!*** ./src/Milestones/ui/Root.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Root = void 0;
const Milestones_1 = __webpack_require__(/*! ../Milestones */ 876);
const React = __importStar(__webpack_require__(/*! react */ 0));
function highestMilestone(p, milestones) {
let n = -1;
for (let i = 0; i < milestones.length; i++) {
if (milestones[i].fulfilled(p))
n = i;
}
return n;
}
function Root(props) {
const n = highestMilestone(props.player, Milestones_1.Milestones);
const milestones = Milestones_1.Milestones.map((milestone, i) => {
if (i <= n + 1) {
return (React.createElement("ul", { key: i },
React.createElement("p", null,
"[",
milestone.fulfilled(props.player) ? "x" : " ",
"] ",
milestone.title)));
}
});
return (React.createElement(React.Fragment, null,
React.createElement("h1", null, "Milestones"),
React.createElement("p", null, "Milestones don't reward you for completing them. They are here to guide you if you're lost. They will reset when you install Augmentations."),
React.createElement("br", null),
React.createElement("h2", null, "Completing fl1ght.exe"),
React.createElement("li", null, milestones)));
}
exports.Root = Root;
/***/ }),
/* 878 */
/*!**************************************************!*\
!*** ./src/ScriptEditor/NetscriptDefinitions.ts ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.libSource = void 0;
exports.libSource = `interface NS {
args: string[];
/**
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
* Example documentation for scan.
*/
scan(ip: string, hostnames: boolean): string[];
hack(ip: string, threads: number, stock: boolean): Promise;
hackAnalyzeThreads(ip: string, hackAmount: number): number;
hackAnalyzePercent(ip: string): number;
hackChance(ip: string): number;
sleep(time: number): Promise;
grow(ip: string, threads: number, stock: boolean): Promise;
growthAnalyze(ip: string, growth: number): number;
weaken(ip: string, threads: boolean): Promise;
print(...args: any[]): void;
tprint(...args: any[]): void;
clearLog(): void;
disableLog(fn: string): void;
enableLog(fn: string): void;
isLogEnabled(fn: string): boolean;
getScriptLogs(fn: string, ip: string, ...scriptArgs: any[]): string[];
tail(fn: string, ip: string, ...scriptArgs: any[]): void;
nuke(ip: string): boolean;
brutessh(ip: string): boolean;
ftpcrack(ip: string): boolean;
relaysmtp(ip: string): boolean;
httpworm(ip: string): boolean;
sqlinject(ip: string): boolean;
run(scriptname: string, threads: number): number;
exec(scriptname: string, ip: string, threads: number): number;
spawn(scriptname: string, threads: number): void;
kill(filename: string, ip: string, ...scriptArgs: any[]): boolean;
killall(ip: string): boolean;
exit(): void;
scp(scriptname: string, ip1: string, ip2: string): boolean;
ls(ip: string, grep: string): string[];
ps(ip: string): {filename: string, threads: number, args: string[], pid: number}[];
hasRootAccess(ip: string): boolean;
getIp(): string;
getHostname(): string;
getHackingLevel(): number;
getHackingMultipliers(): number;
getHacknetMultipliers(): number;
getBitNodeMultipliers(): number;
getServer(ip: string): any;
getServerMoneyAvailable(ip: string): number;
getServerSecurityLevel(ip: string): number;
getServerBaseSecurityLevel(ip: string): number;
getServerMinSecurityLevel(ip: string): number;
getServerRequiredHackingLevel(ip: string): number;
getServerMaxMoney(ip: string): number;
getServerGrowth(ip: string): number;
getServerNumPortsRequired(ip: string): number;
getServerRam(ip: string): number[];
getServerMaxRam(ip: string): number;
getServerUsedRam(ip: string): number;
serverExists(ip: string): boolean;
fileExists(filename: string, ip: string): boolean;
isRunning(fn: string, ip: string, ...scriptArgs: any[]): boolean;
getStockSymbols(): string[];
getStockPrice(symbol: string): number;
getStockAskPrice(symbol: string): number;
getStockBidPrice(symbol: string): number;
getStockPosition(symbol: string): number;
getStockMaxShares(symbol: string): number;
getStockPurchaseCost(symbol: string, shares: number, posType: string): number;
getStockSaleGain(symbol: string, shares: number, posType: string): number;
buyStock(symbol: string, shares: number): number;
sellStock(symbol: string, shares: number): number;
shortStock(symbol: string, shares: number): number;
sellShort(symbol: string, shares: number): number;
placeOrder(symbol: string, shares: number, price: number, type: string, pos: string): boolean;
cancelOrder(symbol: string, shares: number, price: number, type: string, pos: string): boolean;
getOrders(): any;
getStockVolatility(symbol: string): number;
getStockForecast(symbol: string): number;
getPurchasedServerLimit(): number;
getPurchasedServerMaxRam(): number;
getPurchasedServerCost(ram: number): number;
purchaseServer(hostname: string, ram: number): string;
deleteServer(hostname: string): boolean;
getPurchasedServers(hostname: string): string[];
write(port: number, data: string, mode: string): boolean;
tryWrite(port: number, data: string): boolean;
read(port: number): any;
peek(port: number): any;
clear(port: number): number;
getPortHandle(port: number): any; // netscript port
rm(fn: string, ip: string): boolean;
scriptRunning(scriptname: string, ip: string): boolean;
scriptKill(scriptname: string, ip: string): boolean;
getScriptName(): string;
getScriptRam(scriptname: string, ip: string): number;
getRunningScript(fn: string, ip: string): any; // running script
getHackTime(ip: string): number;
getGrowTime(ip: string): number;
getWeakenTime(ip: string): number;
getScriptIncome(scriptname: string, ip: string): number;
getScriptExpGain(scriptname: string, ip: string): number;
nFormat(n: number, format: string): string;
tFormat(milliseconds: number, milliPrecision: boolean): string;
getTimeSinceLastAug(): number;
prompt(txt: string): Promise;
getFavorToDonate(): number;
universityCourse(universityName: string, className: string): boolean;
gymWorkout(gymName: string, stat: string): boolean;
travelToCity(cityname: string): boolean;
purchaseTor(): boolean;
purchaseProgram(programName: string): boolean;
getCurrentServer(): any; // server object
connect(hostname: string): boolean;
manualHack(): Promise;
installBackdoor(): Promise;
getStats(): any; // complex type
getCharacterInformation(): any; // complex type
getPlayer(): any; // complex type
hospitalize(): number;
isBusy(): boolean;
stopAction(): boolean;
upgradeHomeRam(): number;
getUpgradeHomeRamCost(): number;
workForCompany(companyName: string): boolean;
applyToCompany(companyName: string, field: string): boolean;
getCompanyRep(companyName: string): number;
getCompanyFavor(companyName: string): number;
getCompanyFavorGain(companyName: string): number;
checkFactionInvitations(): string[];
joinFaction(name: string): boolean;
workForFaction(name: string, type: string): boolean;
getFactionRep(name: string): number;
getFactionFavor(name: string): number;
getFactionFavorGain(name: string): number;
donateToFaction(name: string, amt: number): boolean;
createProgram(name: string): boolean;
commitCrime(crimeRoughName: string): number;
getCrimeChance(crimeRoughName: string): boolean;
getCrimeStats(crimeRoughName: string): any; // complex type
getOwnedAugmentations(purchased: boolean): string[];
getOwnedSourceFiles(): any; // complex type
getAugmentationsFromFaction(facname: string): string[];
getAugmentationPrereq(name: string): string[];
getAugmentationCost(name: string): number;
getAugmentationStats(name: string): any; // complex type
purchaseAugmentation(faction: string, name: string): boolean;
softReset(cbScript: string): void;
installAugmentations(cbScript: string): void;
exploit(): void;
bypass(doc: any): void;
flags(data: any): any;
}`;
/***/ }),
/* 879 */,
/* 880 */,
/* 881 */
/*!**********************************************!*\
!*** ./src/ScriptEditor/ui/OptionsPopup.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OptionsPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function OptionsPopup(props) {
const [theme, setTheme] = react_1.useState(props.options.theme);
const [insertSpaces, setInsertSpaces] = react_1.useState(props.options.insertSpaces);
function save() {
props.save({
theme: theme,
insertSpaces: insertSpaces,
});
createPopup_1.removePopup(props.id);
}
return (react_1.default.createElement("div", { className: "editor-options-container noselect" },
react_1.default.createElement("div", { className: "editor-options-line" },
react_1.default.createElement("p", null, "Theme: "),
react_1.default.createElement("select", { className: "dropdown", onChange: event => setTheme(event.target.value), defaultValue: theme },
react_1.default.createElement("option", { value: "vs-dark" }, "vs-dark"),
react_1.default.createElement("option", { value: "light" }, "light"))),
react_1.default.createElement("div", { className: "editor-options-line" },
react_1.default.createElement("p", null, "Use whitespace over tabs: "),
react_1.default.createElement("input", { type: "checkbox", onChange: event => setInsertSpaces(event.target.checked), checked: insertSpaces })),
react_1.default.createElement("br", null),
react_1.default.createElement(StdButton_1.StdButton, { style: { width: '50px' }, text: "Save", onClick: save })));
}
exports.OptionsPopup = OptionsPopup;
/***/ }),
/* 882 */,
/* 883 */
/*!******************************************!*\
!*** ./src/ui/React/CorruptableText.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorruptableText = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
function replace(str, i, char) {
return str.substring(0, i) + char + str.substring(i + 1);
}
function randomize(char) {
const randFrom = (str) => str[Math.floor(Math.random() * str.length)];
const classes = [
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"1234567890",
" _",
"()[]{}<>",
];
const other = `!@#$%^&*()_+|\\';"/.,?\`~`;
for (const c of classes) {
if (c.includes(char))
return randFrom(c);
}
return randFrom(other);
}
function CorruptableText(props) {
const [content, setContent] = react_1.useState(props.content);
react_1.useEffect(() => {
let counter = 5;
const id = setInterval(() => {
counter--;
if (counter > 0)
return;
counter = Math.random() * 5;
const index = Math.random() * content.length;
const letter = content.charAt(index);
setContent(replace(content, index, randomize(letter)));
setTimeout(() => {
setContent(content);
}, 50);
}, 100);
return () => {
clearInterval(id);
};
}, []);
return react_1.default.createElement("span", null, content);
}
exports.CorruptableText = CorruptableText;
/***/ }),
/* 884 */
/*!************************************!*\
!*** ./src/Casino/SlotMachine.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlotMachine = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const RNG_1 = __webpack_require__(/*! ./RNG */ 283);
const Game_1 = __webpack_require__(/*! ./Game */ 388);
const utils_1 = __webpack_require__(/*! ./utils */ 465);
// statically shuffled array of symbols.
const symbols = ["D", "C", "$", "?", "♥", "A", "C", "B", "C", "E", "B", "E", "C",
"*", "D", "♥", "B", "A", "A", "A", "C", "A", "D", "B", "E", "?", "D", "*",
"@", "♥", "B", "E", "?"];
function getPayout(s, n) {
switch (s) {
case "$":
return [20, 200, 1000][n];
case "@":
return [8, 80, 400][n];
case "♥":
case "?":
return [6, 20, 150][n];
case "D":
case "E":
return [1, 8, 30][n];
default:
return [1, 5, 20][n];
}
}
const payLines = [
// lines
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]],
[[1, 0], [1, 1], [1, 2], [1, 3], [1, 4]],
[[2, 0], [2, 1], [2, 2], [2, 3], [2, 4]],
// Vs
[[2, 0], [1, 1], [0, 2], [1, 3], [2, 4]],
[[0, 0], [1, 1], [2, 2], [1, 3], [0, 4]],
// rest
[[0, 0], [1, 1], [1, 2], [1, 3], [0, 4]],
[[2, 0], [1, 1], [1, 2], [1, 3], [2, 4]],
[[1, 0], [0, 1], [0, 2], [0, 3], [1, 4]],
[[1, 0], [2, 1], [2, 2], [2, 3], [1, 4]],
];
const minPlay = 0;
const maxPlay = 1e6;
class SlotMachine extends Game_1.Game {
constructor(props) {
super(props);
this.interval = -1;
this.rng = new RNG_1.WHRNG(this.props.p.totalPlaytime);
this.state = {
index: [0, 0, 0, 0, 0],
investment: 1000,
locks: [0, 0, 0, 0, 0],
canPlay: true,
status: 'waiting',
};
this.play = this.play.bind(this);
this.lock = this.lock.bind(this);
this.unlock = this.unlock.bind(this);
this.step = this.step.bind(this);
this.checkWinnings = this.checkWinnings.bind(this);
this.getTable = this.getTable.bind(this);
this.updateInvestment = this.updateInvestment.bind(this);
}
componentDidMount() {
this.interval = window.setInterval(this.step, 50);
}
step() {
let stoppedOne = false;
const index = this.state.index.slice();
for (const i in index) {
if (index[i] === this.state.locks[i] && !stoppedOne)
continue;
index[i] = (index[i] + 1) % symbols.length;
stoppedOne = true;
}
this.setState({ index: index });
if (stoppedOne && index.every((e, i) => e === this.state.locks[i])) {
this.checkWinnings();
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
getTable() {
return [
[symbols[(this.state.index[0] + symbols.length - 1) % symbols.length], symbols[(this.state.index[1] + symbols.length - 1) % symbols.length], symbols[(this.state.index[2] + symbols.length - 1) % symbols.length], symbols[(this.state.index[3] + symbols.length - 1) % symbols.length], symbols[(this.state.index[4] + symbols.length - 1) % symbols.length]],
[symbols[this.state.index[0]], symbols[this.state.index[1]], symbols[this.state.index[2]], symbols[this.state.index[3]], symbols[this.state.index[4]]],
[symbols[(this.state.index[0] + 1) % symbols.length], symbols[(this.state.index[1] + 1) % symbols.length], symbols[(this.state.index[2] + 1) % symbols.length], symbols[(this.state.index[3] + 1) % symbols.length], symbols[(this.state.index[4] + 1) % symbols.length]],
];
}
play() {
if (this.reachedLimit(this.props.p))
return;
this.setState({ status: 'playing' });
this.win(this.props.p, -this.state.investment);
if (!this.state.canPlay)
return;
this.unlock();
setTimeout(this.lock, this.rng.random() * 2000 + 1000);
}
lock() {
this.setState({
locks: [
Math.floor(this.rng.random() * symbols.length),
Math.floor(this.rng.random() * symbols.length),
Math.floor(this.rng.random() * symbols.length),
Math.floor(this.rng.random() * symbols.length),
Math.floor(this.rng.random() * symbols.length),
],
});
}
checkWinnings() {
const t = this.getTable();
const getPaylineData = function (payline) {
const data = [];
for (const point of payline) {
data.push(t[point[0]][point[1]]);
}
return data;
};
const countSequence = function (data) {
let count = 1;
for (let i = 1; i < data.length; i++) {
if (data[i] !== data[i - 1])
break;
count++;
}
return count;
};
let gains = -this.state.investment;
for (const payline of payLines) {
const data = getPaylineData(payline);
const count = countSequence(data);
if (count < 3)
continue;
const payout = getPayout(data[0], count - 3);
gains += this.state.investment * payout;
this.win(this.props.p, this.state.investment * payout);
}
this.setState({
status: React.createElement(React.Fragment, null,
gains > 0 ? "gained" : "lost",
" ",
Money_1.Money(Math.abs(gains))),
canPlay: true,
});
if (this.reachedLimit(this.props.p))
return;
}
unlock() {
this.setState({
locks: [-1, -1, -1, -1, -1],
canPlay: false,
});
}
updateInvestment(e) {
let investment = parseInt(e.currentTarget.value);
if (isNaN(investment)) {
investment = minPlay;
}
if (investment > maxPlay) {
investment = maxPlay;
}
if (investment < minPlay) {
investment = minPlay;
}
this.setState({ investment: investment });
}
render() {
const t = this.getTable();
return React.createElement(React.Fragment, null,
React.createElement("pre", null,
"+\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014+",
React.createElement("br", null),
"| | ",
t[0][0],
" | ",
t[0][1],
" | ",
t[0][2],
" | ",
t[0][3],
" | ",
t[0][4],
" | |",
React.createElement("br", null),
"| | | | | | | |",
React.createElement("br", null),
"| | ",
symbols[this.state.index[0]],
" | ",
symbols[this.state.index[1]],
" | ",
symbols[this.state.index[2]],
" | ",
symbols[this.state.index[3]],
" | ",
symbols[this.state.index[4]],
" | |",
React.createElement("br", null),
"| | | | | | | |",
React.createElement("br", null),
"| | ",
symbols[(this.state.index[0] + 1) % symbols.length],
" | ",
symbols[(this.state.index[1] + 1) % symbols.length],
" | ",
symbols[(this.state.index[2] + 1) % symbols.length],
" | ",
symbols[(this.state.index[3] + 1) % symbols.length],
" | ",
symbols[(this.state.index[4] + 1) % symbols.length],
" | |",
React.createElement("br", null),
"+\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014+",
React.createElement("br", null)),
React.createElement("input", { type: "number", className: "text-input", onChange: this.updateInvestment, placeholder: "Amount to play", value: this.state.investment, disabled: !this.state.canPlay }),
React.createElement(StdButton_1.StdButton, { onClick: utils_1.trusted(this.play), text: "Spin!", disabled: !this.state.canPlay }),
React.createElement("h1", null, this.state.status),
React.createElement("h2", null, "Pay lines"),
React.createElement("pre", null,
"----- \u00B7\u00B7\u00B7\u00B7\u00B7 \u00B7\u00B7\u00B7\u00B7\u00B7 ",
React.createElement("br", null),
"\u00B7\u00B7\u00B7\u00B7\u00B7 ----- \u00B7\u00B7\u00B7\u00B7\u00B7 ",
React.createElement("br", null),
"\u00B7\u00B7\u00B7\u00B7\u00B7 \u00B7\u00B7\u00B7\u00B7\u00B7 ----- ",
React.createElement("br", null)),
React.createElement("br", null),
React.createElement("pre", null,
"\u00B7\u00B7^\u00B7\u00B7 \\\u00B7\u00B7\u00B7/ \\\u00B7\u00B7\u00B7/",
React.createElement("br", null),
"\u00B7/\u00B7\\\u00B7 \u00B7\\\u00B7/\u00B7 \u00B7---\u00B7",
React.createElement("br", null),
"/\u00B7\u00B7\u00B7\\ \u00B7\u00B7v\u00B7\u00B7 \u00B7\u00B7\u00B7\u00B7\u00B7",
React.createElement("br", null)),
React.createElement("br", null),
React.createElement("pre", null,
"\u00B7\u00B7\u00B7\u00B7\u00B7 \u00B7---\u00B7 \u00B7\u00B7\u00B7\u00B7\u00B7",
React.createElement("br", null),
"\u00B7---\u00B7 /\u00B7\u00B7\u00B7\\ \\\u00B7\u00B7\u00B7/",
React.createElement("br", null),
"/\u00B7\u00B7\u00B7\\ \u00B7\u00B7\u00B7\u00B7\u00B7 \u00B7---\u00B7",
React.createElement("br", null)));
}
}
exports.SlotMachine = SlotMachine;
// https://felgo.com/doc/how-to-make-a-slot-game-tutorial/
/***/ }),
/* 885 */
/*!*********************************!*\
!*** ./src/Casino/Roulette.tsx ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Roulette = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const Game_1 = __webpack_require__(/*! ./Game */ 388);
const RNG_1 = __webpack_require__(/*! ./RNG */ 283);
const utils_1 = __webpack_require__(/*! ./utils */ 465);
const minPlay = 0;
const maxPlay = 1e7;
function isRed(n) {
return [1, 3, 5, 7, 9, 12, 14, 16, 18, 19,
21, 23, 25, 27, 30, 32, 34, 36].includes(n);
}
const redNumbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19,
21, 23, 25, 27, 30, 32, 34, 36];
const strategies = {
Red: {
match: (n) => {
if (n === 0)
return false;
return redNumbers.includes(n);
},
payout: 1,
},
Black: {
match: (n) => {
return !redNumbers.includes(n);
},
payout: 1,
},
Odd: {
match: (n) => {
if (n === 0)
return false;
return n % 2 === 1;
},
payout: 1,
},
Even: {
match: (n) => {
if (n === 0)
return false;
return n % 2 === 0;
},
payout: 1,
},
High: {
match: (n) => {
if (n === 0)
return false;
return n > 18;
},
payout: 1,
},
Low: {
match: (n) => {
if (n === 0)
return false;
return n < 19;
},
payout: 1,
},
Third1: {
match: (n) => {
if (n === 0)
return false;
return n <= 12;
},
payout: 2,
},
Third2: {
match: (n) => {
if (n === 0)
return false;
return n >= 13 && n <= 24;
},
payout: 2,
},
Third3: {
match: (n) => {
if (n === 0)
return false;
return n >= 25;
},
payout: 2,
},
};
function Single(s) {
return {
match: (n) => {
return s === n;
},
payout: 36,
};
}
class Roulette extends Game_1.Game {
constructor(props) {
super(props);
this.interval = -1;
this.rng = new RNG_1.WHRNG((new Date()).getTime());
this.state = {
investment: 1000,
canPlay: true,
status: 'waiting',
n: 0,
lock: true,
strategy: {
payout: 0,
match: () => { return false; },
},
};
this.step = this.step.bind(this);
this.currentNumber = this.currentNumber.bind(this);
this.updateInvestment = this.updateInvestment.bind(this);
}
componentDidMount() {
this.interval = window.setInterval(this.step, 50);
}
step() {
if (!this.state.lock) {
this.setState({ n: Math.floor(Math.random() * 37) });
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
updateInvestment(e) {
let investment = parseInt(e.currentTarget.value);
if (isNaN(investment)) {
investment = minPlay;
}
if (investment > maxPlay) {
investment = maxPlay;
}
if (investment < minPlay) {
investment = minPlay;
}
this.setState({ investment: investment });
}
currentNumber() {
if (this.state.n === 0)
return '0';
const color = isRed(this.state.n) ? 'R' : 'B';
return `${this.state.n}${color}`;
}
play(s) {
if (this.reachedLimit(this.props.p))
return;
this.setState({
canPlay: false,
lock: false,
status: 'playing',
strategy: s,
});
setTimeout(() => {
let n = Math.floor(this.rng.random() * 37);
let status = React.createElement(React.Fragment, null);
let gain = 0;
let playerWin = this.state.strategy.match(n);
// oh yeah, the house straight up cheats. Try finding the seed now!
if (playerWin && Math.random() > 0.9) {
playerWin = false;
while (this.state.strategy.match(n)) {
n++;
}
}
if (playerWin) {
gain = this.state.investment * this.state.strategy.payout;
status = React.createElement(React.Fragment, null,
"won ",
Money_1.Money(gain));
}
else {
gain = -this.state.investment;
status = React.createElement(React.Fragment, null,
"lost ",
Money_1.Money(-gain));
}
this.win(this.props.p, gain);
this.setState({
canPlay: true,
lock: true,
status: status,
n: n,
});
this.reachedLimit(this.props.p);
}, 1600);
}
render() {
return React.createElement(React.Fragment, null,
React.createElement("h1", null, this.currentNumber()),
React.createElement("input", { type: "number", className: "text-input", onChange: this.updateInvestment, placeholder: "Amount to play", value: this.state.investment, disabled: !this.state.canPlay }),
React.createElement("h1", null, this.state.status),
React.createElement("table", null,
React.createElement("tbody", null,
React.createElement("tr", null,
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "3", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(3))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "6", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(6))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "9", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(9))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "12", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(12))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "15", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(15))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "18", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(18))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "21", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(21))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "24", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(24))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "27", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(27))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "30", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(30))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "33", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(33))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "36", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(36))) }))),
React.createElement("tr", null,
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "2", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(2))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "5", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(5))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "8", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(8))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "11", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(11))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "14", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(14))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "17", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(17))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "20", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(20))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "23", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(23))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "26", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(26))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "29", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(29))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "32", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(32))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "35", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(35))) }))),
React.createElement("tr", null,
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "1", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(1))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "4", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(4))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "7", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(7))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "10", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(10))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "13", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(13))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "16", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(16))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "19", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(19))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "22", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(22))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "25", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(25))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "28", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(28))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "31", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(31))) })),
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "34", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(34))) }))),
React.createElement("tr", null,
React.createElement("td", { colSpan: 4 },
React.createElement(StdButton_1.StdButton, { text: "1 to 12", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Third1)) })),
React.createElement("td", { colSpan: 4 },
React.createElement(StdButton_1.StdButton, { text: "13 to 24", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Third2)) })),
React.createElement("td", { colSpan: 4 },
React.createElement(StdButton_1.StdButton, { text: "25 to 36", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Third3)) }))),
React.createElement("tr", null,
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "Red", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Red)) })),
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "Black", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Black)) })),
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "Odd", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Odd)) })),
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "Even", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Even)) })),
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "High", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.High)) })),
React.createElement("td", { colSpan: 2 },
React.createElement(StdButton_1.StdButton, { text: "Low", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(strategies.Low)) }))),
React.createElement("tr", null,
React.createElement("td", null,
React.createElement(StdButton_1.StdButton, { text: "0", disabled: !this.state.canPlay, onClick: utils_1.trusted(() => this.play(Single(0))) }))))));
}
}
exports.Roulette = Roulette;
/***/ }),
/* 886 */
/*!*********************************!*\
!*** ./src/Casino/CoinFlip.tsx ***!
\*********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoinFlip = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a gym
*
* This subcomponent renders all of the buttons for training at the gym
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../ui/React/StdButton */ 56);
const RNG_1 = __webpack_require__(/*! ./RNG */ 283);
const Game_1 = __webpack_require__(/*! ./Game */ 388);
const utils_1 = __webpack_require__(/*! ./utils */ 465);
const minPlay = 0;
const maxPlay = 10e3;
class CoinFlip extends Game_1.Game {
constructor(props) {
super(props);
this.state = {
investment: 1000,
result: React.createElement("span", null, " "),
status: '',
playLock: false,
};
this.play = this.play.bind(this);
this.updateInvestment = this.updateInvestment.bind(this);
}
updateInvestment(e) {
let investment = parseInt(e.currentTarget.value);
if (isNaN(investment)) {
investment = minPlay;
}
if (investment > maxPlay) {
investment = maxPlay;
}
if (investment < minPlay) {
investment = minPlay;
}
this.setState({ investment: investment });
}
play(guess) {
if (this.reachedLimit(this.props.p))
return;
const v = RNG_1.BadRNG.random();
let letter;
if (v < 0.5) {
letter = 'H';
}
else {
letter = 'T';
}
const correct = guess === letter;
this.setState({
result: React.createElement("span", { className: correct ? "text" : "failure" }, letter),
status: correct ? " win!" : "lose!",
playLock: true,
});
setTimeout(() => this.setState({ playLock: false }), 250);
if (correct) {
this.win(this.props.p, this.state.investment);
}
else {
this.win(this.props.p, -this.state.investment);
}
if (this.reachedLimit(this.props.p))
return;
}
render() {
return React.createElement(React.Fragment, null,
React.createElement("pre", null,
"+\u2014\u2014\u2014\u2014\u2014\u2014\u2014+",
React.createElement("br", null),
"| | | |",
React.createElement("br", null),
"| | ",
this.state.result,
" | |",
React.createElement("br", null),
"| | | |",
React.createElement("br", null),
"+\u2014\u2014\u2014\u2014\u2014\u2014\u2014+",
React.createElement("br", null)),
React.createElement("span", { className: "text" }, "Play for: "),
React.createElement("input", { type: "number", className: "text-input", onChange: this.updateInvestment, value: this.state.investment }),
React.createElement("br", null),
React.createElement(StdButton_1.StdButton, { onClick: utils_1.trusted(() => this.play('H')), text: "Head!", disabled: this.state.playLock }),
React.createElement(StdButton_1.StdButton, { onClick: utils_1.trusted(() => this.play('T')), text: "Tail!", disabled: this.state.playLock }),
React.createElement("h1", null, this.state.status));
}
}
exports.CoinFlip = CoinFlip;
/***/ }),
/* 887 */
/*!***********************************!*\
!*** ./src/ui/React/MuiPaper.tsx ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Wrapper around material-ui's Button component that styles it with
* Bitburner's UI theme
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MuiPaper = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const core_1 = __webpack_require__(/*! @material-ui/core */ 387);
const useStyles = core_1.makeStyles({
root: {
backgroundColor: "rgb(30, 30, 30)",
border: "2px solid #000",
borderRadius: "10px",
display: "inline-block",
flexWrap: "wrap",
padding: "10px",
},
});
const MuiPaper = (props) => {
return (react_1.default.createElement(core_1.Paper, Object.assign({}, props, { classes: Object.assign(Object.assign({}, useStyles()), props.classes) })));
};
exports.MuiPaper = MuiPaper;
/***/ }),
/* 888 */
/*!************************************!*\
!*** ./src/ui/React/MuiButton.tsx ***!
\************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Wrapper around material-ui's Button component that styles it with
* Bitburner's UI theme
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MuiButton = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const core_1 = __webpack_require__(/*! @material-ui/core */ 387);
const useStyles = core_1.makeStyles({
// Tries to emulate StdButton in buttons.scss
root: {
backgroundColor: "#555",
border: "1px solid #333",
color: "white",
margin: "5px",
padding: "3px 5px",
"&:hover": {
backgroundColor: "#666",
},
},
textPrimary: {
color: "rgb( 144, 202, 249)",
},
textSecondary: {
color: "rgb(244, 143, 177)",
},
disabled: {
backgroundColor: "#333",
color: "#fff",
cursor: "default",
},
});
const MuiButton = (props) => {
return (react_1.default.createElement(core_1.Button, Object.assign({}, props, { classes: Object.assign(Object.assign({}, useStyles()), props.classes) })));
};
exports.MuiButton = MuiButton;
/***/ }),
/* 889 */
/*!***************************************!*\
!*** ./src/ui/React/MuiTextField.tsx ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Wrapper around material-ui's TextField component that styles it with
* Bitburner's UI theme
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MuiTextField = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const core_1 = __webpack_require__(/*! @material-ui/core */ 387);
const backgroundColorStyles = {
backgroundColor: 'rgba(57, 54, 54, 0.9)',
'&:hover': {
backgroundColor: 'rgba(70, 70, 70, 0.9)',
},
};
const formControlStyles = Object.assign({ border: '1px solid #e2e2e1', overflow: 'hidden', borderRadius: 4, color: 'white' }, backgroundColorStyles);
const useStyles = core_1.makeStyles({
root: Object.assign({}, formControlStyles),
});
const useInputStyles = core_1.makeStyles({
root: Object.assign(Object.assign({}, backgroundColorStyles), { color: 'white' }),
focused: {
backgroundColor: 'rgba(70, 70, 70, 0.9)',
},
disabled: {
color: 'white',
},
});
const useLabelStyles = core_1.makeStyles({
root: {
color: 'white',
},
focused: {
color: 'white !important', // Need important to override styles from FormLabel
},
disabled: {
color: 'white !important', // Need important to override styles from FormLabel
},
});
const MuiTextField = (props) => {
var _a, _b;
return (react_1.default.createElement(core_1.TextField, Object.assign({}, props, { classes: Object.assign(Object.assign({}, useStyles()), props.classes), InputProps: Object.assign({ classes: Object.assign(Object.assign({}, useInputStyles()), (_a = props.InputProps) === null || _a === void 0 ? void 0 : _a.classes) }, props.InputProps), InputLabelProps: Object.assign({ classes: Object.assign(Object.assign({}, useLabelStyles()), (_b = props.InputLabelProps) === null || _b === void 0 ? void 0 : _b.classes) }, props.InputLabelProps) })));
};
exports.MuiTextField = MuiTextField;
/***/ }),
/* 890 */
/*!*******************************************!*\
!*** ./src/Casino/CardDeck/ReactCard.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactCard = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const Card_1 = __webpack_require__(/*! ./Card */ 631);
const ReactCard = ({ card, hidden }) => {
let suit;
switch (card.suit) {
case Card_1.Suit.Clubs:
suit = react_1.default.createElement("span", null, "\u2663");
break;
case Card_1.Suit.Diamonds:
suit = react_1.default.createElement("span", null, "\u2666");
break;
case Card_1.Suit.Hearts:
suit = react_1.default.createElement("span", null, "\u2665");
break;
case Card_1.Suit.Spades:
suit = react_1.default.createElement("span", null, "\u2660");
break;
default:
throw new Error(`MissingCaseException: ${card.suit}`);
}
return (react_1.default.createElement("div", { className: `casino-card ${card.isRedSuit() ? "red" : "black"}` },
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("div", { className: "value" }, hidden ? " - " : card.formatValue()),
react_1.default.createElement("div", { className: `suit` }, hidden ? " - " : suit))));
};
exports.ReactCard = ReactCard;
/***/ }),
/* 891 */
/*!*************************************!*\
!*** ./src/Casino/CardDeck/Hand.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Represents a Hand of cards.
*
* This class is IMMUTABLE
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hand = void 0;
class Hand {
constructor(cards) {
this.cards = cards;
}
addCards(...cards) {
return new Hand([...this.cards, ...cards]);
}
removeByIndex(i) {
if (i >= this.cards.length) {
throw new Error(`Tried to remove invalid card from Hand by index: ${i}`);
}
return new Hand([...this.cards.slice().splice(i, 1)]);
}
}
exports.Hand = Hand;
/***/ }),
/* 892 */,
/* 893 */,
/* 894 */
/*!*************************************!*\
!*** ./src/Casino/CardDeck/Deck.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Deck = void 0;
const Card_1 = __webpack_require__(/*! ./Card */ 631);
const lodash_1 = __webpack_require__(/*! lodash */ 893);
class Deck {
// Support multiple decks
constructor(numDecks = 1) {
this.numDecks = numDecks;
this.cards = [];
this.reset();
}
shuffle() {
this.cards = lodash_1.shuffle(this.cards); // Just use lodash
}
drawCard() {
if (this.cards.length == 0) {
throw new Error("Tried to draw card from empty deck");
}
return this.cards.shift(); // Guaranteed to return a Card since we throw an Error if array is empty
}
// Draws a card, resetting the deck beforehands if the Deck is empty
safeDrawCard() {
if (this.cards.length === 0) {
this.reset();
}
return this.drawCard();
}
// Reset the deck back to the original 52 cards and shuffle it
reset() {
this.cards = [];
for (let i = 1; i <= 13; ++i) {
for (let j = 0; j < this.numDecks; ++j) {
this.cards.push(new Card_1.Card(i, Card_1.Suit.Clubs));
this.cards.push(new Card_1.Card(i, Card_1.Suit.Diamonds));
this.cards.push(new Card_1.Card(i, Card_1.Suit.Hearts));
this.cards.push(new Card_1.Card(i, Card_1.Suit.Spades));
}
}
this.shuffle();
}
size() {
return this.cards.length;
}
isEmpty() {
return this.cards.length === 0;
}
}
exports.Deck = Deck;
/***/ }),
/* 895 */
/*!**********************************!*\
!*** ./src/Casino/Blackjack.tsx ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Blackjack = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const Game_1 = __webpack_require__(/*! ./Game */ 388);
const Deck_1 = __webpack_require__(/*! ./CardDeck/Deck */ 894);
const Hand_1 = __webpack_require__(/*! ./CardDeck/Hand */ 891);
const core_1 = __webpack_require__(/*! @material-ui/core */ 387);
const ReactCard_1 = __webpack_require__(/*! ./CardDeck/ReactCard */ 890);
const MuiTextField_1 = __webpack_require__(/*! ../ui/React/MuiTextField */ 889);
const MuiButton_1 = __webpack_require__(/*! ../ui/React/MuiButton */ 888);
const MuiPaper_1 = __webpack_require__(/*! ../ui/React/MuiPaper */ 887);
const MAX_BET = 100e6;
var Result;
(function (Result) {
Result["Pending"] = "";
Result["PlayerWon"] = "You won!";
Result["PlayerWonByBlackjack"] = "You Won! Blackjack!";
Result["DealerWon"] = "You lost!";
Result["Tie"] = "Push! (Tie)";
})(Result || (Result = {}));
class Blackjack extends Game_1.Game {
constructor(props) {
super(props);
this.canStartGame = () => {
const { p } = this.props;
const { bet } = this.state;
return p.canAfford(bet);
};
this.startGame = () => {
if (!this.canStartGame()) {
return;
}
// Take money from player right away so that player's dont just "leave" to avoid the loss (I mean they could
// always reload without saving but w.e)
this.props.p.loseMoney(this.state.bet);
const playerHand = new Hand_1.Hand([this.deck.safeDrawCard(), this.deck.safeDrawCard()]);
const dealerHand = new Hand_1.Hand([this.deck.safeDrawCard(), this.deck.safeDrawCard()]);
this.setState({
playerHand,
dealerHand,
gameInProgress: true,
result: Result.Pending,
});
// If the player is dealt a blackjack and the dealer is not, then the player
// immediately wins
if (this.getTrueHandValue(playerHand) === 21) {
if (this.getTrueHandValue(dealerHand) === 21) {
this.finishGame(Result.Tie);
}
else {
this.finishGame(Result.PlayerWonByBlackjack);
}
}
else if (this.getTrueHandValue(dealerHand) === 21) {
// Check if dealer won by blackjack. We know at this point that the player does not also have blackjack.
this.finishGame(Result.DealerWon);
}
};
// Returns an array of numbers representing all possible values of the given Hand. The reason it needs to be
// an array is because an Ace can count as both 1 and 11.
this.getHandValue = (hand) => {
let result = [0];
for (let i = 0; i < hand.cards.length; ++i) {
const value = hand.cards[i].value;
if (value >= 10) {
result = result.map((x) => x + 10);
}
else if (value === 1) {
result = result.flatMap((x) => [x + 1, x + 11]);
}
else {
result = result.map((x) => x + value);
}
}
return result;
};
// Returns the single hand value used for determine things like victory and whether or not
// the dealer has to hit. Essentially this uses the biggest value that's 21 or under. If no such value exists,
// then it means the hand is busted and we can just return whatever
this.getTrueHandValue = (hand) => {
const handValues = this.getHandValue(hand);
const valuesUnder21 = handValues.filter((x) => (x <= 21));
if (valuesUnder21.length > 0) {
valuesUnder21.sort((a, b) => a - b);
return valuesUnder21[valuesUnder21.length - 1];
}
else {
// Just return the first value. It doesnt really matter anyways since hand is buted
return handValues[0];
}
};
// Returns all hand values that are 21 or under. If no values are 21 or under, then the first value is returned.
this.getHandDisplayValues = (hand) => {
const handValues = this.getHandValue(hand);
if (this.isHandBusted(hand)) {
// Hand is busted so just return the 1st value, doesn't really matter
return [...new Set([handValues[0]])];
}
else {
return [...new Set(handValues.filter((x) => x <= 21))];
}
};
this.isHandBusted = (hand) => {
return this.getTrueHandValue(hand) > 21;
};
this.playerHit = (event) => {
if (!event.isTrusted) {
return;
}
const newHand = this.state.playerHand.addCards(this.deck.safeDrawCard());
this.setState({
playerHand: newHand,
});
// Check if player busted, and finish the game if so
if (this.isHandBusted(newHand)) {
this.finishGame(Result.DealerWon);
}
};
this.playerStay = (event) => {
if (!event.isTrusted) {
return;
}
// Determine if Dealer needs to hit. A dealer must hit if they have 16 or lower.
// If the dealer has a Soft 17 (Ace + 6), then they stay.
let newDealerHand = this.state.dealerHand;
while (true) {
// The dealer's "true" hand value is the 2nd one if its 21 or less (the 2nd value is always guaranteed
// to be equal or larger). Otherwise its the 1st.
const dealerHandValue = this.getTrueHandValue(newDealerHand);
if (dealerHandValue <= 16) {
newDealerHand = newDealerHand.addCards(this.deck.safeDrawCard());
}
else {
break;
}
}
this.setState({
dealerHand: newDealerHand,
});
// If dealer has busted, then player wins
if (this.isHandBusted(newDealerHand)) {
this.finishGame(Result.PlayerWon);
}
else {
const dealerHandValue = this.getTrueHandValue(newDealerHand);
const playerHandValue = this.getTrueHandValue(this.state.playerHand);
// We expect nobody to have busted. If someone busted, there is an error
// in our game logic
if (dealerHandValue > 21 || playerHandValue > 21) {
throw new Error("Someone busted when not expected to");
}
if (playerHandValue > dealerHandValue) {
this.finishGame(Result.PlayerWon);
}
else if (playerHandValue < dealerHandValue) {
this.finishGame(Result.DealerWon);
}
else {
this.finishGame(Result.Tie);
}
}
};
this.finishGame = (result) => {
let gains = 0;
if (this.isPlayerWinResult(result)) {
gains = this.state.bet;
// We 2x the gains because we took away money at the start, so we need to give the original bet back.
this.win(this.props.p, 2 * gains);
}
else if (result === Result.DealerWon) {
gains = -1 * this.state.bet;
// Dont need to take money here since we already did it at the start
}
else if (result === Result.Tie) {
this.win(this.props.p, this.state.bet); // Get the original bet back
}
this.setState({
gameInProgress: false,
result,
gains: this.state.gains + gains,
});
};
this.isPlayerWinResult = (result) => {
return (result === Result.PlayerWon || result === Result.PlayerWonByBlackjack);
};
this.wagerOnChange = (event) => {
const { p } = this.props;
const betInput = event.target.value;
const wager = Math.round(parseFloat(betInput));
if (isNaN(wager)) {
this.setState({
bet: 0,
betInput,
wagerInvalid: true,
wagerInvalidHelperText: "Not a valid number",
});
}
else if (wager <= 0) {
this.setState({
bet: 0,
betInput,
wagerInvalid: true,
wagerInvalidHelperText: "Must bet a postive amount",
});
}
else if (wager > MAX_BET) {
this.setState({
bet: 0,
betInput,
wagerInvalid: true,
wagerInvalidHelperText: "Exceeds max bet",
});
}
else if (!p.canAfford(wager)) {
this.setState({
bet: 0,
betInput,
wagerInvalid: true,
wagerInvalidHelperText: "Not enough money",
});
}
else {
// Valid wager
this.setState({
bet: wager,
betInput,
wagerInvalid: false,
wagerInvalidHelperText: "",
result: Result.Pending, // Reset previous game status to clear the win/lose text UI
});
}
};
// Start game button
this.startOnClick = (event) => {
// Protect against scripting...although maybe this would be fun to automate
if (!event.isTrusted) {
return;
}
if (!this.state.wagerInvalid) {
this.startGame();
}
};
this.deck = new Deck_1.Deck(5); // 5-deck multideck
const initialBet = 1e6;
this.state = {
playerHand: new Hand_1.Hand([]),
dealerHand: new Hand_1.Hand([]),
bet: initialBet,
betInput: String(initialBet),
gameInProgress: false,
result: Result.Pending,
gains: 0,
wagerInvalid: false,
wagerInvalidHelperText: "",
};
}
render() {
const { betInput, playerHand, dealerHand, gameInProgress, result, wagerInvalid, wagerInvalidHelperText, gains, } = this.state;
// Get the player totals to display.
const playerHandValues = this.getHandDisplayValues(playerHand);
const dealerHandValues = this.getHandDisplayValues(dealerHand);
return (React.createElement("div", null,
React.createElement("div", null,
React.createElement(MuiTextField_1.MuiTextField, { value: betInput, label: React.createElement(React.Fragment, null,
"Wager (Max: ",
Money_1.Money(MAX_BET),
")"), disabled: gameInProgress, onChange: this.wagerOnChange, error: wagerInvalid, helperText: wagerInvalid ? wagerInvalidHelperText : "", type: "number", variant: "filled", style: {
width: "200px",
}, InputProps: {
startAdornment: React.createElement(core_1.InputAdornment, { position: "start" }, "$"),
} }),
React.createElement("p", null,
"Total earnings this session: ",
Money_1.Money(gains))),
!gameInProgress ? (React.createElement("div", null,
React.createElement(MuiButton_1.MuiButton, { color: "primary", onClick: this.startOnClick, disabled: wagerInvalid || !this.canStartGame() }, "Start"))) : (React.createElement("div", null,
React.createElement(MuiButton_1.MuiButton, { color: "primary", onClick: this.playerHit }, "Hit"),
React.createElement(MuiButton_1.MuiButton, { color: "secondary", onClick: this.playerStay }, "Stay"))),
(gameInProgress || result !== Result.Pending) && (React.createElement("div", null,
React.createElement(MuiPaper_1.MuiPaper, { variant: "outlined", elevation: 2 },
React.createElement("pre", null, "Player"),
playerHand.cards.map((card, i) => (React.createElement(ReactCard_1.ReactCard, { card: card, key: i }))),
React.createElement("pre", null, "Value(s): "),
playerHandValues.map((value, i) => (React.createElement("pre", { key: i }, value)))),
React.createElement("br", null),
React.createElement(MuiPaper_1.MuiPaper, { variant: "outlined", elevation: 2 },
React.createElement("pre", null, "Dealer"),
dealerHand.cards.map((card, i) => (
// Hide every card except the first while game is in progress
React.createElement(ReactCard_1.ReactCard, { card: card, hidden: gameInProgress && i !== 0, key: i }))),
!gameInProgress && (React.createElement(React.Fragment, null,
React.createElement("pre", null, "Value(s): "),
dealerHandValues.map((value, i) => (React.createElement("pre", { key: i }, value)))))))),
result !== Result.Pending && (React.createElement("p", null,
result,
this.isPlayerWinResult(result) && (React.createElement(React.Fragment, null,
" You gained ",
Money_1.Money(this.state.bet))),
result === Result.DealerWon && (React.createElement(React.Fragment, null,
" You lost ",
Money_1.Money(this.state.bet)))))));
}
}
exports.Blackjack = Blackjack;
/***/ }),
/* 896 */
/*!*********************************************!*\
!*** ./src/Locations/ui/CasinoLocation.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CasinoLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a gym
*
* This subcomponent renders all of the buttons for training at the gym
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Blackjack_1 = __webpack_require__(/*! ../../Casino/Blackjack */ 895);
const CoinFlip_1 = __webpack_require__(/*! ../../Casino/CoinFlip */ 886);
const Roulette_1 = __webpack_require__(/*! ../../Casino/Roulette */ 885);
const SlotMachine_1 = __webpack_require__(/*! ../../Casino/SlotMachine */ 884);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
var GameType;
(function (GameType) {
GameType["None"] = "none";
GameType["Coin"] = "coin";
GameType["Slots"] = "slots";
GameType["Roulette"] = "roulette";
GameType["Blackjack"] = "blackjack";
})(GameType || (GameType = {}));
class CasinoLocation extends React.Component {
constructor(props) {
super(props);
this.state = {
game: GameType.None,
};
this.updateGame = this.updateGame.bind(this);
}
updateGame(game) {
this.setState({
game,
});
}
renderGames() {
return (React.createElement(React.Fragment, null,
React.createElement(StdButton_1.StdButton, { onClick: () => this.updateGame(GameType.Coin), text: "Play coin flip" }),
React.createElement("br", null),
React.createElement(StdButton_1.StdButton, { onClick: () => this.updateGame(GameType.Slots), text: "Play slots" }),
React.createElement("br", null),
React.createElement(StdButton_1.StdButton, { onClick: () => this.updateGame(GameType.Roulette), text: "Play roulette" }),
React.createElement("br", null),
React.createElement(StdButton_1.StdButton, { onClick: () => this.updateGame(GameType.Blackjack), text: "Play blackjack" })));
}
renderGame() {
let elem = null;
switch (this.state.game) {
case GameType.Coin:
elem = React.createElement(CoinFlip_1.CoinFlip, { p: this.props.p });
break;
case GameType.Slots:
elem = React.createElement(SlotMachine_1.SlotMachine, { p: this.props.p });
break;
case GameType.Roulette:
elem = React.createElement(Roulette_1.Roulette, { p: this.props.p });
break;
case GameType.Blackjack:
elem = React.createElement(Blackjack_1.Blackjack, { p: this.props.p });
break;
case GameType.None:
break;
default:
throw new Error(`MissingCaseException: ${this.state.game}`);
}
return (React.createElement(React.Fragment, null,
React.createElement(StdButton_1.StdButton, { onClick: () => this.updateGame(GameType.None), text: "Stop playing" }),
elem));
}
render() {
if (this.state.game === GameType.None) {
return this.renderGames();
}
else {
return this.renderGame();
}
}
}
exports.CasinoLocation = CasinoLocation;
/***/ }),
/* 897 */
/*!*************************************************!*\
!*** ./src/Locations/ui/UniversityLocation.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UniversityLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a university
*
* This subcomponent renders all of the buttons for studying/taking courses
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const ServerHelpers_1 = __webpack_require__(/*! ../../Server/ServerHelpers */ 22);
const SpecialServerIps_1 = __webpack_require__(/*! ../../Server/SpecialServerIps */ 38);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
class UniversityLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.take = this.take.bind(this);
this.study = this.study.bind(this);
this.dataStructures = this.dataStructures.bind(this);
this.networks = this.networks.bind(this);
this.algorithms = this.algorithms.bind(this);
this.management = this.management.bind(this);
this.leadership = this.leadership.bind(this);
this.calculateCost = this.calculateCost.bind(this);
}
calculateCost() {
const ip = SpecialServerIps_1.SpecialServerIps.getIp(this.props.loc.name);
const server = ServerHelpers_1.getServer(ip);
if (server == null || !server.hasOwnProperty('backdoorInstalled'))
return this.props.loc.costMult;
const discount = server.backdoorInstalled ? 0.9 : 1;
return this.props.loc.costMult * discount;
}
take(stat) {
const loc = this.props.loc;
this.props.p.startClass(this.calculateCost(), loc.expMult, stat);
}
study() {
this.take(Constants_1.CONSTANTS.ClassStudyComputerScience);
}
dataStructures() {
this.take(Constants_1.CONSTANTS.ClassDataStructures);
}
networks() {
this.take(Constants_1.CONSTANTS.ClassNetworks);
}
algorithms() {
this.take(Constants_1.CONSTANTS.ClassAlgorithms);
}
management() {
this.take(Constants_1.CONSTANTS.ClassManagement);
}
leadership() {
this.take(Constants_1.CONSTANTS.ClassLeadership);
}
render() {
const costMult = this.calculateCost();
const dataStructuresCost = Constants_1.CONSTANTS.ClassDataStructuresBaseCost * costMult;
const networksCost = Constants_1.CONSTANTS.ClassNetworksBaseCost * costMult;
const algorithmsCost = Constants_1.CONSTANTS.ClassAlgorithmsBaseCost * costMult;
const managementCost = Constants_1.CONSTANTS.ClassManagementBaseCost * costMult;
const leadershipCost = Constants_1.CONSTANTS.ClassLeadershipBaseCost * costMult;
const earnHackingExpTooltip = `Gain hacking experience!`;
const earnCharismaExpTooltip = `Gain charisma experience!`;
return (React.createElement("div", null,
React.createElement(StdButton_1.StdButton, { onClick: this.study, style: this.btnStyle, text: `Study Computer Science (free)`, tooltip: earnHackingExpTooltip }),
React.createElement(StdButton_1.StdButton, { onClick: this.dataStructures, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Take Data Structures course (",
Money_1.Money(dataStructuresCost),
" / sec)"), tooltip: earnHackingExpTooltip }),
React.createElement(StdButton_1.StdButton, { onClick: this.networks, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Take Networks course (",
Money_1.Money(networksCost),
" / sec)"), tooltip: earnHackingExpTooltip }),
React.createElement(StdButton_1.StdButton, { onClick: this.algorithms, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Take Algorithms course (",
Money_1.Money(algorithmsCost),
" / sec)"), tooltip: earnHackingExpTooltip }),
React.createElement(StdButton_1.StdButton, { onClick: this.management, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Take Management course (",
Money_1.Money(managementCost),
" / sec)"), tooltip: earnCharismaExpTooltip }),
React.createElement(StdButton_1.StdButton, { onClick: this.leadership, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Take Leadership course (",
Money_1.Money(leadershipCost),
" / sec)"), tooltip: earnCharismaExpTooltip })));
}
}
exports.UniversityLocation = UniversityLocation;
/***/ }),
/* 898 */
/*!***************************************************!*\
!*** ./src/Locations/ui/TravelAgencyLocation.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TravelAgencyLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a Travel Agency
*
* TThis subcomponent renders all of the buttons for traveling to different cities
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const CityNames_1 = __webpack_require__(/*! ../data/CityNames */ 42);
const LocationsHelpers_1 = __webpack_require__(/*! ../LocationsHelpers */ 469);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
class TravelAgencyLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
}
asciiWorldMap() {
const LocationLetter = (props) => {
if (props.city !== this.props.p.city) {
return React.createElement("span", { className: "tooltip", style: { color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px' }, onClick: LocationsHelpers_1.createTravelPopup.bind(null, props.city, this.props.travel) },
React.createElement("span", { className: "tooltiptext" }, props.city),
props.city[0]);
}
return React.createElement("span", null, props.city[0]);
};
return (React.createElement("div", { className: "noselect" },
React.createElement("p", null,
"From here, you can travel to any other city! A ticket costs ",
Money_1.Money(Constants_1.CONSTANTS.TravelCost),
"."),
React.createElement("pre", null, " ,_ . ._. _. ."),
React.createElement("pre", null, " , _-\\','|~\\~ ~/ ;-'_ _-' ,;_;_, ~~-"),
React.createElement("pre", null, " /~~-\\_/-'~'--' \\~~| ', ,' / / ~|-_\\_/~/~ ~~--~~~~'--_"),
React.createElement("pre", null,
" / ,/'-/~ '\\ ,' _ , '",
React.createElement(LocationLetter, { city: "Volhaven" }),
",'|~ ._/-, /~"),
React.createElement("pre", null, " ~/-'~\\_, '-,| '|. ' ~ ,\\ /'~ / /_ /~"),
React.createElement("pre", null,
".-~ '| '',\\~|\\ _\\~ ,_ , ",
React.createElement(LocationLetter, { city: "Chongqing" }),
" /,"),
React.createElement("pre", null,
" '\\ ",
React.createElement(LocationLetter, { city: "Sector-12" }),
" /'~ |_/~\\\\,-,~ \\ \" ,_,/ |"),
React.createElement("pre", null,
" | / ._-~'\\_ _~| \\ ) ",
React.createElement(LocationLetter, { city: "New Tokyo" })),
React.createElement("pre", null, " \\ __-\\ '/ ~ |\\ \\_ / ~"),
React.createElement("pre", null, " ., '\\ |, ~-_ - | \\\\_' ~| /\\ \\~ ,"),
React.createElement("pre", null, " ~-_' _; '\\ '-, \\,' /\\/ |"),
React.createElement("pre", null, " '\\_,~'\\_ \\_ _, /' ' |, /|'"),
React.createElement("pre", null, " / \\_ ~ | / \\ ~'; -,_."),
React.createElement("pre", null, " | ~\\ | | , '-_, ,; ~ ~\\"),
React.createElement("pre", null,
" \\, ",
React.createElement(LocationLetter, { city: "Aevum" }),
" / \\ / /| ,-, , -,"),
React.createElement("pre", null, " | ,/ | |' |/ ,- ~ \\ '."),
React.createElement("pre", null,
" ,| ,/ \\ ,/ \\ ",
React.createElement(LocationLetter, { city: "Ishima" }),
" |"),
React.createElement("pre", null, " / | ~ -~~-, / _"),
React.createElement("pre", null, " | ,-' ~ /"),
React.createElement("pre", null, " / ,' ~"),
React.createElement("pre", null, " ',| ~"),
React.createElement("pre", null, " ~'")));
}
listWorldMap() {
const travelBtns = [];
for (const key in CityNames_1.CityName) {
const city = CityNames_1.CityName[key];
// Skip current city
if (city === this.props.p.city) {
continue;
}
travelBtns.push(React.createElement(StdButton_1.StdButton, { key: city, onClick: LocationsHelpers_1.createTravelPopup.bind(null, city, this.props.travel), style: this.btnStyle, text: `Travel to ${city}` }));
}
return (React.createElement("div", null,
React.createElement("p", null,
"From here, you can travel to any other city! A ticket costs ",
Money_1.Money(Constants_1.CONSTANTS.TravelCost),
"."),
travelBtns));
}
render() {
if (Settings_1.Settings.DisableASCIIArt) {
return this.listWorldMap();
}
else {
return this.asciiWorldMap();
}
}
}
exports.TravelAgencyLocation = TravelAgencyLocation;
/***/ }),
/* 899 */
/*!*************************************************!*\
!*** ./src/Locations/ui/TechVendorLocation.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TechVendorLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a tech vendor
*
* This subcomponent renders all of the buttons for purchasing things from tech vendors
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const LocationsHelpers_1 = __webpack_require__(/*! ../LocationsHelpers */ 469);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const ServerPurchases_1 = __webpack_require__(/*! ../../Server/ServerPurchases */ 136);
const StdButtonPurchased_1 = __webpack_require__(/*! ../../ui/React/StdButtonPurchased */ 647);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
class TechVendorLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.state = {
torPurchased: props.p.hasTorRouter(),
};
this.createUpgradeHomeCoresPopup = this.createUpgradeHomeCoresPopup.bind(this);
this.createUpgradeHomeRamPopup = this.createUpgradeHomeRamPopup.bind(this);
this.purchaseTorRouter = this.purchaseTorRouter.bind(this);
}
createUpgradeHomeCoresPopup() {
LocationsHelpers_1.createUpgradeHomeCoresPopup(this.props.p);
}
createUpgradeHomeRamPopup() {
LocationsHelpers_1.createUpgradeHomeRamPopup(this.props.p);
}
purchaseTorRouter() {
LocationsHelpers_1.purchaseTorRouter(this.props.p);
this.setState({
torPurchased: this.props.p.hasTorRouter(),
});
}
render() {
const loc = this.props.loc;
const purchaseServerButtons = [];
for (let i = loc.techVendorMinRam; i <= loc.techVendorMaxRam; i *= 2) {
const cost = ServerPurchases_1.getPurchaseServerCost(i);
purchaseServerButtons.push(React.createElement(StdButton_1.StdButton, { key: i, onClick: () => LocationsHelpers_1.createPurchaseServerPopup(i, this.props.p), style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Purchase ",
i,
"GB Server - ",
Money_1.Money(cost)) }));
}
return (React.createElement("div", null,
purchaseServerButtons,
this.state.torPurchased ? (React.createElement(StdButtonPurchased_1.StdButtonPurchased, { style: this.btnStyle, text: "TOR Router - Purchased" })) : (React.createElement(StdButton_1.StdButton, { onClick: this.purchaseTorRouter, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Purchase TOR Router - ",
Money_1.Money(Constants_1.CONSTANTS.TorRouterCost)) })),
React.createElement(StdButton_1.StdButton, { onClick: this.createUpgradeHomeRamPopup, style: this.btnStyle, text: `Purchase additional RAM for Home computer` }),
React.createElement(StdButton_1.StdButton, { onClick: this.createUpgradeHomeCoresPopup, style: this.btnStyle, text: `Purchase additional Core for Home computer` })));
}
}
exports.TechVendorLocation = TechVendorLocation;
/***/ }),
/* 900 */
/*!**********************************************!*\
!*** ./src/Locations/ui/SpecialLocation.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpecialLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location has special
* actions/options/properties
*
* Examples:
* - Bladeburner @ NSA
* - Re-sleeving @ VitaLife
* - Create Corporation @ City Hall
*
* This subcomponent creates all of the buttons for interacting with those special
* properties
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const LocationsHelpers_1 = __webpack_require__(/*! ../LocationsHelpers */ 469);
const LocationNames_1 = __webpack_require__(/*! ../data/LocationNames */ 40);
const AutoupdatingStdButton_1 = __webpack_require__(/*! ../../ui/React/AutoupdatingStdButton */ 470);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
class SpecialLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.renderNoodleBar = this.renderNoodleBar.bind(this);
this.createCorporationPopup = this.createCorporationPopup.bind(this);
this.handleBladeburner = this.handleBladeburner.bind(this);
this.handleResleeving = this.handleResleeving.bind(this);
this.state = {
inBladeburner: this.props.p.inBladeburner(),
};
}
/**
* Click handler for "Create Corporation" button at Sector-12 City Hall
*/
createCorporationPopup() {
LocationsHelpers_1.createStartCorporationPopup(this.props.p);
}
/**
* Click handler for Bladeburner button at Sector-12 NSA
*/
handleBladeburner() {
const p = this.props.p;
if (p.inBladeburner()) {
// Enter Bladeburner division
this.props.engine.loadBladeburnerContent();
}
else {
// Apply for Bladeburner division
if (p.strength >= 100 && p.defense >= 100 && p.dexterity >= 100 && p.agility >= 100) {
p.startBladeburner({ new: true });
DialogBox_1.dialogBoxCreate("You have been accepted into the Bladeburner division!");
this.setState({
inBladeburner: true,
});
const worldHeader = document.getElementById("world-menu-header");
if (worldHeader instanceof HTMLElement) {
worldHeader.click();
worldHeader.click();
}
}
else {
DialogBox_1.dialogBoxCreate("Rejected! Please apply again when you have 100 of each combat stat (str, def, dex, agi)");
}
}
}
/**
* Click handler for Resleeving button at New Tokyo VitaLife
*/
handleResleeving() {
this.props.engine.loadResleevingContent();
}
renderBladeburner() {
if (!this.props.p.canAccessBladeburner()) {
return null;
}
const text = this.state.inBladeburner ? "Enter Bladeburner Headquarters" : "Apply to Bladeburner Division";
return (React.createElement(StdButton_1.StdButton, { onClick: this.handleBladeburner, style: this.btnStyle, text: text }));
}
renderNoodleBar() {
function EatNoodles() {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null, "You ate some delicious noodles and feel refreshed."));
}
return (React.createElement(StdButton_1.StdButton, { onClick: EatNoodles, style: this.btnStyle, text: 'Eat noodles' }));
}
renderCreateCorporation() {
if (!this.props.p.canAccessCorporation()) {
return React.createElement(React.Fragment, null,
React.createElement("p", null,
React.createElement("i", null, "A business man is yelling at a clerk. You should come back later.")));
}
return (React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { disabled: !this.props.p.canAccessCorporation() || this.props.p.hasCorporation(), onClick: this.createCorporationPopup, style: this.btnStyle, text: "Create a Corporation" }));
}
renderResleeving() {
if (!this.props.p.canAccessResleeving()) {
return null;
}
return (React.createElement(StdButton_1.StdButton, { onClick: this.handleResleeving, style: this.btnStyle, text: "Re-Sleeve" }));
}
render() {
switch (this.props.loc.name) {
case LocationNames_1.LocationName.NewTokyoVitaLife: {
return this.renderResleeving();
}
case LocationNames_1.LocationName.Sector12CityHall: {
return this.renderCreateCorporation();
}
case LocationNames_1.LocationName.Sector12NSA: {
return this.renderBladeburner();
}
case LocationNames_1.LocationName.NewTokyoNoodleBar: {
return this.renderNoodleBar();
}
default:
console.error(`Location ${this.props.loc.name} doesn't have any special properties`);
break;
}
}
}
exports.SpecialLocation = SpecialLocation;
/***/ }),
/* 901 */
/*!********************************************!*\
!*** ./src/Locations/ui/SlumsLocation.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlumsLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a slum
*
* This subcomponent renders all of the buttons for committing crimes
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Crimes_1 = __webpack_require__(/*! ../../Crime/Crimes */ 169);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const AutoupdatingStdButton_1 = __webpack_require__(/*! ../../ui/React/AutoupdatingStdButton */ 470);
class SlumsLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.shoplift = this.shoplift.bind(this);
this.robStore = this.robStore.bind(this);
this.mug = this.mug.bind(this);
this.larceny = this.larceny.bind(this);
this.dealDrugs = this.dealDrugs.bind(this);
this.bondForgery = this.bondForgery.bind(this);
this.traffickArms = this.traffickArms.bind(this);
this.homicide = this.homicide.bind(this);
this.grandTheftAuto = this.grandTheftAuto.bind(this);
this.kidnap = this.kidnap.bind(this);
this.assassinate = this.assassinate.bind(this);
this.heist = this.heist.bind(this);
}
shoplift(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Shoplift.commit(this.props.p);
}
robStore(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.RobStore.commit(this.props.p);
}
mug(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Mug.commit(this.props.p);
}
larceny(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Larceny.commit(this.props.p);
}
dealDrugs(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.DealDrugs.commit(this.props.p);
}
bondForgery(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.BondForgery.commit(this.props.p);
}
traffickArms(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.TraffickArms.commit(this.props.p);
}
homicide(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Homicide.commit(this.props.p);
}
grandTheftAuto(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.GrandTheftAuto.commit(this.props.p);
}
kidnap(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Kidnap.commit(this.props.p);
}
assassinate(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Assassination.commit(this.props.p);
}
heist(e) {
if (!e.isTrusted) {
return;
}
Crimes_1.Crimes.Heist.commit(this.props.p);
}
render() {
const shopliftChance = Crimes_1.Crimes.Shoplift.successRate(this.props.p);
const robStoreChance = Crimes_1.Crimes.RobStore.successRate(this.props.p);
const mugChance = Crimes_1.Crimes.Mug.successRate(this.props.p);
const larcenyChance = Crimes_1.Crimes.Larceny.successRate(this.props.p);
const drugsChance = Crimes_1.Crimes.DealDrugs.successRate(this.props.p);
const bondChance = Crimes_1.Crimes.BondForgery.successRate(this.props.p);
const armsChance = Crimes_1.Crimes.TraffickArms.successRate(this.props.p);
const homicideChance = Crimes_1.Crimes.Homicide.successRate(this.props.p);
const gtaChance = Crimes_1.Crimes.GrandTheftAuto.successRate(this.props.p);
const kidnapChance = Crimes_1.Crimes.Kidnap.successRate(this.props.p);
const assassinateChance = Crimes_1.Crimes.Assassination.successRate(this.props.p);
const heistChance = Crimes_1.Crimes.Heist.successRate(this.props.p);
return (React.createElement("div", null,
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.shoplift, style: this.btnStyle, text: `Shoplift (${numeralFormat_1.numeralWrapper.formatPercentage(shopliftChance)} chance of success)`, tooltip: "Attempt to shoplift from a low-end retailer" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.robStore, style: this.btnStyle, text: `Rob store (${numeralFormat_1.numeralWrapper.formatPercentage(robStoreChance)} chance of success)`, tooltip: "Attempt to commit armed robbery on a high-end store" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.mug, style: this.btnStyle, text: `Mug someone (${numeralFormat_1.numeralWrapper.formatPercentage(mugChance)} chance of success)`, tooltip: "Attempt to mug a random person on the street" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.larceny, style: this.btnStyle, text: `Larceny (${numeralFormat_1.numeralWrapper.formatPercentage(larcenyChance)} chance of success)`, tooltip: "Attempt to rob property from someone's house" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.dealDrugs, style: this.btnStyle, text: `Deal Drugs (${numeralFormat_1.numeralWrapper.formatPercentage(drugsChance)} chance of success)`, tooltip: "Attempt to deal drugs" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.bondForgery, style: this.btnStyle, text: `Bond Forgery (${numeralFormat_1.numeralWrapper.formatPercentage(bondChance)} chance of success)`, tooltip: "Attempt to forge corporate bonds" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.traffickArms, style: this.btnStyle, text: `Traffick illegal Arms (${numeralFormat_1.numeralWrapper.formatPercentage(armsChance)} chance of success)`, tooltip: "Attempt to smuggle illegal arms into the city" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.homicide, style: this.btnStyle, text: `Homicide (${numeralFormat_1.numeralWrapper.formatPercentage(homicideChance)} chance of success)`, tooltip: "Attempt to murder a random person on the street" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.grandTheftAuto, style: this.btnStyle, text: `Grand theft Auto (${numeralFormat_1.numeralWrapper.formatPercentage(gtaChance)} chance of success)`, tooltip: "Attempt to commit grand theft auto" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.kidnap, style: this.btnStyle, text: `Kidnap and Ransom (${numeralFormat_1.numeralWrapper.formatPercentage(kidnapChance)} chance of success)`, tooltip: "Attempt to kidnap and ransom a high-profile-target" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.assassinate, style: this.btnStyle, text: `Assassinate (${numeralFormat_1.numeralWrapper.formatPercentage(assassinateChance)} chance of success)`, tooltip: "Attempt to assassinate a high-profile target" }),
React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { intervalTime: 5e3, onClick: this.heist, style: this.btnStyle, text: `Heist (${numeralFormat_1.numeralWrapper.formatPercentage(heistChance)} chance of success)`, tooltip: "Attempt to pull off the ultimate heist" })));
}
}
exports.SlumsLocation = SlumsLocation;
/***/ }),
/* 902 */
/*!***********************************************!*\
!*** ./src/Locations/ui/HospitalLocation.tsx ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HospitalLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a hospital
*
* This subcomponent renders all of the buttons for hospital options
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Hospital_1 = __webpack_require__(/*! ../../Hospital/Hospital */ 412);
const AutoupdatingStdButton_1 = __webpack_require__(/*! ../../ui/React/AutoupdatingStdButton */ 470);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
class HospitalLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.getCost = this.getCost.bind(this);
this.getHealed = this.getHealed.bind(this);
this.state = {
currHp: this.props.p.hp,
};
}
getCost() {
return Hospital_1.getHospitalizationCost(this.props.p);
}
getHealed(e) {
if (!e.isTrusted) {
return;
}
if (this.props.p.hp < 0) {
this.props.p.hp = 0;
}
if (this.props.p.hp >= this.props.p.max_hp) {
return;
}
const cost = this.getCost();
this.props.p.loseMoney(cost);
this.props.p.hp = this.props.p.max_hp;
this.props.p.recordMoneySource(-1 * cost, 'hospitalization');
// This just forces a re-render to update the cost
this.setState({
currHp: this.props.p.hp,
});
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"You were healed to full health! The hospital billed you for ",
Money_1.Money(cost)));
}
render() {
const cost = this.getCost();
return (React.createElement(AutoupdatingStdButton_1.AutoupdatingStdButton, { onClick: this.getHealed, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Get treatment for wounds - ",
Money_1.Money(cost)) }));
}
}
exports.HospitalLocation = HospitalLocation;
/***/ }),
/* 903 */
/*!******************************************!*\
!*** ./src/Locations/ui/GymLocation.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GymLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a gym
*
* This subcomponent renders all of the buttons for training at the gym
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const ServerHelpers_1 = __webpack_require__(/*! ../../Server/ServerHelpers */ 22);
const SpecialServerIps_1 = __webpack_require__(/*! ../../Server/SpecialServerIps */ 38);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
class GymLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
this.trainStrength = this.trainStrength.bind(this);
this.trainDefense = this.trainDefense.bind(this);
this.trainDexterity = this.trainDexterity.bind(this);
this.trainAgility = this.trainAgility.bind(this);
this.calculateCost = this.calculateCost.bind(this);
}
calculateCost() {
const ip = SpecialServerIps_1.SpecialServerIps.getIp(this.props.loc.name);
const server = ServerHelpers_1.getServer(ip);
if (server == null || !server.hasOwnProperty('backdoorInstalled'))
return this.props.loc.costMult;
const discount = server.backdoorInstalled ? 0.9 : 1;
return this.props.loc.costMult * discount;
}
train(stat) {
const loc = this.props.loc;
this.props.p.startClass(this.calculateCost(), loc.expMult, stat);
}
trainStrength() {
this.train(Constants_1.CONSTANTS.ClassGymStrength);
}
trainDefense() {
this.train(Constants_1.CONSTANTS.ClassGymDefense);
}
trainDexterity() {
this.train(Constants_1.CONSTANTS.ClassGymDexterity);
}
trainAgility() {
this.train(Constants_1.CONSTANTS.ClassGymAgility);
}
render() {
const cost = Constants_1.CONSTANTS.ClassGymBaseCost * this.calculateCost();
return (React.createElement("div", null,
React.createElement(StdButton_1.StdButton, { onClick: this.trainStrength, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Train Strength (",
Money_1.Money(cost),
" / sec)") }),
React.createElement(StdButton_1.StdButton, { onClick: this.trainDefense, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Train Defense (",
Money_1.Money(cost),
" / sec)") }),
React.createElement(StdButton_1.StdButton, { onClick: this.trainDexterity, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Train Dexterity (",
Money_1.Money(cost),
" / sec)") }),
React.createElement(StdButton_1.StdButton, { onClick: this.trainAgility, style: this.btnStyle, text: React.createElement(React.Fragment, null,
"Train Agility (",
Money_1.Money(cost),
" / sec)") })));
}
}
exports.GymLocation = GymLocation;
/***/ }),
/* 904 */
/*!***********************************************!*\
!*** ./src/Locations/ui/ApplyToJobButton.tsx ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplyToJobButton = void 0;
/**
* React Component for a button that's used to apply for a job
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const GetJobRequirementText_1 = __webpack_require__(/*! ../../Company/GetJobRequirementText */ 442);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
class ApplyToJobButton extends React.Component {
constructor(props) {
super(props);
this.getJobRequirementTooltip = this.getJobRequirementTooltip.bind(this);
}
getJobRequirementTooltip() {
const pos = this.props.p.getNextCompanyPosition(this.props.company, this.props.entryPosType);
if (pos == null) {
return "";
}
if (!this.props.company.hasPosition(pos)) {
return "";
}
return GetJobRequirementText_1.getJobRequirementText(this.props.company, pos, true);
}
render() {
return (React.createElement(StdButton_1.StdButton, { onClick: this.props.onClick, style: this.props.style, text: this.props.text, tooltip: this.getJobRequirementTooltip() }));
}
}
exports.ApplyToJobButton = ApplyToJobButton;
/***/ }),
/* 905 */
/*!**********************************************!*\
!*** ./src/Locations/ui/CompanyLocation.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompanyLocation = void 0;
/**
* React Subcomponent for displaying a location's UI, when that location is a company
*
* This subcomponent renders all of the buttons for applying to jobs at a company
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const ApplyToJobButton_1 = __webpack_require__(/*! ./ApplyToJobButton */ 904);
const Locations_1 = __webpack_require__(/*! ../Locations */ 408);
const Companies_1 = __webpack_require__(/*! ../../Company/Companies */ 33);
const CompanyPosition_1 = __webpack_require__(/*! ../../Company/CompanyPosition */ 286);
const CompanyPositions_1 = __webpack_require__(/*! ../../Company/CompanyPositions */ 52);
const posNames = __importStar(__webpack_require__(/*! ../../Company/data/companypositionnames */ 58));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Reputation_1 = __webpack_require__(/*! ../../ui/React/Reputation */ 59);
const Favor_1 = __webpack_require__(/*! ../../ui/React/Favor */ 685);
const YesNoBox_1 = __webpack_require__(/*! ../../../utils/YesNoBox */ 61);
const blockStyleMarkup = {
display: "block",
};
class CompanyLocation extends React.Component {
constructor(props) {
super(props);
/**
* CompanyPosition object for the job that the player holds at this company
* (if he has one)
*/
this.companyPosition = null;
/**
* Name of company position that player holds, if applicable
*/
this.jobTitle = null;
this.btnStyle = { display: "block" };
this.quit = this.quit.bind(this);
this.applyForAgentJob = this.applyForAgentJob.bind(this);
this.applyForBusinessConsultantJob = this.applyForBusinessConsultantJob.bind(this);
this.applyForBusinessJob = this.applyForBusinessJob.bind(this);
this.applyForEmployeeJob = this.applyForEmployeeJob.bind(this);
this.applyForItJob = this.applyForItJob.bind(this);
this.applyForPartTimeEmployeeJob = this.applyForPartTimeEmployeeJob.bind(this);
this.applyForPartTimeWaiterJob = this.applyForPartTimeWaiterJob.bind(this);
this.applyForSecurityJob = this.applyForSecurityJob.bind(this);
this.applyForSoftwareConsultantJob = this.applyForSoftwareConsultantJob.bind(this);
this.applyForSoftwareJob = this.applyForSoftwareJob.bind(this);
this.applyForWaiterJob = this.applyForWaiterJob.bind(this);
this.startInfiltration = this.startInfiltration.bind(this);
this.work = this.work.bind(this);
this.location = Locations_1.Locations[props.locName];
if (this.location == null) {
throw new Error(`CompanyLocation component constructed with invalid location: ${props.locName}`);
}
this.company = Companies_1.Companies[props.locName];
if (this.company == null) {
throw new Error(`CompanyLocation component constructed with invalid company: ${props.locName}`);
}
this.state = {
employedHere: false,
};
this.props.p.location = props.locName;
this.checkIfEmployedHere(false);
}
applyForAgentJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForAgentJob();
this.checkIfEmployedHere(true);
}
applyForBusinessConsultantJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForBusinessConsultantJob();
this.checkIfEmployedHere(true);
}
applyForBusinessJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForBusinessJob();
this.checkIfEmployedHere(true);
}
applyForEmployeeJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForEmployeeJob();
this.checkIfEmployedHere(true);
}
applyForItJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForItJob();
this.checkIfEmployedHere(true);
}
applyForPartTimeEmployeeJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForPartTimeEmployeeJob();
this.checkIfEmployedHere(true);
}
applyForPartTimeWaiterJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForPartTimeWaiterJob();
this.checkIfEmployedHere(true);
}
applyForSecurityJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForSecurityJob();
this.checkIfEmployedHere(true);
}
applyForSoftwareConsultantJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForSoftwareConsultantJob();
this.checkIfEmployedHere(true);
}
applyForSoftwareJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForSoftwareJob();
this.checkIfEmployedHere(true);
}
applyForWaiterJob(e) {
if (!e.isTrusted) {
return;
}
this.props.p.applyForWaiterJob();
this.checkIfEmployedHere(true);
}
checkIfEmployedHere(updateState = false) {
this.jobTitle = this.props.p.jobs[this.props.locName];
if (this.jobTitle != null) {
this.companyPosition = CompanyPositions_1.CompanyPositions[this.jobTitle];
}
if (updateState) {
this.setState({
employedHere: this.jobTitle != null,
});
}
}
startInfiltration(e) {
if (!e.isTrusted) {
return;
}
const loc = this.location;
if (!loc.infiltrationData) {
console.error(`trying to start infiltration at ${this.props.locName} but the infiltrationData is null`);
return;
}
this.props.engine.loadInfiltrationContent(this.props.locName, loc.infiltrationData.startingSecurityLevel, loc.infiltrationData.maxClearanceLevel);
const data = loc.infiltrationData;
if (data == null) {
return;
}
}
work(e) {
if (!e.isTrusted) {
return;
}
const pos = this.companyPosition;
if (pos instanceof CompanyPosition_1.CompanyPosition) {
if (pos.isPartTimeJob() || pos.isSoftwareConsultantJob() || pos.isBusinessConsultantJob()) {
this.props.p.startWorkPartTime(this.props.locName);
}
else {
this.props.p.startWork(this.props.locName);
}
}
}
quit(e) {
if (!e.isTrusted) {
return;
}
const yesBtn = YesNoBox_1.yesNoBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoBoxGetNoButton();
if (yesBtn == null || noBtn == null) {
return;
}
yesBtn.innerHTML = "Quit job";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", () => {
this.props.p.quitJob(this.props.locName);
this.checkIfEmployedHere(true);
YesNoBox_1.yesNoBoxClose();
});
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoBoxClose();
});
YesNoBox_1.yesNoBoxCreate(React.createElement(React.Fragment, null,
"Would you like to quit your job at ",
this.company.name,
"?"));
}
render() {
const isEmployedHere = this.jobTitle != null;
const favorGain = this.company.getFavorGain();
return (React.createElement("div", null,
isEmployedHere &&
React.createElement("div", null,
React.createElement("p", null,
"Job Title: ",
this.jobTitle),
React.createElement("br", null),
React.createElement("p", { style: blockStyleMarkup }, "-------------------------"),
React.createElement("br", null),
React.createElement("p", { className: "tooltip" },
"Company reputation: ",
Reputation_1.Reputation(this.company.playerReputation),
React.createElement("span", { className: "tooltiptext" },
"You will earn ",
Favor_1.Favor(favorGain[0]),
" company favor upon resetting after installing Augmentations")),
React.createElement("br", null),
React.createElement("br", null),
React.createElement("p", { style: blockStyleMarkup }, "-------------------------"),
React.createElement("br", null),
React.createElement("p", { className: "tooltip" },
"Company Favor: ",
Favor_1.Favor(this.company.favor),
React.createElement("span", { className: "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 Augmentations. The amount of favor you gain depends on how much reputation you have with the comapny.")),
React.createElement("br", null),
React.createElement("br", null),
React.createElement("p", { style: blockStyleMarkup }, "-------------------------"),
React.createElement("br", null),
React.createElement(StdButton_1.StdButton, { onClick: this.work, text: "Work" }),
"\u00A0\u00A0\u00A0\u00A0",
React.createElement(StdButton_1.StdButton, { onClick: this.quit, text: "Quit" })),
this.company.hasAgentPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.AgentCompanyPositions[0]], onClick: this.applyForAgentJob, p: this.props.p, style: this.btnStyle, text: "Apply for Agent Job" }),
this.company.hasBusinessConsultantPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.BusinessConsultantCompanyPositions[0]], onClick: this.applyForBusinessConsultantJob, p: this.props.p, style: this.btnStyle, text: "Apply for Business Consultant Job" }),
this.company.hasBusinessPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.BusinessCompanyPositions[0]], onClick: this.applyForBusinessJob, p: this.props.p, style: this.btnStyle, text: "Apply for Business Job" }),
this.company.hasEmployeePositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.MiscCompanyPositions[1]], onClick: this.applyForEmployeeJob, p: this.props.p, style: this.btnStyle, text: "Apply to be an Employee" }),
this.company.hasEmployeePositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.PartTimeCompanyPositions[1]], onClick: this.applyForPartTimeEmployeeJob, p: this.props.p, style: this.btnStyle, text: "Apply to be a part-time Employee" }),
this.company.hasITPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.ITCompanyPositions[0]], onClick: this.applyForItJob, p: this.props.p, style: this.btnStyle, text: "Apply for IT Job" }),
this.company.hasSecurityPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.SecurityCompanyPositions[2]], onClick: this.applyForSecurityJob, p: this.props.p, style: this.btnStyle, text: "Apply for Security Job" }),
this.company.hasSoftwareConsultantPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.SoftwareConsultantCompanyPositions[0]], onClick: this.applyForSoftwareConsultantJob, p: this.props.p, style: this.btnStyle, text: "Apply for Software Consultant Job" }),
this.company.hasSoftwarePositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.SoftwareCompanyPositions[0]], onClick: this.applyForSoftwareJob, p: this.props.p, style: this.btnStyle, text: "Apply for Software Job" }),
this.company.hasWaiterPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.MiscCompanyPositions[0]], onClick: this.applyForWaiterJob, p: this.props.p, style: this.btnStyle, text: "Apply to be a Waiter" }),
this.company.hasWaiterPositions() &&
React.createElement(ApplyToJobButton_1.ApplyToJobButton, { company: this.company, entryPosType: CompanyPositions_1.CompanyPositions[posNames.PartTimeCompanyPositions[0]], onClick: this.applyForPartTimeWaiterJob, p: this.props.p, style: this.btnStyle, text: "Apply to be a part-time Waiter" }),
(this.location.infiltrationData != null) &&
React.createElement(StdButton_1.StdButton, { onClick: this.startInfiltration, style: this.btnStyle, text: "Infiltrate Company" })));
}
}
exports.CompanyLocation = CompanyLocation;
/***/ }),
/* 906 */
/*!**********************************************!*\
!*** ./src/Locations/ui/GenericLocation.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenericLocation = void 0;
/**
* React Component for displaying a location's UI
*
* This is a "router" component of sorts, meaning it deduces the type of
* location that is being rendered and then creates the proper component(s) for that.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const CompanyLocation_1 = __webpack_require__(/*! ./CompanyLocation */ 905);
const GymLocation_1 = __webpack_require__(/*! ./GymLocation */ 903);
const HospitalLocation_1 = __webpack_require__(/*! ./HospitalLocation */ 902);
const SlumsLocation_1 = __webpack_require__(/*! ./SlumsLocation */ 901);
const SpecialLocation_1 = __webpack_require__(/*! ./SpecialLocation */ 900);
const TechVendorLocation_1 = __webpack_require__(/*! ./TechVendorLocation */ 899);
const TravelAgencyLocation_1 = __webpack_require__(/*! ./TravelAgencyLocation */ 898);
const UniversityLocation_1 = __webpack_require__(/*! ./UniversityLocation */ 897);
const CasinoLocation_1 = __webpack_require__(/*! ./CasinoLocation */ 896);
const LocationTypeEnum_1 = __webpack_require__(/*! ../LocationTypeEnum */ 477);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const SpecialServerIps_1 = __webpack_require__(/*! ../../Server/SpecialServerIps */ 38);
const ServerHelpers_1 = __webpack_require__(/*! ../../Server/ServerHelpers */ 22);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const CorruptableText_1 = __webpack_require__(/*! ../../ui/React/CorruptableText */ 883);
class GenericLocation extends React.Component {
constructor(props) {
super(props);
this.btnStyle = { display: "block" };
}
/**
* Determine what needs to be rendered for this location based on the locations
* type. Returns an array of React components that should be rendered
*/
getLocationSpecificContent() {
const content = [];
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Company)) {
content.push(React.createElement(CompanyLocation_1.CompanyLocation, { engine: this.props.engine, key: "companylocation", locName: this.props.loc.name, p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Gym)) {
content.push(React.createElement(GymLocation_1.GymLocation, { key: "gymlocation", loc: this.props.loc, p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Hospital)) {
content.push(React.createElement(HospitalLocation_1.HospitalLocation, { key: "hospitallocation", p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Slums)) {
content.push(React.createElement(SlumsLocation_1.SlumsLocation, { key: "slumslocation", p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Special)) {
content.push(React.createElement(SpecialLocation_1.SpecialLocation, { engine: this.props.engine, key: "speciallocation", loc: this.props.loc, p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.TechVendor)) {
content.push(React.createElement(TechVendorLocation_1.TechVendorLocation, { key: "techvendorlocation", loc: this.props.loc, p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.TravelAgency)) {
content.push(React.createElement(TravelAgencyLocation_1.TravelAgencyLocation, { key: "travelagencylocation", p: this.props.p, travel: this.props.travel }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.University)) {
content.push(React.createElement(UniversityLocation_1.UniversityLocation, { key: "universitylocation", loc: this.props.loc, p: this.props.p }));
}
if (this.props.loc.types.includes(LocationTypeEnum_1.LocationType.Casino)) {
content.push(React.createElement(CasinoLocation_1.CasinoLocation, { key: "casinoLocation", p: this.props.p }));
}
return content;
}
render() {
const locContent = this.getLocationSpecificContent();
const ip = SpecialServerIps_1.SpecialServerIps.getIp(this.props.loc.name);
const server = ServerHelpers_1.getServer(ip);
const backdoorInstalled = server !== null && ServerHelpers_1.isBackdoorInstalled(server);
return (React.createElement("div", null,
React.createElement(StdButton_1.StdButton, { onClick: this.props.returnToCity, style: this.btnStyle, text: "Return to World" }),
React.createElement("h1", { className: "noselect" }, backdoorInstalled && !Settings_1.Settings.DisableTextEffects
? React.createElement(CorruptableText_1.CorruptableText, { content: this.props.loc.name })
: this.props.loc.name),
locContent));
}
}
exports.GenericLocation = GenericLocation;
/***/ }),
/* 907 */
/*!***********************************!*\
!*** ./src/Locations/ui/City.tsx ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocationCity = void 0;
/**
* React Component for displaying a City's UI.
* This UI shows all of the available locations in the city, and lets the player
* visit those locations
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
class LocationCity extends React.Component {
asciiCity() {
const LocationLetter = (location) => {
if (location)
return React.createElement("span", { key: location, className: "tooltip", style: { color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px', cursor: 'pointer' }, onClick: this.props.enterLocation.bind(this, location) }, "X");
return React.createElement("span", null, "*");
};
const locationLettersRegex = /[A-Z]/g;
const letterMap = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6,
'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14,
'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22,
'X': 23, 'Y': 24, 'Z': 25 };
const lineElems = (s) => {
const elems = [];
const matches = [];
let match;
while ((match = locationLettersRegex.exec(s)) !== null) {
matches.push(match);
}
if (matches.length === 0) {
elems.push(s);
return elems;
}
for (let i = 0; i < matches.length; i++) {
const startI = i === 0 ? 0 : matches[i - 1].index + 1;
const endI = matches[i].index;
elems.push(s.slice(startI, endI));
const locationI = letterMap[s[matches[i].index]];
elems.push(LocationLetter(this.props.city.locations[locationI]));
}
elems.push(s.slice(matches[matches.length - 1].index + 1));
return elems;
};
const elems = [];
const lines = this.props.city.asciiArt.split('\n');
for (const i in lines) {
elems.push(React.createElement("pre", { key: i }, lineElems(lines[i])));
}
return React.createElement("div", { className: "noselect" }, elems);
}
listCity() {
const locationButtons = this.props.city.locations.map((locName) => {
return (React.createElement("li", { key: locName },
React.createElement(StdButton_1.StdButton, { onClick: this.props.enterLocation.bind(this, locName), text: locName })));
});
return (React.createElement("ul", null, locationButtons));
}
render() {
return (React.createElement(React.Fragment, null, Settings_1.Settings.DisableASCIIArt ? this.listCity() : this.asciiCity()));
}
}
exports.LocationCity = LocationCity;
/***/ }),
/* 908 */
/*!*****************************************!*\
!*** ./src/Infiltration/ui/Victory.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Victory = void 0;
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const Reputation_1 = __webpack_require__(/*! ../../ui/React/Reputation */ 59);
const BitNodeMultipliers_1 = __webpack_require__(/*! ../../BitNode/BitNodeMultipliers */ 19);
function Victory(props) {
const [faction, setFaction] = react_1.useState('none');
function quitInfiltration() {
const menu = document.getElementById("mainmenu-container");
if (!menu)
throw new Error('mainmenu-container somehow null');
menu.style.visibility = "visible";
props.Engine.loadLocationContent();
}
const levelBonus = props.MaxLevel * Math.pow(1.01, props.MaxLevel);
const repGain = Math.pow(props.Difficulty + 1, 1.1) *
Math.pow(props.StartingDifficulty, 1.2) *
30 * levelBonus * BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationRep;
const moneyGain = Math.pow(props.Difficulty + 1, 2) *
Math.pow(props.StartingDifficulty, 3) *
3e3 * levelBonus * BitNodeMultipliers_1.BitNodeMultipliers.InfiltrationMoney;
function sell() {
props.Player.gainMoney(moneyGain);
props.Player.recordMoneySource(moneyGain, 'infiltration');
quitInfiltration();
}
function trade() {
if (faction === 'none')
return;
Factions_1.Factions[faction].playerReputation += repGain;
quitInfiltration();
}
function changeDropdown(event) {
setFaction(event.target.value);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("h1", null, "Infiltration successful!")),
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("h2", null, "You can trade the confidential information you found for money or reputation."),
react_1.default.createElement("select", { className: "dropdown", onChange: changeDropdown },
react_1.default.createElement("option", { key: 'none', value: 'none' }, 'none'),
props.Player.factions.filter(f => Factions_1.Factions[f].getInfo().offersWork()).map(f => react_1.default.createElement("option", { key: f, value: f }, f))),
react_1.default.createElement(StdButton_1.StdButton, { onClick: trade, text: react_1.default.createElement(react_1.default.Fragment, null,
"Trade for ",
Reputation_1.Reputation(repGain),
" reputation") })),
react_1.default.createElement(Grid_1.default, { item: true, xs: 3 },
react_1.default.createElement(StdButton_1.StdButton, { onClick: sell, text: react_1.default.createElement(react_1.default.Fragment, null,
"Sell for ",
Money_1.Money(moneyGain)) })),
react_1.default.createElement(Grid_1.default, { item: true, xs: 3 },
react_1.default.createElement(StdButton_1.StdButton, { onClick: quitInfiltration, text: "Quit" })))));
}
exports.Victory = Victory;
/***/ }),
/* 909 */
/*!*************************************************!*\
!*** ./src/Infiltration/ui/WireCuttingGame.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WireCuttingGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const difficulties = {
Trivial: { timer: 9000, wiresmin: 4, wiresmax: 4, rules: 2 },
Normal: { timer: 7000, wiresmin: 6, wiresmax: 6, rules: 2 },
Hard: { timer: 5000, wiresmin: 8, wiresmax: 8, rules: 3 },
Impossible: { timer: 4000, wiresmin: 9, wiresmax: 9, rules: 4 },
};
const types = [
"|",
".",
"/",
"-",
"█",
"#",
];
const colors = [
"red",
"#FFC107",
"blue",
"white",
];
const colorNames = {
"red": "red",
"#FFC107": "yellow",
"blue": "blue",
"white": "white",
};
function WireCuttingGame(props) {
const difficulty = { timer: 0, wiresmin: 0, wiresmax: 0, rules: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [wires] = react_1.useState(generateWires(difficulty));
const [cutWires, setCutWires] = react_1.useState((new Array(wires.length)).fill(false));
const [questions] = react_1.useState(generateQuestion(wires, difficulty));
function press(event) {
event.preventDefault();
const wireNum = parseInt(event.key);
if (wireNum < 1 || wireNum > wires.length || isNaN(wireNum))
return;
setCutWires(old => {
const next = [...old];
next[wireNum - 1] = true;
if (!questions.some((q => q.shouldCut(wires[wireNum - 1], wireNum - 1)))) {
props.onFailure();
}
// check if we won
const wiresToBeCut = [];
for (let j = 0; j < wires.length; j++) {
let shouldBeCut = false;
for (let i = 0; i < questions.length; i++) {
shouldBeCut = shouldBeCut || questions[i].shouldCut(wires[j], j);
}
wiresToBeCut.push(shouldBeCut);
}
if (wiresToBeCut.every((b, i) => b === next[i])) {
props.onSuccess();
}
return next;
});
}
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Cut the wires with the following properties! (keyboard 1 to 9)"),
questions.map((question, i) => react_1.default.createElement("h3", { key: i }, question.toString())),
react_1.default.createElement("pre", null, (new Array(wires.length)).fill(0).map((_, i) => react_1.default.createElement("span", { key: i },
"\u00A0",
i + 1,
"\u00A0\u00A0\u00A0\u00A0"))),
(new Array(8)).fill(0).map((_, i) => react_1.default.createElement("div", { key: i },
react_1.default.createElement("pre", null, wires.map((wire, j) => {
if ((i === 3 || i === 4) && cutWires[j])
return react_1.default.createElement("span", { key: j }, "\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0");
return react_1.default.createElement("span", { key: j, style: { color: wire.colors[i % wire.colors.length] } },
"|",
wire.tpe,
"|\u00A0\u00A0\u00A0");
})))),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.WireCuttingGame = WireCuttingGame;
function randomPositionQuestion(wires) {
const index = Math.floor(Math.random() * wires.length);
return {
toString: () => {
return `Cut wires number ${index + 1}.`;
},
shouldCut: (wire, i) => {
return index === i;
},
};
}
function randomColorQuestion(wires) {
const index = Math.floor(Math.random() * wires.length);
const cutColor = wires[index].colors[0];
return {
toString: () => {
return `Cut all wires colored ${colorNames[cutColor]}.`;
},
shouldCut: (wire) => {
return wire.colors.includes(cutColor);
},
};
}
function generateQuestion(wires, difficulty) {
const numQuestions = difficulty.rules;
const questionGenerators = [
randomPositionQuestion,
randomColorQuestion,
];
const questions = [];
for (let i = 0; i < numQuestions; i++) {
questions.push(questionGenerators[i % 2](wires));
}
return questions;
}
function generateWires(difficulty) {
const wires = [];
const numWires = utils_1.random(difficulty.wiresmin, difficulty.wiresmax);
for (let i = 0; i < numWires; i++) {
const wireColors = [colors[Math.floor(Math.random() * colors.length)]];
if (Math.random() < 0.15) {
wireColors.push(colors[Math.floor(Math.random() * colors.length)]);
}
wires.push({
tpe: types[Math.floor(Math.random() * types.length)],
colors: wireColors,
});
}
return wires;
}
/***/ }),
/* 910 */
/*!*************************************************!*\
!*** ./src/Infiltration/ui/MinesweeperGame.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MinesweeperGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const difficulties = {
Trivial: { timer: 15000, width: 3, height: 3, mines: 4 },
Normal: { timer: 15000, width: 4, height: 4, mines: 7 },
Hard: { timer: 15000, width: 5, height: 5, mines: 11 },
Impossible: { timer: 15000, width: 6, height: 6, mines: 15 },
};
function MinesweeperGame(props) {
const difficulty = { timer: 0, width: 0, height: 0, mines: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [minefield] = react_1.useState(generateMinefield(difficulty));
const [answer, setAnswer] = react_1.useState(generateEmptyField(difficulty));
const [pos, setPos] = react_1.useState([0, 0]);
const [memoryPhase, setMemoryPhase] = react_1.useState(true);
function press(event) {
event.preventDefault();
if (memoryPhase)
return;
const move = [0, 0];
const arrow = utils_1.getArrow(event);
switch (arrow) {
case "↑":
move[1]--;
break;
case "←":
move[0]--;
break;
case "↓":
move[1]++;
break;
case "→":
move[0]++;
break;
}
const next = [pos[0] + move[0], pos[1] + move[1]];
next[0] = (next[0] + minefield[0].length) % minefield[0].length;
next[1] = (next[1] + minefield.length) % minefield.length;
setPos(next);
if (event.keyCode == 32) {
if (!minefield[pos[1]][pos[0]]) {
props.onFailure();
return;
}
setAnswer(old => {
old[pos[1]][pos[0]] = true;
if (fieldEquals(minefield, old))
props.onSuccess();
return old;
});
}
}
react_1.useEffect(() => {
const id = setTimeout(() => setMemoryPhase(false), 2000);
return () => clearInterval(id);
}, []);
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, memoryPhase ? "Remember all the mines!" : "Mark all the mines!"),
minefield.map((line, y) => react_1.default.createElement("div", { key: y },
react_1.default.createElement("pre", null, line.map((cell, x) => {
if (memoryPhase) {
if (minefield[y][x])
return react_1.default.createElement("span", { key: x }, "[?]\u00A0");
return react_1.default.createElement("span", { key: x }, "[\u00A0]\u00A0");
}
else {
if (x == pos[0] && y == pos[1])
return react_1.default.createElement("span", { key: x }, "[X]\u00A0");
if (answer[y][x])
return react_1.default.createElement("span", { key: x }, "[.]\u00A0");
return react_1.default.createElement("span", { key: x }, "[\u00A0]\u00A0");
}
})),
react_1.default.createElement("br", null))),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.MinesweeperGame = MinesweeperGame;
function fieldEquals(a, b) {
function count(field) {
return field.flat().reduce((a, b) => a + (b ? 1 : 0), 0);
}
return count(a) === count(b);
}
function generateEmptyField(difficulty) {
const field = [];
for (let i = 0; i < difficulty.height; i++) {
field.push((new Array(Math.round(difficulty.width))).fill(false));
}
return field;
}
function generateMinefield(difficulty) {
const field = generateEmptyField(difficulty);
for (let i = 0; i < difficulty.mines; i++) {
const x = Math.floor(Math.random() * field.length);
const y = Math.floor(Math.random() * field[0].length);
if (field[x][y]) {
i--;
continue;
}
field[x][y] = true;
}
return field;
}
/***/ }),
/* 911 */
/*!***************************************************!*\
!*** ./src/Infiltration/ui/Cyberpunk2077Game.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cyberpunk2077Game = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const difficulties = {
Trivial: { timer: 12500, width: 3, height: 3, symbols: 6 },
Normal: { timer: 15000, width: 4, height: 4, symbols: 7 },
Hard: { timer: 12500, width: 5, height: 5, symbols: 8 },
Impossible: { timer: 10000, width: 6, height: 6, symbols: 9 },
};
function Cyberpunk2077Game(props) {
const difficulty = { timer: 0, width: 0, height: 0, symbols: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [grid] = react_1.useState(generatePuzzle(difficulty));
const [answer] = react_1.useState(generateAnswer(grid, difficulty));
const [index, setIndex] = react_1.useState(0);
const [pos, setPos] = react_1.useState([0, 0]);
function press(event) {
event.preventDefault();
const move = [0, 0];
const arrow = utils_1.getArrow(event);
switch (arrow) {
case "↑":
move[1]--;
break;
case "←":
move[0]--;
break;
case "↓":
move[1]++;
break;
case "→":
move[0]++;
break;
}
const next = [pos[0] + move[0], pos[1] + move[1]];
next[0] = (next[0] + grid[0].length) % grid[0].length;
next[1] = (next[1] + grid.length) % grid.length;
setPos(next);
if (event.keyCode == 32) {
const selected = grid[pos[1]][pos[0]];
const expected = answer[index];
if (selected !== expected) {
props.onFailure();
return;
}
setIndex(index + 1);
if (answer.length === index + 1)
props.onSuccess();
}
}
const fontSize = "2em";
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Match the symbols!"),
react_1.default.createElement("h2", { style: { fontSize: fontSize } },
"Targets: ",
answer.map((a, i) => {
if (i == index)
return react_1.default.createElement("span", { key: `${i}`, style: { fontSize: "1em", color: 'blue' } },
a,
"\u00A0");
return react_1.default.createElement("span", { key: `${i}`, style: { fontSize: "1em" } },
a,
"\u00A0");
})),
react_1.default.createElement("br", null),
grid.map((line, y) => react_1.default.createElement("div", { key: y },
react_1.default.createElement("pre", null, line.map((cell, x) => {
if (x == pos[0] && y == pos[1])
return react_1.default.createElement("span", { key: `${x}${y}`, style: { fontSize: fontSize, color: 'blue' } },
cell,
"\u00A0");
return react_1.default.createElement("span", { key: `${x}${y}`, style: { fontSize: fontSize } },
cell,
"\u00A0");
})),
react_1.default.createElement("br", null))),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.Cyberpunk2077Game = Cyberpunk2077Game;
function generateAnswer(grid, difficulty) {
const answer = [];
for (let i = 0; i < Math.round(difficulty.symbols); i++) {
answer.push(grid[Math.floor(Math.random() * grid.length)][Math.floor(Math.random() * grid[0].length)]);
}
return answer;
}
function randChar() {
return "ABCDEF0123456789"[Math.floor(Math.random() * 16)];
}
function generatePuzzle(difficulty) {
const puzzle = [];
for (let i = 0; i < Math.round(difficulty.height); i++) {
const line = [];
for (let j = 0; j < Math.round(difficulty.width); j++) {
line.push(randChar() + randChar());
}
puzzle.push(line);
}
return puzzle;
}
/***/ }),
/* 912 */
/*!***********************************************!*\
!*** ./src/Infiltration/ui/CheatCodeGame.tsx ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CheatCodeGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const difficulties = {
Trivial: { timer: 13000, min: 6, max: 8 },
Normal: { timer: 7000, min: 7, max: 8 },
Hard: { timer: 5000, min: 8, max: 9 },
Impossible: { timer: 3000, min: 9, max: 9 },
};
function CheatCodeGame(props) {
const difficulty = { timer: 0, min: 0, max: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [code] = react_1.useState(generateCode(difficulty));
const [index, setIndex] = react_1.useState(0);
function press(event) {
event.preventDefault();
if (code[index] !== utils_1.getArrow(event)) {
props.onFailure();
return;
}
setIndex(index + 1);
if (index + 1 >= code.length)
props.onSuccess();
}
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Enter the Code!"),
react_1.default.createElement("p", { style: { fontSize: '5em' } }, code[index]),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.CheatCodeGame = CheatCodeGame;
function generateCode(difficulty) {
const arrows = ['←', '→', '↑', '↓'];
let code = '';
for (let i = 0; i < utils_1.random(difficulty.min, difficulty.max); i++) {
let arrow = arrows[Math.floor(4 * Math.random())];
while (arrow === code[code.length - 1])
arrow = arrows[Math.floor(4 * Math.random())];
code += arrow;
}
return code;
}
/***/ }),
/* 913 */
/*!*******************************************!*\
!*** ./src/Infiltration/ui/BribeGame.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BribeGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const difficulties = {
Trivial: { timer: 12000, size: 6 },
Normal: { timer: 9000, size: 8 },
Hard: { timer: 5000, size: 9 },
Impossible: { timer: 2500, size: 12 },
};
function BribeGame(props) {
const difficulty = { timer: 0, size: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [choices] = react_1.useState(makeChoices(difficulty));
const [index, setIndex] = react_1.useState(0);
function press(event) {
event.preventDefault();
const k = event.keyCode;
if (k === 32) {
if (positive.includes(choices[index]))
props.onSuccess();
else
props.onFailure();
return;
}
let newIndex = index;
if ([38, 87, 68, 39].includes(k))
newIndex++;
if ([65, 37, 83, 40].includes(k))
newIndex--;
while (newIndex < 0)
newIndex += choices.length;
while (newIndex > choices.length - 1)
newIndex -= choices.length;
setIndex(newIndex);
}
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", null, "Say something nice about the guard."),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure })),
react_1.default.createElement(Grid_1.default, { item: true, xs: 6 },
react_1.default.createElement("h2", { style: { fontSize: "2em" } }, "\u2191"),
react_1.default.createElement("h2", { style: { fontSize: "2em" } }, choices[index]),
react_1.default.createElement("h2", { style: { fontSize: "2em" } }, "\u2193"))));
}
exports.BribeGame = BribeGame;
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
function makeChoices(difficulty) {
const choices = [];
choices.push(positive[Math.floor(Math.random() * positive.length)]);
for (let i = 0; i < difficulty.size; i++) {
const option = negative[Math.floor(Math.random() * negative.length)];
if (choices.includes(option)) {
i--;
continue;
}
choices.push(option);
}
shuffleArray(choices);
return choices;
}
const positive = ["affectionate", "agreeable", "bright", "charming", "creative",
"determined", "energetic", "friendly", "funny", "generous", "polite", "likable",
"diplomatic", "helpful", "giving", "kind", "hardworking", "patient", "dynamic",
"loyal"];
const negative = ["aggressive", "aloof", "arrogant", "big-headed", "boastful",
"boring", "bossy", "careless", "clingy", "couch potato", "cruel", "cynical",
"grumpy", "hot air", "know it all", "obnoxious", "pain in the neck", "picky",
"tactless", "thoughtless"];
/***/ }),
/* 914 */
/*!**********************************************!*\
!*** ./src/Infiltration/ui/BackwardGame.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BackwardGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const BlinkingCursor_1 = __webpack_require__(/*! ./BlinkingCursor */ 632);
const difficulties = {
Trivial: { timer: 16000, min: 3, max: 4 },
Normal: { timer: 12500, min: 2, max: 3 },
Hard: { timer: 15000, min: 3, max: 4 },
Impossible: { timer: 8000, min: 4, max: 4 },
};
function BackwardGame(props) {
const difficulty = { timer: 0, min: 0, max: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [answer] = react_1.useState(makeAnswer(difficulty));
const [guess, setGuess] = react_1.useState("");
function press(event) {
event.preventDefault();
if (event.keyCode === 16)
return;
const nextGuess = guess + event.key.toUpperCase();
if (!answer.startsWith(nextGuess))
props.onFailure();
else if (answer === nextGuess)
props.onSuccess();
else
setGuess(nextGuess);
}
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Type it backward"),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure })),
react_1.default.createElement(Grid_1.default, { item: true, xs: 6 },
react_1.default.createElement("p", { style: { transform: 'scaleX(-1)' } }, answer)),
react_1.default.createElement(Grid_1.default, { item: true, xs: 6 },
react_1.default.createElement("p", null,
guess,
react_1.default.createElement(BlinkingCursor_1.BlinkingCursor, null)))));
}
exports.BackwardGame = BackwardGame;
function makeAnswer(difficulty) {
const length = utils_1.random(difficulty.min, difficulty.max);
let answer = "";
for (let i = 0; i < length; i++) {
if (i > 0)
answer += " ";
answer += words[Math.floor(Math.random() * words.length)];
}
return answer;
}
const words = ["ALGORITHM", "ANALOG", "APP", "APPLICATION", "ARRAY", "BACKUP",
"BANDWIDTH", "BINARY", "BIT", "BITE", "BITMAP", "BLOG", "BLOGGER",
"BOOKMARK", "BOOT", "BROADBAND", "BROWSER", "BUFFER", "BUG", "BUS", "BYTE",
"CACHE", "CAPS LOCK", "CAPTCHA", "CD", "CD-ROM", "CLIENT",
"CLIPBOARD", "CLOUD", "COMPUTING", "COMMAND", "COMPILE", "COMPRESS",
"COMPUTER", "CONFIGURE", "COOKIE", "COPY", "CPU",
"CYBERCRIME", "CYBERSPACE", "DASHBOARD", "DATA", "MINING", "DATABASE",
"DEBUG", "DECOMPRESS", "DELETE", "DESKTOP", "DEVELOPMENT", "DIGITAL",
"DISK", "DNS", "DOCUMENT", "DOMAIN", "DOMAIN NAME", "DOT", "DOT MATRIX",
"DOWNLOAD", "DRAG", "DVD", "DYNAMIC", "EMAIL", "EMOTICON", "ENCRYPT",
"ENCRYPTION", "ENTER", "EXABYTE", "FAQ", "FILE", "FINDER", "FIREWALL",
"FIRMWARE", "FLAMING", "FLASH", "FLASH DRIVE", "FLOPPY DISK", "FLOWCHART",
"FOLDER", "FONT", "FORMAT", "FRAME", "FREEWARE", "GIGABYTE", "GRAPHICS",
"HACK", "HACKER", "HARDWARE", "HOME PAGE", "HOST", "HTML", "HYPERLINK",
"HYPERTEXT", "ICON", "INBOX", "INTEGER", "INTERFACE", "INTERNET",
"IP ADDRESS", "ITERATION", "JAVA", "JOYSTICK", "JUNKMAIL", "KERNEL",
"KEY", "KEYBOARD", "KEYWORD", "LAPTOP", "LASER PRINTER", "LINK", "LINUX",
"LOG OUT", "LOGIC", "LOGIN", "LURKING", "MACINTOSH", "MACRO", "MAINFRAME",
"MALWARE", "MEDIA", "MEMORY", "MIRROR", "MODEM", "MONITOR", "MOTHERBOARD",
"MOUSE", "MULTIMEDIA", "NET", "NETWORK", "NODE", "NOTEBOOK", "COMPUTER",
"OFFLINE", "ONLINE", "OPENSOURCE", "OPERATING", "SYSTEM", "OPTION", "OUTPUT",
"PAGE", "PASSWORD", "PASTE", "PATH", "PHISHING", "PIRACY", "PIRATE",
"PLATFORM", "PLUGIN", "PODCAST", "POPUP", "PORTAL", "PRINT", "PRINTER",
"PRIVACY", "PROCESS", "PROGRAM", "PROGRAMMER", "PROTOCOL", "QUEUE",
"QWERTY", "RAM", "REALTIME", "REBOOT", "RESOLUTION", "RESTORE", "ROM",
"ROOT", "ROUTER", "RUNTIME", "SAVE", "SCAN", "SCANNER", "SCREEN",
"SCREENSHOT", "SCRIPT", "SCROLL", "SCROLL", "SEARCH", "ENGINE",
"SECURITY", "SERVER", "SHAREWARE", "SHELL", "SHIFT", "SHIFT KEY",
"SNAPSHOT", "SOCIAL NETWORKING", "SOFTWARE", "SPAM", "SPAMMER",
"SPREADSHEET", "SPYWARE", "STATUS", "STORAGE", "SUPERCOMPUTER", "SURF",
"SYNTAX", "TABLE", "TAG", "TERMINAL", "TEMPLATE", "TERABYTE", "TEXT EDITOR",
"THREAD", "TOOLBAR", "TRASH", "TROJAN HORSE", "TYPEFACE", "UNDO", "UNIX",
"UPLOAD", "URL", "USER", "USER INTERFACE", "USERNAME", "UTILITY", "VERSION",
"VIRTUAL", "VIRTUAL MEMORY", "VIRUS", "WEB", "WEBMASTER",
"WEBSITE", "WIDGET", "WIKI", "WINDOW", "WINDOWS", "WIRELESS",
"PROCESSOR", "WORKSTATION", "WEB", "WORM", "WWW", "XML",
"ZIP"];
/***/ }),
/* 915 */
/*!*******************************************!*\
!*** ./src/Infiltration/ui/SlashGame.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlashGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const difficulties = {
Trivial: { window: 600 },
Normal: { window: 325 },
Hard: { window: 250 },
Impossible: { window: 150 },
};
function SlashGame(props) {
const difficulty = { window: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const [guarding, setGuarding] = react_1.useState(true);
function press(event) {
event.preventDefault();
if (event.keyCode !== 32)
return;
if (guarding) {
props.onFailure();
}
else {
props.onSuccess();
}
}
react_1.useEffect(() => {
let id2 = -1;
const id = window.setTimeout(() => {
setGuarding(false);
id2 = window.setTimeout(() => setGuarding(true), difficulty.window);
}, Math.random() * 3250 + 1500);
return () => {
clearInterval(id);
if (id2 !== -1)
clearInterval(id2);
};
}, []);
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: 5000, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Slash when his guard is down!"),
react_1.default.createElement("p", { style: { fontSize: '5em' } }, guarding ? "!Guarding!" : "!ATTACKING!"),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.SlashGame = SlashGame;
/***/ }),
/* 916 */
/*!*********************************************!*\
!*** ./src/Infiltration/ui/BracketGame.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BracketGame = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const KeyHandler_1 = __webpack_require__(/*! ./KeyHandler */ 160);
const GameTimer_1 = __webpack_require__(/*! ./GameTimer */ 159);
const utils_1 = __webpack_require__(/*! ../utils */ 216);
const Difficulty_1 = __webpack_require__(/*! ./Difficulty */ 158);
const BlinkingCursor_1 = __webpack_require__(/*! ./BlinkingCursor */ 632);
const difficulties = {
Trivial: { timer: 8000, min: 2, max: 3 },
Normal: { timer: 6000, min: 4, max: 5 },
Hard: { timer: 4000, min: 4, max: 6 },
Impossible: { timer: 2500, min: 7, max: 7 },
};
function generateLeftSide(difficulty) {
let str = "";
const length = utils_1.random(difficulty.min, difficulty.max);
for (let i = 0; i < length; i++) {
str += ["[", '<', '(', '{'][Math.floor(Math.random() * 4)];
}
return str;
}
function getChar(event) {
if (event.keyCode == 48 && event.shiftKey)
return ")";
if (event.keyCode == 221 && !event.shiftKey)
return "]";
if (event.keyCode == 221 && event.shiftKey)
return "}";
if (event.keyCode == 190 && event.shiftKey)
return ">";
return "";
}
function match(left, right) {
return (left === '[' && right === ']') ||
(left === '<' && right === '>') ||
(left === '(' && right === ')') ||
(left === '{' && right === '}');
}
function BracketGame(props) {
const difficulty = { timer: 0, min: 0, max: 0 };
Difficulty_1.interpolate(difficulties, props.difficulty, difficulty);
const timer = difficulty.timer;
const [right, setRight] = react_1.useState("");
const [left] = react_1.useState(generateLeftSide(difficulty));
function press(event) {
event.preventDefault();
const char = getChar(event);
if (!char)
return;
if (!match(left[left.length - right.length - 1], char)) {
props.onFailure();
return;
}
if (left.length === right.length + 1) {
props.onSuccess();
return;
}
setRight(right + char);
}
return (react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(GameTimer_1.GameTimer, { millis: timer, onExpire: props.onFailure }),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", { className: "noselect" }, "Close the brackets"),
react_1.default.createElement("p", { style: { fontSize: '5em' } },
`${left}${right}`,
react_1.default.createElement(BlinkingCursor_1.BlinkingCursor, null)),
react_1.default.createElement(KeyHandler_1.KeyHandler, { onKeyDown: press, onFailure: props.onFailure }))));
}
exports.BracketGame = BracketGame;
/***/ }),
/* 917 */
/*!*******************************************!*\
!*** ./src/Infiltration/ui/Countdown.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Countdown = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
function Countdown(props) {
const [x, setX] = react_1.useState(3);
react_1.useEffect(() => {
if (x === 0) {
props.onFinish();
return;
}
setTimeout(() => setX(x - 1), 200);
});
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 },
react_1.default.createElement("h1", null, "Get Ready!"),
react_1.default.createElement("h1", null, x)))));
}
exports.Countdown = Countdown;
/***/ }),
/* 918 */
/*!**************************************!*\
!*** ./src/Infiltration/ui/Game.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Game = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
const Countdown_1 = __webpack_require__(/*! ./Countdown */ 917);
const BracketGame_1 = __webpack_require__(/*! ./BracketGame */ 916);
const SlashGame_1 = __webpack_require__(/*! ./SlashGame */ 915);
const BackwardGame_1 = __webpack_require__(/*! ./BackwardGame */ 914);
const BribeGame_1 = __webpack_require__(/*! ./BribeGame */ 913);
const CheatCodeGame_1 = __webpack_require__(/*! ./CheatCodeGame */ 912);
const Cyberpunk2077Game_1 = __webpack_require__(/*! ./Cyberpunk2077Game */ 911);
const MinesweeperGame_1 = __webpack_require__(/*! ./MinesweeperGame */ 910);
const WireCuttingGame_1 = __webpack_require__(/*! ./WireCuttingGame */ 909);
const Victory_1 = __webpack_require__(/*! ./Victory */ 908);
var Stage;
(function (Stage) {
Stage[Stage["Countdown"] = 0] = "Countdown";
Stage[Stage["Minigame"] = 1] = "Minigame";
Stage[Stage["Result"] = 2] = "Result";
Stage[Stage["Sell"] = 3] = "Sell";
})(Stage || (Stage = {}));
const minigames = [
SlashGame_1.SlashGame,
BracketGame_1.BracketGame,
BackwardGame_1.BackwardGame,
BribeGame_1.BribeGame,
CheatCodeGame_1.CheatCodeGame,
Cyberpunk2077Game_1.Cyberpunk2077Game,
MinesweeperGame_1.MinesweeperGame,
WireCuttingGame_1.WireCuttingGame,
];
function Game(props) {
const [level, setLevel] = react_1.useState(1);
const [stage, setStage] = react_1.useState(Stage.Countdown);
const [results, setResults] = react_1.useState('');
const [gameIds, setGameIds] = react_1.useState({
lastGames: [-1, -1],
id: Math.floor(Math.random() * minigames.length),
});
function nextGameId() {
let id = gameIds.lastGames[0];
const ids = [gameIds.lastGames[0], gameIds.lastGames[1], gameIds.id];
while (ids.includes(id)) {
id = Math.floor(Math.random() * minigames.length);
}
return id;
}
function setupNextGame() {
setGameIds({
lastGames: [gameIds.lastGames[1], gameIds.id],
id: nextGameId(),
});
}
function success() {
pushResult(true);
if (level === props.MaxLevel) {
setStage(Stage.Sell);
}
else {
setStage(Stage.Countdown);
setLevel(level + 1);
}
setupNextGame();
}
function pushResult(win) {
setResults(old => {
let next = old;
next += win ? "✓" : "✗";
if (next.length > 15)
next = next.slice(1);
return next;
});
}
function failure(options) {
setStage(Stage.Countdown);
pushResult(false);
// Kill the player immediately if they use automation, so
// it's clear they're not meant to
const damage = (options === null || options === void 0 ? void 0 : options.automated) ? props.Player.hp : props.StartingDifficulty * 3;
if (props.Player.takeDamage(damage)) {
const menu = document.getElementById("mainmenu-container");
if (menu === null)
throw new Error("mainmenu-container not found");
menu.style.visibility = "visible";
props.Engine.loadLocationContent();
}
setupNextGame();
}
let stageComponent;
switch (stage) {
case Stage.Countdown:
stageComponent = (react_1.default.createElement(Countdown_1.Countdown, { onFinish: () => setStage(Stage.Minigame) }));
break;
case Stage.Minigame: {
const MiniGame = minigames[gameIds.id];
stageComponent = (react_1.default.createElement(MiniGame, { onSuccess: success, onFailure: failure, difficulty: props.Difficulty + level / 50 }));
break;
}
case Stage.Sell:
stageComponent = (react_1.default.createElement(Victory_1.Victory, { Player: props.Player, Engine: props.Engine, StartingDifficulty: props.StartingDifficulty, Difficulty: props.Difficulty, MaxLevel: props.MaxLevel }));
break;
}
function Progress() {
return react_1.default.createElement("h4", null,
react_1.default.createElement("span", { style: { color: "gray" } }, results.slice(0, results.length - 1)),
results[results.length - 1]);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(Grid_1.default, { item: true, xs: 3 },
react_1.default.createElement("h3", null,
"Level: ",
level,
"\u00A0/\u00A0",
props.MaxLevel),
react_1.default.createElement(Progress, null)),
react_1.default.createElement(Grid_1.default, { item: true, xs: 12 }, stageComponent))));
}
exports.Game = Game;
/***/ }),
/* 919 */,
/* 920 */,
/* 921 */,
/* 922 */
/*!***************************************!*\
!*** ./src/Infiltration/ui/Intro.tsx ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Intro = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const Grid_1 = __importDefault(__webpack_require__(/*! @material-ui/core/Grid */ 89));
function arrowPart(color, length) {
let arrow = "";
if (length <= 0)
length = 0;
else if (length > 13)
length = 13;
else {
length--;
arrow = ">";
}
return react_1.default.createElement("span", { style: { color: color } },
"=".repeat(length),
arrow,
" ".repeat(13 - arrow.length - length));
}
function coloredArrow(difficulty) {
if (difficulty === 0) {
return react_1.default.createElement("span", { style: { color: 'white' } },
'>',
" ".repeat(38));
}
else {
return react_1.default.createElement(react_1.default.Fragment, null,
arrowPart('white', difficulty * 13),
arrowPart('orange', (difficulty - 1) * 13),
arrowPart('red', (difficulty - 2) * 13));
}
}
function Intro(props) {
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(Grid_1.default, { container: true, spacing: 3 },
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("h1", null,
"Infiltrating ",
props.Location)),
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("h2", null,
"Maximum level: ",
props.MaxLevel)),
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("pre", null,
"[",
coloredArrow(props.Difficulty),
"]"),
react_1.default.createElement("pre", null, " ^ ^ ^ ^"),
react_1.default.createElement("pre", null, " Trivial Normal Hard Impossible")),
react_1.default.createElement(Grid_1.default, { item: true, xs: 10 },
react_1.default.createElement("p", null, "Infiltration is a series of short minigames that get progressively harder. You take damage for failing them. Reaching the maximum level rewards you with intel you can trade for money or reputation."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "The minigames you play are randomly selected. It might take you few tries to get used to them."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "No game require use of the mouse."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "Spacebar is the default action/confirm button."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "Everything that uses arrow can also use WASD"),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "Sometimes the rest of the keyboard is used.")),
react_1.default.createElement(Grid_1.default, { item: true, xs: 3 },
react_1.default.createElement(StdButton_1.StdButton, { onClick: props.start, text: "Start" })),
react_1.default.createElement(Grid_1.default, { item: true, xs: 3 },
react_1.default.createElement(StdButton_1.StdButton, { onClick: props.cancel, text: "Cancel" })))));
}
exports.Intro = Intro;
/***/ }),
/* 923 */
/*!**************************************!*\
!*** ./src/Infiltration/ui/Root.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Root = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const Intro_1 = __webpack_require__(/*! ./Intro */ 922);
const Game_1 = __webpack_require__(/*! ./Game */ 918);
function Root(props) {
const [start, setStart] = react_1.useState(false);
function cancel() {
const menu = document.getElementById("mainmenu-container");
if (menu === null)
throw new Error("mainmenu-container not found");
menu.style.visibility = "visible";
props.Engine.loadLocationContent();
}
if (!start) {
return (react_1.default.createElement(Intro_1.Intro, { Player: props.Player, Engine: props.Engine, Location: props.Location, Difficulty: props.Difficulty, MaxLevel: props.MaxLevel, start: () => setStart(true), cancel: cancel }));
}
return (react_1.default.createElement(Game_1.Game, { Player: props.Player, Engine: props.Engine, StartingDifficulty: props.StartingDifficulty, Difficulty: props.Difficulty, MaxLevel: props.MaxLevel }));
}
exports.Root = Root;
/***/ }),
/* 924 */
/*!******************************************!*\
!*** ./src/Bladeburner/ui/SkillElem.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkillElem = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const CopyableText_1 = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
function SkillElem(props) {
const skillName = props.skill.name;
let currentLevel = 0;
if (props.bladeburner.skills[skillName] && !isNaN(props.bladeburner.skills[skillName])) {
currentLevel = props.bladeburner.skills[skillName];
}
const pointCost = props.skill.calculateCost(currentLevel);
const canLevel = props.bladeburner.skillPoints >= pointCost;
const maxLvl = props.skill.maxLvl ? currentLevel >= props.skill.maxLvl : false;
function onClick() {
if (props.bladeburner.skillPoints < pointCost)
return;
props.bladeburner.skillPoints -= pointCost;
props.bladeburner.upgradeSkill(props.skill);
props.onUpgrade();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("h2", { style: { display: 'inline-block' } },
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.skill.name })),
react_1.default.createElement("a", { onClick: onClick, style: { display: "inline-block", margin: "3px", padding: "3px" }, className: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive" }, "Level"),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { style: { display: 'block' } },
"Level: ",
currentLevel),
maxLvl ?
react_1.default.createElement("p", { style: { color: "red", display: "block" } }, "MAX LEVEL") :
react_1.default.createElement("p", { style: { display: "block" } },
"Skill Points required: ",
StringHelperFunctions_1.formatNumber(pointCost, 0)),
react_1.default.createElement("p", { style: { display: "inline-block" }, dangerouslySetInnerHTML: { __html: props.skill.desc } })));
}
exports.SkillElem = SkillElem;
/***/ }),
/* 925 */
/*!******************************************!*\
!*** ./src/Bladeburner/ui/SkillList.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkillList = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const SkillElem_1 = __webpack_require__(/*! ./SkillElem */ 924);
const Skills_1 = __webpack_require__(/*! ../Skills */ 687);
function SkillList(props) {
return (React.createElement(React.Fragment, null, Object.keys(Skills_1.Skills).map((skill) => React.createElement("li", { key: skill, className: "bladeburner-action" },
React.createElement(SkillElem_1.SkillElem, { bladeburner: props.bladeburner, skill: Skills_1.Skills[skill], onUpgrade: props.onUpgrade })))));
}
exports.SkillList = SkillList;
/***/ }),
/* 926 */
/*!******************************************!*\
!*** ./src/Bladeburner/ui/SkillPage.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkillPage = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const SkillList_1 = __webpack_require__(/*! ./SkillList */ 925);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 142);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
function SkillPage(props) {
const setRerender = react_1.useState(false)[1];
const mults = props.bladeburner.skillMultipliers;
function valid(mult) {
return mult && mult !== 1;
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
react_1.default.createElement("strong", null,
"Skill Points: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.skillPoints, 0))),
react_1.default.createElement("p", null,
"You will gain one skill point every ",
Constants_1.BladeburnerConstants.RanksPerSkillPoint,
" ranks.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Note that when upgrading a skill, the benefit for that skill is additive. However, the effects of different skills with each other is multiplicative.",
react_1.default.createElement("br", null)),
react_1.default.createElement("br", null),
valid(mults["successChanceAll"]) && react_1.default.createElement("p", null,
"Total Success Chance: x",
StringHelperFunctions_1.formatNumber(mults["successChanceAll"], 3)),
valid(mults["successChanceStealth"]) && react_1.default.createElement("p", null,
"Stealth Success Chance: x",
StringHelperFunctions_1.formatNumber(mults["successChanceStealth"], 3)),
valid(mults["successChanceKill"]) && react_1.default.createElement("p", null,
"Retirement Success Chance: x",
StringHelperFunctions_1.formatNumber(mults["successChanceKill"], 3)),
valid(mults["successChanceContract"]) && react_1.default.createElement("p", null,
"Contract Success Chance: x",
StringHelperFunctions_1.formatNumber(mults["successChanceContract"], 3)),
valid(mults["successChanceOperation"]) && react_1.default.createElement("p", null,
"Operation Success Chance: x",
StringHelperFunctions_1.formatNumber(mults["successChanceOperation"], 3)),
valid(mults["successChanceEstimate"]) && react_1.default.createElement("p", null,
"Synthoid Data Estimate: x",
StringHelperFunctions_1.formatNumber(mults["successChanceEstimate"], 3)),
valid(mults["actionTime"]) && react_1.default.createElement("p", null,
"Action Time: x",
StringHelperFunctions_1.formatNumber(mults["actionTime"], 3)),
valid(mults["effHack"]) && react_1.default.createElement("p", null,
"Hacking Skill: x",
StringHelperFunctions_1.formatNumber(mults["effHack"], 3)),
valid(mults["effStr"]) && react_1.default.createElement("p", null,
"Strength: x",
StringHelperFunctions_1.formatNumber(mults["effStr"], 3)),
valid(mults["effDef"]) && react_1.default.createElement("p", null,
"Defense: x",
StringHelperFunctions_1.formatNumber(mults["effDef"], 3)),
valid(mults["effDex"]) && react_1.default.createElement("p", null,
"Dexterity: x",
StringHelperFunctions_1.formatNumber(mults["effDex"], 3)),
valid(mults["effAgi"]) && react_1.default.createElement("p", null,
"Agility: x",
StringHelperFunctions_1.formatNumber(mults["effAgi"], 3)),
valid(mults["effCha"]) && react_1.default.createElement("p", null,
"Charisma: x",
StringHelperFunctions_1.formatNumber(mults["effCha"], 3)),
valid(mults["effInt"]) && react_1.default.createElement("p", null,
"Intelligence: x",
StringHelperFunctions_1.formatNumber(mults["effInt"], 3)),
valid(mults["stamina"]) && react_1.default.createElement("p", null,
"Stamina: x",
StringHelperFunctions_1.formatNumber(mults["stamina"], 3)),
valid(mults["money"]) && react_1.default.createElement("p", null,
"Contract Money: x",
StringHelperFunctions_1.formatNumber(mults["money"], 3)),
valid(mults["expGain"]) && react_1.default.createElement("p", null,
"Exp Gain: x",
StringHelperFunctions_1.formatNumber(mults["expGain"], 3)),
react_1.default.createElement("br", null),
react_1.default.createElement(SkillList_1.SkillList, { bladeburner: props.bladeburner, onUpgrade: () => setRerender(old => !old) })));
}
exports.SkillPage = SkillPage;
/*
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 = formatNumber(mult, 3);
switch(multKeys[i]) {
}
}
}
*/
/***/ }),
/* 927 */
/*!********************************************!*\
!*** ./src/Bladeburner/ui/BlackOpElem.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlackOpElem = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const ActionTypes_1 = __webpack_require__(/*! ../data/ActionTypes */ 281);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const Icons_1 = __webpack_require__(/*! ../data/Icons */ 393);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const TeamSizePopup_1 = __webpack_require__(/*! ./TeamSizePopup */ 641);
const SuccessChance_1 = __webpack_require__(/*! ./SuccessChance */ 476);
const CopyableText_1 = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
function BlackOpElem(props) {
const setRerender = react_1.useState(false)[1];
const isCompleted = (props.bladeburner.blackops[props.action.name] != null);
if (isCompleted) {
return (react_1.default.createElement("h2", { style: { display: 'block' } },
props.action.name,
" (COMPLETED)"));
}
const isActive = props.bladeburner.action.type === ActionTypes_1.ActionTypes["BlackOperation"] && props.action.name === props.bladeburner.action.name;
const estimatedSuccessChance = props.action.getEstSuccessChance(props.bladeburner);
const actionTime = props.action.getActionTime(props.bladeburner);
const hasReqdRank = props.bladeburner.rank >= props.action.reqdRank;
const computedActionTimeCurrent = Math.min(props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete);
function onStart() {
props.bladeburner.action.type = ActionTypes_1.ActionTypes.BlackOperation;
props.bladeburner.action.name = props.action.name;
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function onTeam() {
const popupId = "bladeburner-operation-set-team-size-popup";
createPopup_1.createPopup(popupId, TeamSizePopup_1.TeamSizePopup, {
bladeburner: props.bladeburner,
action: props.action,
popupId: popupId,
});
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("h2", { style: { display: 'inline-block' } }, isActive ?
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name }),
" (IN PROGRESS - ",
StringHelperFunctions_1.formatNumber(computedActionTimeCurrent, 0),
" / ",
StringHelperFunctions_1.formatNumber(props.bladeburner.actionTimeToComplete, 0),
")") :
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name })),
isActive ?
react_1.default.createElement("p", { style: { display: 'block' } }, createProgressBarText_1.createProgressBarText({ progress: computedActionTimeCurrent / props.bladeburner.actionTimeToComplete })) :
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { className: hasReqdRank ? "a-link-button" : "a-link-button-inactive", style: { margin: "3px", padding: "3px" }, onClick: onStart }, "Start"),
react_1.default.createElement("a", { onClick: onTeam, style: { margin: "3px", padding: "3px" }, className: "a-link-button" },
"Set Team Size (Curr Size: ",
StringHelperFunctions_1.formatNumber(props.action.teamCount, 0),
")")),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { style: { display: "inline-block" }, dangerouslySetInnerHTML: { __html: props.action.desc } }),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { style: { display: "block", color: hasReqdRank ? "white" : "red" } },
"Required Rank: ",
StringHelperFunctions_1.formatNumber(props.action.reqdRank, 0)),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { style: { display: "inline-block" } },
"Estimated Success Chance: ",
react_1.default.createElement(SuccessChance_1.SuccessChance, { chance: estimatedSuccessChance }),
" ",
props.action.isStealth ? Icons_1.stealthIcon : react_1.default.createElement(react_1.default.Fragment, null),
props.action.isKill ? Icons_1.killIcon : react_1.default.createElement(react_1.default.Fragment, null),
react_1.default.createElement("br", null),
"Time Required: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(actionTime * 1000))));
}
exports.BlackOpElem = BlackOpElem;
/***/ }),
/* 928 */
/*!********************************************!*\
!*** ./src/Bladeburner/ui/BlackOpList.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlackOpList = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const BlackOperations_1 = __webpack_require__(/*! ../BlackOperations */ 691);
const BlackOpElem_1 = __webpack_require__(/*! ./BlackOpElem */ 927);
function BlackOpList(props) {
let blackops = [];
for (const blackopName in BlackOperations_1.BlackOperations) {
if (BlackOperations_1.BlackOperations.hasOwnProperty(blackopName)) {
blackops.push(BlackOperations_1.BlackOperations[blackopName]);
}
}
blackops.sort(function (a, b) {
return (a.reqdRank - b.reqdRank);
});
blackops = blackops.filter((blackop, i) => !(props.bladeburner.blackops[blackops[i].name] == null &&
i !== 0 &&
props.bladeburner.blackops[blackops[i - 1].name] == null));
blackops = blackops.reverse();
return (react_1.default.createElement(react_1.default.Fragment, null, blackops.map((blackop) => react_1.default.createElement("li", { key: blackop.name, className: "bladeburner-action" },
react_1.default.createElement(BlackOpElem_1.BlackOpElem, { bladeburner: props.bladeburner, action: blackop, player: props.player })))));
}
exports.BlackOpList = BlackOpList;
/***/ }),
/* 929 */
/*!********************************************!*\
!*** ./src/Bladeburner/ui/BlackOpPage.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlackOpPage = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const BlackOpList_1 = __webpack_require__(/*! ./BlackOpList */ 928);
function BlackOpPage(props) {
return (React.createElement(React.Fragment, null,
React.createElement("p", { style: { display: 'block', margin: '4px', padding: '4px' } },
"Black Operations (Black Ops) are special, one-time covert operations. Each Black Op must be unlocked successively by completing the one before it.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("b", null, "Your ultimate goal to climb through the ranks of Bladeburners is to complete all of the Black Ops."),
React.createElement("br", null),
React.createElement("br", null),
"Like normal operations, you may use a team for Black Ops. Failing a black op will incur heavy HP and rank losses."),
React.createElement(BlackOpList_1.BlackOpList, { bladeburner: props.bladeburner, player: props.player })));
}
exports.BlackOpPage = BlackOpPage;
/***/ }),
/* 930 */
/*!**********************************************!*\
!*** ./src/Bladeburner/ui/OperationElem.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationElem = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const ActionTypes_1 = __webpack_require__(/*! ../data/ActionTypes */ 281);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const Icons_1 = __webpack_require__(/*! ../data/Icons */ 393);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 142);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const TeamSizePopup_1 = __webpack_require__(/*! ./TeamSizePopup */ 641);
const SuccessChance_1 = __webpack_require__(/*! ./SuccessChance */ 476);
const CopyableText_1 = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
function OperationElem(props) {
const setRerender = react_1.useState(false)[1];
const isActive = props.bladeburner.action.type === ActionTypes_1.ActionTypes["Operation"] && props.action.name === props.bladeburner.action.name;
const estimatedSuccessChance = props.action.getEstSuccessChance(props.bladeburner);
const computedActionTimeCurrent = Math.min(props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete);
const maxLevel = (props.action.level >= props.action.maxLevel);
const actionTime = props.action.getActionTime(props.bladeburner);
const autolevelCheckboxId = `bladeburner-${props.action.name}-autolevel-checkbox`;
function onStart() {
props.bladeburner.action.type = ActionTypes_1.ActionTypes.Operation;
props.bladeburner.action.name = props.action.name;
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function onTeam() {
const popupId = "bladeburner-operation-set-team-size-popup";
createPopup_1.createPopup(popupId, TeamSizePopup_1.TeamSizePopup, {
bladeburner: props.bladeburner,
action: props.action,
popupId: popupId,
});
}
function increaseLevel() {
++props.action.level;
if (isActive)
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function decreaseLevel() {
--props.action.level;
if (isActive)
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function onAutolevel(event) {
props.action.autoLevel = event.target.checked;
setRerender(old => !old);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("h2", { style: { display: 'inline-block' } }, isActive ?
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name }),
" (IN PROGRESS - ",
StringHelperFunctions_1.formatNumber(computedActionTimeCurrent, 0),
" / ",
StringHelperFunctions_1.formatNumber(props.bladeburner.actionTimeToComplete, 0),
")") :
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name })),
isActive ?
react_1.default.createElement("p", { style: { display: 'block' } }, createProgressBarText_1.createProgressBarText({ progress: computedActionTimeCurrent / props.bladeburner.actionTimeToComplete })) :
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { onClick: onStart, className: "a-link-button", style: { margin: "3px", padding: "3px" } }, "Start"),
react_1.default.createElement("a", { onClick: onTeam, style: { margin: "3px", padding: "3px" }, className: "a-link-button" },
"Set Team Size (Curr Size: ",
StringHelperFunctions_1.formatNumber(props.action.teamCount, 0),
")")),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { className: "tooltip", style: { display: "inline-block" } },
react_1.default.createElement("span", { className: "tooltiptext" },
props.action.getSuccessesNeededForNextLevel(Constants_1.BladeburnerConstants.OperationSuccessesPerLevel),
" successes needed for next level"),
"Level: ",
props.action.level,
" / ",
props.action.maxLevel),
react_1.default.createElement("a", { onClick: increaseLevel, style: { padding: "2px", margin: "2px" }, className: `tooltip ${maxLevel ? "a-link-button-inactive" : "a-link-button"}` },
isActive && (react_1.default.createElement("span", { className: "tooltiptext" }, "WARNING: changing the level will restart the Operation")),
"\u2191"),
react_1.default.createElement("a", { onClick: decreaseLevel, style: { padding: "2px", margin: "2px" }, className: `tooltip ${props.action.level <= 1 ? "a-link-button-inactive" : "a-link-button"}` },
isActive && (react_1.default.createElement("span", { className: "tooltiptext" }, "WARNING: changing the level will restart the Operation")),
"\u2193"),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { style: { display: "inline-block" } },
react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: props.action.desc } }),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Estimated success chance: ",
react_1.default.createElement(SuccessChance_1.SuccessChance, { chance: estimatedSuccessChance }),
" ",
props.action.isStealth ? Icons_1.stealthIcon : react_1.default.createElement(react_1.default.Fragment, null),
props.action.isKill ? Icons_1.killIcon : react_1.default.createElement(react_1.default.Fragment, null),
react_1.default.createElement("br", null),
"Time Required: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(actionTime * 1000),
react_1.default.createElement("br", null),
"Operations remaining: ",
Math.floor(props.action.count),
react_1.default.createElement("br", null),
"Successes: ",
props.action.successes,
react_1.default.createElement("br", null),
"Failures: ",
props.action.failures),
react_1.default.createElement("br", null),
react_1.default.createElement("label", { className: "tooltip", style: { color: 'white' }, htmlFor: autolevelCheckboxId },
"Autolevel:",
react_1.default.createElement("span", { className: "tooltiptext" }, "Automatically increase operation level when possible")),
react_1.default.createElement("input", { type: "checkbox", id: autolevelCheckboxId, checked: props.action.autoLevel, onChange: onAutolevel })));
}
exports.OperationElem = OperationElem;
/***/ }),
/* 931 */
/*!**********************************************!*\
!*** ./src/Bladeburner/ui/OperationList.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationList = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const OperationElem_1 = __webpack_require__(/*! ./OperationElem */ 930);
function OperationList(props) {
const names = Object.keys(props.bladeburner.operations);
const operations = props.bladeburner.operations;
return (react_1.default.createElement(react_1.default.Fragment, null, names.map((name) => react_1.default.createElement("li", { key: name, className: "bladeburner-action" },
react_1.default.createElement(OperationElem_1.OperationElem, { bladeburner: props.bladeburner, action: operations[name], player: props.player })))));
}
exports.OperationList = OperationList;
/***/ }),
/* 932 */
/*!**********************************************!*\
!*** ./src/Bladeburner/ui/OperationPage.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationPage = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const OperationList_1 = __webpack_require__(/*! ./OperationList */ 931);
function OperationPage(props) {
return (React.createElement(React.Fragment, null,
React.createElement("p", { style: { display: 'block', margin: '4px', padding: '4px' } },
"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.",
React.createElement("br", null),
React.createElement("br", null),
"Operations can affect the chaos level and Synthoid population of your current city. The exact effects vary between different Operations.",
React.createElement("br", null),
React.createElement("br", null),
"For operations, you can use a team. You must first recruit team members. Having a larger team will improves your chances of success.",
React.createElement("br", null),
React.createElement("br", null),
"You can unlock higher-level operations by successfully completing them. Higher-level operations are more difficult, but grant more rank and experience."),
React.createElement(OperationList_1.OperationList, { bladeburner: props.bladeburner, player: props.player })));
}
exports.OperationPage = OperationPage;
/***/ }),
/* 933 */
/*!*********************************************!*\
!*** ./src/Bladeburner/ui/ContractElem.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractElem = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const ActionTypes_1 = __webpack_require__(/*! ../data/ActionTypes */ 281);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const Icons_1 = __webpack_require__(/*! ../data/Icons */ 393);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 142);
const SuccessChance_1 = __webpack_require__(/*! ./SuccessChance */ 476);
const CopyableText_1 = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
function ContractElem(props) {
const setRerender = react_1.useState(false)[1];
const isActive = props.bladeburner.action.type === ActionTypes_1.ActionTypes["Contract"] && props.action.name === props.bladeburner.action.name;
const estimatedSuccessChance = props.action.getEstSuccessChance(props.bladeburner);
const successChance = props.action.getSuccessChance(props.bladeburner);
const computedActionTimeCurrent = Math.min(props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete);
const maxLevel = (props.action.level >= props.action.maxLevel);
const actionTime = props.action.getActionTime(props.bladeburner);
const autolevelCheckboxId = `bladeburner-${props.action.name}-autolevel-checkbox`;
function onStart() {
props.bladeburner.action.type = ActionTypes_1.ActionTypes.Contract;
props.bladeburner.action.name = props.action.name;
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function increaseLevel() {
++props.action.level;
if (isActive)
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function decreaseLevel() {
--props.action.level;
if (isActive)
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
function onAutolevel(event) {
props.action.autoLevel = event.target.checked;
setRerender(old => !old);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("h2", { style: { display: 'inline-block' } }, isActive ?
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name }),
" (IN PROGRESS - ",
StringHelperFunctions_1.formatNumber(computedActionTimeCurrent, 0),
" / ",
StringHelperFunctions_1.formatNumber(props.bladeburner.actionTimeToComplete, 0),
")") :
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name })),
isActive ?
react_1.default.createElement("p", { style: { display: 'block' } }, createProgressBarText_1.createProgressBarText({ progress: computedActionTimeCurrent / props.bladeburner.actionTimeToComplete })) :
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { onClick: onStart, className: "a-link-button", style: { margin: "3px", padding: "3px" } }, "Start")),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { className: "tooltip", style: { display: "inline-block" } },
react_1.default.createElement("span", { className: "tooltiptext" },
props.action.getSuccessesNeededForNextLevel(Constants_1.BladeburnerConstants.ContractSuccessesPerLevel),
" successes needed for next level"),
"Level: ",
props.action.level,
" / ",
props.action.maxLevel),
react_1.default.createElement("a", { onClick: increaseLevel, style: { padding: "2px", margin: "2px" }, className: `tooltip ${maxLevel ? "a-link-button-inactive" : "a-link-button"}` },
isActive && (react_1.default.createElement("span", { className: "tooltiptext" }, "WARNING: changing the level will restart the Operation")),
"\u2191"),
react_1.default.createElement("a", { onClick: decreaseLevel, style: { padding: "2px", margin: "2px" }, className: `tooltip ${props.action.level <= 1 ? "a-link-button-inactive" : "a-link-button"}` },
isActive && (react_1.default.createElement("span", { className: "tooltiptext" }, "WARNING: changing the level will restart the Operation")),
"\u2193"),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { style: { display: 'inline-block' } },
react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: props.action.desc } }),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Estimated success chance: ",
react_1.default.createElement(SuccessChance_1.SuccessChance, { chance: estimatedSuccessChance }),
" ",
props.action.isStealth ? Icons_1.stealthIcon : react_1.default.createElement(react_1.default.Fragment, null),
props.action.isKill ? Icons_1.killIcon : react_1.default.createElement(react_1.default.Fragment, null),
react_1.default.createElement("br", null),
"Time Required: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(actionTime * 1000),
react_1.default.createElement("br", null),
"Contracts remaining: ",
Math.floor(props.action.count),
react_1.default.createElement("br", null),
"Successes: ",
props.action.successes,
react_1.default.createElement("br", null),
"Failures: ",
props.action.failures),
react_1.default.createElement("br", null),
react_1.default.createElement("label", { className: "tooltip", style: { color: 'white' }, htmlFor: autolevelCheckboxId },
"Autolevel:",
react_1.default.createElement("span", { className: "tooltiptext" }, "Automatically increase operation level when possible")),
react_1.default.createElement("input", { type: "checkbox", id: autolevelCheckboxId, checked: props.action.autoLevel, onChange: onAutolevel })));
}
exports.ContractElem = ContractElem;
/***/ }),
/* 934 */
/*!*********************************************!*\
!*** ./src/Bladeburner/ui/ContractList.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractList = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const ContractElem_1 = __webpack_require__(/*! ./ContractElem */ 933);
function ContractList(props) {
const names = Object.keys(props.bladeburner.contracts);
const contracts = props.bladeburner.contracts;
return (react_1.default.createElement(react_1.default.Fragment, null, names.map((name) => react_1.default.createElement("li", { key: name, className: "bladeburner-action" },
react_1.default.createElement(ContractElem_1.ContractElem, { bladeburner: props.bladeburner, action: contracts[name], player: props.player })))));
}
exports.ContractList = ContractList;
/***/ }),
/* 935 */
/*!*********************************************!*\
!*** ./src/Bladeburner/ui/ContractPage.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractPage = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const ContractList_1 = __webpack_require__(/*! ./ContractList */ 934);
function ContractPage(props) {
return (React.createElement(React.Fragment, null,
React.createElement("p", { style: { display: 'block', margin: '4px', padding: '4px' } },
"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.",
React.createElement("br", null),
React.createElement("br", null),
"You can unlock higher-level contracts by successfully completing them. Higher-level contracts are more difficult, but grant more rank, experience, and money."),
React.createElement(ContractList_1.ContractList, { bladeburner: props.bladeburner, player: props.player })));
}
exports.ContractPage = ContractPage;
/***/ }),
/* 936 */
/*!**************************************************!*\
!*** ./src/Bladeburner/ui/GeneralActionElem.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralActionElem = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const ActionTypes_1 = __webpack_require__(/*! ../data/ActionTypes */ 281);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const CopyableText_1 = __webpack_require__(/*! ../../ui/React/CopyableText */ 164);
function GeneralActionElem(props) {
const setRerender = react_1.useState(false)[1];
const isActive = props.action.name === props.bladeburner.action.name;
const computedActionTimeCurrent = Math.min(props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete);
const actionTime = (function () {
switch (props.action.name) {
case "Training":
case "Field Analysis":
return 30;
case "Diplomacy":
case "Hyperbolic Regeneration Chamber":
return 60;
case "Recruitment":
return props.bladeburner.getRecruitmentTime(props.player);
}
return -1; // dead code
})();
const successChance = props.action.name === "Recruitment" ? Math.max(0, Math.min(props.bladeburner.getRecruitmentSuccessChance(props.player), 1)) : -1;
function onStart() {
props.bladeburner.action.type = ActionTypes_1.ActionTypes[props.action.name];
props.bladeburner.action.name = props.action.name;
props.bladeburner.startAction(props.player, props.bladeburner.action);
setRerender(old => !old);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("h2", { style: { display: 'inline-block' } }, isActive ?
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name }),
" (IN PROGRESS - ",
StringHelperFunctions_1.formatNumber(computedActionTimeCurrent, 0),
" / ",
StringHelperFunctions_1.formatNumber(props.bladeburner.actionTimeToComplete, 0),
")") :
react_1.default.createElement(CopyableText_1.CopyableText, { value: props.action.name })),
isActive ?
react_1.default.createElement("p", { style: { display: 'block' } }, createProgressBarText_1.createProgressBarText({ progress: computedActionTimeCurrent / props.bladeburner.actionTimeToComplete })) :
react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { onClick: onStart, className: "a-link-button", style: { margin: "3px", padding: "3px" } }, "Start")),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { style: { display: 'inline-block' }, dangerouslySetInnerHTML: { __html: props.action.desc } }),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("pre", { style: { display: 'inline-block' } },
"Time Required: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(actionTime * 1000),
successChance !== -1 && react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("br", null),
"Estimated success chance: ",
StringHelperFunctions_1.formatNumber(successChance * 100, 1),
"%"))));
}
exports.GeneralActionElem = GeneralActionElem;
/***/ }),
/* 937 */
/*!**************************************************!*\
!*** ./src/Bladeburner/ui/GeneralActionList.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralActionList = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const GeneralActionElem_1 = __webpack_require__(/*! ./GeneralActionElem */ 936);
const GeneralActions_1 = __webpack_require__(/*! ../GeneralActions */ 688);
function GeneralActionList(props) {
const actions = [];
for (const name in GeneralActions_1.GeneralActions) {
if (GeneralActions_1.GeneralActions.hasOwnProperty(name)) {
actions.push(GeneralActions_1.GeneralActions[name]);
}
}
return (react_1.default.createElement(react_1.default.Fragment, null, actions.map((action) => react_1.default.createElement("li", { key: action.name, className: "bladeburner-action" },
react_1.default.createElement(GeneralActionElem_1.GeneralActionElem, { bladeburner: props.bladeburner, action: action, player: props.player })))));
}
exports.GeneralActionList = GeneralActionList;
/***/ }),
/* 938 */
/*!**************************************************!*\
!*** ./src/Bladeburner/ui/GeneralActionPage.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralActionPage = void 0;
const React = __importStar(__webpack_require__(/*! react */ 0));
const GeneralActionList_1 = __webpack_require__(/*! ./GeneralActionList */ 937);
function GeneralActionPage(props) {
return (React.createElement(React.Fragment, null,
React.createElement("p", { style: { display: 'block', margin: '4px', padding: '4px' } }, "These are generic actions that will assist you in your Bladeburner duties. They will not affect your Bladeburner rank in any way."),
React.createElement(GeneralActionList_1.GeneralActionList, { bladeburner: props.bladeburner, player: props.player })));
}
exports.GeneralActionPage = GeneralActionPage;
/***/ }),
/* 939 */
/*!*****************************************!*\
!*** ./src/Bladeburner/ui/AllPages.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AllPages = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const GeneralActionPage_1 = __webpack_require__(/*! ./GeneralActionPage */ 938);
const ContractPage_1 = __webpack_require__(/*! ./ContractPage */ 935);
const OperationPage_1 = __webpack_require__(/*! ./OperationPage */ 932);
const BlackOpPage_1 = __webpack_require__(/*! ./BlackOpPage */ 929);
const SkillPage_1 = __webpack_require__(/*! ./SkillPage */ 926);
const Icons_1 = __webpack_require__(/*! ../data/Icons */ 393);
function AllPages(props) {
const [page, setPage] = react_1.useState('General');
const setRerender = react_1.useState(false)[1];
react_1.useEffect(() => {
const id = setInterval(() => setRerender(old => !old), 1000);
return () => clearInterval(id);
}, []);
function Header(props) {
return (react_1.default.createElement("a", { onClick: () => setPage(props.name), className: page !== props.name ?
"bladeburner-nav-button" :
"bladeburner-nav-button-inactive" }, props.name));
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(Header, { name: 'General' }),
react_1.default.createElement(Header, { name: 'Contracts' }),
react_1.default.createElement(Header, { name: 'Operations' }),
react_1.default.createElement(Header, { name: 'BlackOps' }),
react_1.default.createElement(Header, { name: 'Skills' }),
react_1.default.createElement("div", { style: { display: "block", margin: "4px", padding: "4px" } },
page === 'General' && react_1.default.createElement(GeneralActionPage_1.GeneralActionPage, { bladeburner: props.bladeburner, player: props.player }),
page === 'Contracts' && react_1.default.createElement(ContractPage_1.ContractPage, { bladeburner: props.bladeburner, player: props.player }),
page === 'Operations' && react_1.default.createElement(OperationPage_1.OperationPage, { bladeburner: props.bladeburner, player: props.player }),
page === 'BlackOps' && react_1.default.createElement(BlackOpPage_1.BlackOpPage, { bladeburner: props.bladeburner, player: props.player }),
page === 'Skills' && react_1.default.createElement(SkillPage_1.SkillPage, { bladeburner: props.bladeburner })),
react_1.default.createElement("span", { className: "text" },
Icons_1.stealthIcon,
" = This action requires stealth, ",
Icons_1.killIcon,
" = This action involves retirement")));
}
exports.AllPages = AllPages;
/***/ }),
/* 940 */
/*!****************************************!*\
!*** ./src/Bladeburner/ui/Console.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Console = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
function Line(props) {
return (react_1.default.createElement("tr", null,
react_1.default.createElement("td", { className: "bladeburner-console-line", style: { color: 'var(--my-font-color)', whiteSpace: 'pre-wrap' } }, props.content)));
}
function Console(props) {
const lastRef = react_1.useRef(null);
const setRerender = react_1.useState(false)[1];
const [consoleHistoryIndex, setConsoleHistoryIndex] = react_1.useState(props.bladeburner.consoleHistory.length);
// TODO: Figure out how to actually make the scrolling work correctly.
function scrollToBottom() {
if (!lastRef.current)
return;
lastRef.current.scrollTop = lastRef.current.scrollHeight;
}
function rerender() {
setRerender(old => !old);
}
react_1.useEffect(() => {
const id = setInterval(rerender, 1000);
const id2 = setInterval(scrollToBottom, 100);
return () => {
clearInterval(id);
clearInterval(id2);
};
}, []);
function handleKeyDown(event) {
if (event.keyCode === 13) {
event.preventDefault();
const command = event.currentTarget.value;
event.currentTarget.value = "";
if (command.length > 0) {
props.bladeburner.postToConsole("> " + command);
props.bladeburner.executeConsoleCommands(props.player, command);
setConsoleHistoryIndex(props.bladeburner.consoleHistory.length);
rerender();
}
}
const consoleHistory = props.bladeburner.consoleHistory;
if (event.keyCode === 38) { // up
let i = consoleHistoryIndex;
const len = consoleHistory.length;
if (len === 0) {
return;
}
if (i < 0 || i > len) {
setConsoleHistoryIndex(len);
}
if (i !== 0) {
i = i - 1;
}
setConsoleHistoryIndex(i);
const prevCommand = consoleHistory[i];
event.currentTarget.value = prevCommand;
}
if (event.keyCode === 40) {
const i = consoleHistoryIndex;
const len = consoleHistory.length;
if (len == 0) {
return;
}
if (i < 0 || i > len) {
setConsoleHistoryIndex(len);
}
// Latest command, put nothing
if (i == len || i == len - 1) {
setConsoleHistoryIndex(len);
event.currentTarget.value = "";
}
else {
setConsoleHistoryIndex(consoleHistoryIndex + 1);
const prevCommand = consoleHistory[consoleHistoryIndex + 1];
event.currentTarget.value = prevCommand;
}
}
}
return (react_1.default.createElement("div", { ref: lastRef, className: "bladeburner-console-div" },
react_1.default.createElement("table", { className: "bladeburner-console-table" },
react_1.default.createElement("tbody", null,
props.bladeburner.consoleLogs.map((log, i) => react_1.default.createElement(Line, { key: i, content: log })),
react_1.default.createElement("tr", { key: "input", id: "bladeburner-console-input-row", className: "bladeburner-console-input-row" },
react_1.default.createElement("td", { className: "bladeburner-console-input-cell" },
react_1.default.createElement("pre", null, "> "),
react_1.default.createElement("input", { autoFocus: true, className: "bladeburner-console-input", tabIndex: 1, type: "text", onKeyDown: handleKeyDown })))))));
}
exports.Console = Console;
/***/ }),
/* 941 */
/*!********************************************!*\
!*** ./src/Bladeburner/ui/TravelPopup.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TravelPopup = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 142);
function TravelPopup(props) {
function travel(city) {
props.bladeburner.city = city;
createPopup_1.removePopup(props.popupId);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "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."),
Constants_1.BladeburnerConstants.CityNames.map(city => {
// Reusing this css class...it adds a border and makes it
// so that background color changes when you hover
return react_1.default.createElement("div", { key: city, className: "cmpy-mgmt-find-employee-option", onClick: () => travel(city) }, city);
})));
}
exports.TravelPopup = TravelPopup;
/***/ }),
/* 942 */
/*!**************************************!*\
!*** ./src/Bladeburner/ui/Stats.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stats = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 142);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const StatsTable_1 = __webpack_require__(/*! ../../ui/React/StatsTable */ 275);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
const FactionHelpers_1 = __webpack_require__(/*! ../../Faction/FactionHelpers */ 71);
const TravelPopup_1 = __webpack_require__(/*! ./TravelPopup */ 941);
function Stats(props) {
const setRerender = react_1.useState(false)[1];
react_1.useEffect(() => {
const id = setInterval(() => setRerender(old => !old), 1000);
return () => clearInterval(id);
}, []);
function openStaminaHelp() {
DialogBox_1.dialogBoxCreate("Performing actions will use up your stamina.
" +
"Your max stamina is determined primarily by your agility stat.
" +
"Your stamina gain rate is determined by both your agility and your " +
"max stamina. Higher max stamina leads to a higher gain rate.
" +
"Once your " +
"stamina falls below 50% of its max value, it begins to negatively " +
"affect the success rate of your contracts/operations. This penalty " +
"is shown in the overview panel. If the penalty is 15%, then this means " +
"your success rate would be multipled by 85% (100 - 15).
" +
"Your max stamina and stamina gain rate can also be increased by " +
"training, or through skills and Augmentation upgrades.");
}
function openPopulationHelp() {
DialogBox_1.dialogBoxCreate("The success rate of your contracts/operations depends on " +
"the population of Synthoids in your current city. " +
"The success rate that is shown to you is only an estimate, " +
"and it is based on your Synthoid population estimate.
" +
"Therefore, it is important that this Synthoid population estimate " +
"is accurate so that you have a better idea of your " +
"success rate for contracts/operations. Certain " +
"actions will increase the accuracy of your population " +
"estimate.
" +
"The Synthoid populations of cities can change due to your " +
"actions or random events. If random events occur, they will " +
"be logged in the Bladeburner Console.");
}
function openTravel() {
const popupId = "bladeburner-travel-popup";
createPopup_1.createPopup(popupId, TravelPopup_1.TravelPopup, {
bladeburner: props.bladeburner,
popupId: popupId,
});
}
function openFaction() {
const faction = Factions_1.Factions["Bladeburners"];
if (faction.isMember) {
props.engine.loadFactionContent();
FactionHelpers_1.displayFactionContent("Bladeburners");
}
else {
if (props.bladeburner.rank >= Constants_1.BladeburnerConstants.RankNeededForFaction) {
FactionHelpers_1.joinFaction(faction);
DialogBox_1.dialogBoxCreate("Congratulations! You were accepted into the Bladeburners faction");
}
else {
DialogBox_1.dialogBoxCreate("You need a rank of 25 to join the Bladeburners Faction!");
}
}
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", { className: "tooltip", style: { display: 'inline-block' } },
"Rank: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.rank, 2),
react_1.default.createElement("span", { className: "tooltiptext" }, "Your rank within the Bladeburner division.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Stamina: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.stamina, 3),
" / ",
StringHelperFunctions_1.formatNumber(props.bladeburner.maxStamina, 3)),
react_1.default.createElement("div", { className: "help-tip", onClick: openStaminaHelp }, "?"),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Stamina Penalty: ",
StringHelperFunctions_1.formatNumber((1 - props.bladeburner.calculateStaminaPenalty()) * 100, 1),
"%"),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Team Size: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.teamSize, 0)),
react_1.default.createElement("p", null,
"Team Members Lost: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.teamLost, 0)),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Num Times Hospitalized: ",
props.bladeburner.numHosp),
react_1.default.createElement("p", null,
"Money Lost From Hospitalizations: ",
Money_1.Money(props.bladeburner.moneyLost)),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Current City: ",
props.bladeburner.city),
react_1.default.createElement("p", { className: "tooltip", style: { display: 'inline-block' } },
"Est. Synthoid Population: ",
numeralFormat_1.numeralWrapper.formatPopulation(props.bladeburner.getCurrentCity().popEst),
react_1.default.createElement("span", { className: "tooltiptext" }, "This is your Bladeburner division's estimate of how many Synthoids exist in your current city.")),
react_1.default.createElement("div", { className: "help-tip", onClick: openPopulationHelp }, "?"),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: 'inline-block' } },
"Est. Synthoid Communities: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.getCurrentCity().comms, 0),
react_1.default.createElement("span", { className: "tooltiptext" }, "This is your Bladeburner divison's estimate of how many Synthoid communities exist in your current city.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: 'inline-block' } },
"City Chaos: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.getCurrentCity().chaos),
react_1.default.createElement("span", { className: "tooltiptext" }, "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.")),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: 'inline-block' } },
"Bonus time: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(props.bladeburner.storedCycles / Constants_1.BladeburnerConstants.CyclesPerSecond * 1000),
react_1.default.createElement("br", null),
react_1.default.createElement("span", { className: "tooltiptext" }, "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.")),
react_1.default.createElement("p", null,
"Skill Points: ",
StringHelperFunctions_1.formatNumber(props.bladeburner.skillPoints, 0)),
react_1.default.createElement("br", null),
StatsTable_1.StatsTable([
["Aug. Success Chance mult: ", StringHelperFunctions_1.formatNumber(props.player.bladeburner_success_chance_mult * 100, 1) + "%"],
["Aug. Max Stamina mult: ", StringHelperFunctions_1.formatNumber(props.player.bladeburner_max_stamina_mult * 100, 1) + "%"],
["Aug. Stamina Gain mult: ", StringHelperFunctions_1.formatNumber(props.player.bladeburner_stamina_gain_mult * 100, 1) + "%"],
["Aug. Field Analysis mult: ", StringHelperFunctions_1.formatNumber(props.player.bladeburner_analysis_mult * 100, 1) + "%"],
]),
react_1.default.createElement("br", null),
react_1.default.createElement("a", { onClick: openTravel, className: "a-link-button", style: { display: "inline-block" } }, "Travel"),
react_1.default.createElement("a", { onClick: openFaction, className: "a-link-button tooltip", style: { display: "inline-block" } },
react_1.default.createElement("span", { className: "tooltiptext" }, "Apply to the Bladeburner Faction, or go to the faction page if you are already a member"),
"Faction"),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null)));
}
exports.Stats = Stats;
/***/ }),
/* 943 */
/*!******************************************!*\
!*** ./src/Gang/ui/TerritorySubpage.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TerritorySubpage = void 0;
/**
* React Component for the territory subpage.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const AllGangs_1 = __webpack_require__(/*! ../AllGangs */ 85);
function TerritorySubpage(props) {
function openWarfareHelp() {
DialogBox_1.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.");
}
function formatTerritory(n) {
const v = n * 100;
if (v <= 0) {
return StringHelperFunctions_1.formatNumber(0, 2);
}
else if (v >= 100) {
return StringHelperFunctions_1.formatNumber(100, 2);
}
else {
return StringHelperFunctions_1.formatNumber(v, 2);
}
}
const playerPower = AllGangs_1.AllGangs[props.gang.facName].power;
function otherGangTerritory(name) {
const power = AllGangs_1.AllGangs[name].power;
const clashVictoryChance = playerPower / (power + playerPower);
return (react_1.default.createElement("span", { key: name },
react_1.default.createElement("u", null, name),
react_1.default.createElement("br", null),
"Power: ",
StringHelperFunctions_1.formatNumber(power, 6),
react_1.default.createElement("br", null),
"Territory: ",
formatTerritory(AllGangs_1.AllGangs[name].territory),
"%",
react_1.default.createElement("br", null),
"Chance to win clash with this gang: ",
numeralFormat_1.numeralWrapper.formatPercentage(clashVictoryChance, 3),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null)));
}
const gangNames = Object.keys(AllGangs_1.AllGangs).filter(g => g != props.gang.facName);
return (react_1.default.createElement("div", { style: { width: '70%' } },
react_1.default.createElement("p", { className: "noselect" },
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null)),
react_1.default.createElement("input", { checked: props.gang.territoryWarfareEngaged, id: "warfare", type: "checkbox", style: { display: "inline-block", margin: "2px" }, onChange: (event) => props.gang.territoryWarfareEngaged = event.target.checked }),
react_1.default.createElement("label", { htmlFor: "warfare", className: "tooltip noselect", style: { color: "white", display: 'inline-block' } },
"Engage in Territory Warfare",
react_1.default.createElement("span", { className: "tooltiptext", style: { display: "inline-block" } }, "Engaging in Territory Warfare sets your clash chance to 100%. Disengaging will cause your clash chance to gradually decrease until it reaches 0%.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { style: { display: 'inline-block' } },
"Territory Clash Chance: ",
numeralFormat_1.numeralWrapper.formatPercentage(props.gang.territoryClashChance, 3)),
react_1.default.createElement("div", { className: "help-tip noselect", style: { display: "inline-block" }, onClick: openWarfareHelp }, "?"),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { checked: props.gang.notifyMemberDeath, id: "notify", type: "checkbox", style: { display: "inline-block", margin: "2px" }, onChange: (event) => props.gang.notifyMemberDeath = event.target.checked }),
react_1.default.createElement("label", { htmlFor: "warfare", className: "tooltip noselect", style: { color: "white", display: 'inline-block' } },
"Notify about Gang Member Deaths",
react_1.default.createElement("span", { className: "tooltiptext", style: { display: "inline-block" } }, "If this is enabled, then you will receive a pop-up notifying you whenever one of your Gang Members dies in a territory clash.")),
react_1.default.createElement("br", null),
react_1.default.createElement("fieldset", { style: { display: "block", margin: "6px" } },
react_1.default.createElement("p", null,
react_1.default.createElement("b", null,
react_1.default.createElement("u", null, props.gang.facName)),
react_1.default.createElement("br", null),
"Power: ",
StringHelperFunctions_1.formatNumber(AllGangs_1.AllGangs[props.gang.facName].power, 6),
react_1.default.createElement("br", null),
"Territory: ",
formatTerritory(AllGangs_1.AllGangs[props.gang.facName].territory),
"%",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
gangNames.map(name => otherGangTerritory(name))))));
}
exports.TerritorySubpage = TerritorySubpage;
/***/ }),
/* 944 */
/*!**************************************!*\
!*** ./src/Gang/ui/RecruitPopup.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecruitPopup = void 0;
/**
* React Component for the popup used to recruit new gang members.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
function RecruitPopup(props) {
const [name, setName] = react_1.useState("");
function recruit() {
if (name === "") {
DialogBox_1.dialogBoxCreate("You must enter a name for your Gang member!");
return;
}
if (!props.gang.canRecruitMember()) {
DialogBox_1.dialogBoxCreate("You cannot recruit another Gang member!");
return;
}
// At this point, the only way this can fail is if you already
// have a gang member with the same name
if (!props.gang.recruitMember(name)) {
DialogBox_1.dialogBoxCreate("You already have a gang member with this name!");
return;
}
props.onRecruit();
createPopup_1.removePopup(props.popupId);
}
function cancel() {
createPopup_1.removePopup(props.popupId);
}
function onKeyUp(event) {
if (event.keyCode === 13)
recruit();
if (event.keyCode === 27)
cancel();
}
function onChange(event) {
setName(event.target.value);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", { className: "noselect" }, "Enter a name for your new Gang member:"),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { autoFocus: true, onKeyUp: onKeyUp, onChange: onChange, className: "text-input noselect", type: "text", placeholder: "unique name" }),
react_1.default.createElement("a", { className: "std-button", onClick: recruit }, "Recruit Gang Member"),
react_1.default.createElement("a", { className: "std-button", onClick: cancel }, "Cancel")));
}
exports.RecruitPopup = RecruitPopup;
/***/ }),
/* 945 */
/*!***************************************!*\
!*** ./src/Gang/ui/RecruitButton.tsx ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecruitButton = void 0;
/**
* React Component for the recruitment button and text on the gang main page.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const RecruitPopup_1 = __webpack_require__(/*! ./RecruitPopup */ 944);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 678);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function RecruitButton(props) {
if (props.gang.members.length >= Constants_1.GangConstants.MaximumGangMembers) {
return (react_1.default.createElement(react_1.default.Fragment, null));
}
if (!props.gang.canRecruitMember()) {
const respect = props.gang.getRespectNeededToRecruitMember();
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { className: "a-link-button-inactive", style: { display: 'inline-block', margin: '10px' } }, "Recruit Gang Member"),
react_1.default.createElement("p", { style: { margin: '10px', color: 'red', display: 'inline-block' } },
StringHelperFunctions_1.formatNumber(respect, 2),
" respect needed to recruit next member")));
}
function onClick() {
const popupId = "recruit-gang-member-popup";
createPopup_1.createPopup(popupId, RecruitPopup_1.RecruitPopup, {
gang: props.gang,
popupId: popupId,
onRecruit: props.onRecruit,
});
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { className: "a-link-button", onClick: onClick, style: { display: 'inline-block', margin: '10px' } }, "Recruit Gang Member")));
}
exports.RecruitButton = RecruitButton;
/***/ }),
/* 946 */
/*!*****************************************!*\
!*** ./src/Gang/ui/TaskDescription.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDescription = void 0;
/**
* React Component for left side of the gang member accordion, contains the
* description of the task that member is currently doing.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const GangMemberTasks_1 = __webpack_require__(/*! ../GangMemberTasks */ 285);
function TaskDescription(props) {
const task = GangMemberTasks_1.GangMemberTasks[props.member.task];
const desc = task ? task.desc : GangMemberTasks_1.GangMemberTasks["Unassigned"].desc;
return (react_1.default.createElement("p", { className: "inline noselect", dangerouslySetInnerHTML: { __html: desc } }));
}
exports.TaskDescription = TaskDescription;
/***/ }),
/* 947 */
/*!**************************************!*\
!*** ./src/Gang/ui/TaskSelector.tsx ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskSelector = void 0;
/**
* React Component for the middle part of the gang member accordion. Contains
* the task selector as well as some stats.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const StatsTable_1 = __webpack_require__(/*! ../../ui/React/StatsTable */ 275);
const MoneyRate_1 = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
function TaskSelector(props) {
const [currentTask, setCurrentTask] = react_1.useState(props.member.task);
function onChange(event) {
const task = event.target.value;
props.member.assignToTask(task);
setCurrentTask(task);
props.onTaskChange();
}
const tasks = props.gang.getAllTaskNames();
const data = [
[`Money:`, MoneyRate_1.MoneyRate(5 * props.member.calculateMoneyGain(props.gang))],
[`Respect:`, `${numeralFormat_1.numeralWrapper.formatRespect(5 * props.member.calculateRespectGain(props.gang))} / sec`],
[`Wanted Level:`, `${numeralFormat_1.numeralWrapper.formatWanted(5 * props.member.calculateWantedLevelGain(props.gang))} / sec`],
[`Total Respect:`, `${numeralFormat_1.numeralWrapper.formatRespect(props.member.earnedRespect)}`],
];
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("select", { onChange: onChange, className: "dropdown noselect", value: currentTask },
react_1.default.createElement("option", { key: 0, value: "---" }, "---"),
tasks.map((task, i) => react_1.default.createElement("option", { key: i + 1, value: task }, task))),
react_1.default.createElement("div", null, StatsTable_1.StatsTable(data))));
}
exports.TaskSelector = TaskSelector;
/***/ }),
/* 948 */
/*!****************************************!*\
!*** ./src/Gang/ui/AscensionPopup.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AscensionPopup = void 0;
/**
* React Component for the content of the popup before the player confirms the
* ascension of a gang member.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
function AscensionPopup(props) {
const setRerender = react_1.useState(false)[1];
react_1.useEffect(() => {
const id = setInterval(() => setRerender(old => !old), 1000);
return () => clearInterval(id);
}, []);
function confirm() {
props.onAscend();
const res = props.gang.ascendMember(props.member);
DialogBox_1.dialogBoxCreate(react_1.default.createElement("p", null,
"You ascended ",
props.member.name,
"!",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Your gang lost ",
numeralFormat_1.numeralWrapper.formatRespect(res.respect),
" respect.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
props.member.name,
" gained the following stat multipliers for ascending:",
react_1.default.createElement("br", null),
"Hacking: x",
numeralFormat_1.numeralWrapper.format(res.hack, '0.000'),
react_1.default.createElement("br", null),
"Strength: x",
numeralFormat_1.numeralWrapper.format(res.str, '0.000'),
react_1.default.createElement("br", null),
"Defense: x",
numeralFormat_1.numeralWrapper.format(res.def, '0.000'),
react_1.default.createElement("br", null),
"Dexterity: x",
numeralFormat_1.numeralWrapper.format(res.dex, '0.000'),
react_1.default.createElement("br", null),
"Agility: x",
numeralFormat_1.numeralWrapper.format(res.agi, '0.000'),
react_1.default.createElement("br", null),
"Charisma: x",
numeralFormat_1.numeralWrapper.format(res.cha, '0.000'),
react_1.default.createElement("br", null)));
createPopup_1.removePopup(props.popupId);
}
function cancel() {
createPopup_1.removePopup(props.popupId);
}
const ascendBenefits = props.member.getAscensionResults();
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("pre", null,
"Are you sure you want to ascend this member? They will lose all of",
react_1.default.createElement("br", null),
"their non-Augmentation upgrades and their stats will reset back to 1.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Furthermore, your gang will lose ",
numeralFormat_1.numeralWrapper.formatRespect(props.member.earnedRespect),
" respect",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"In return, they will gain the following permanent boost to stat multipliers:",
react_1.default.createElement("br", null),
"Hacking: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.hack, '0.000'),
react_1.default.createElement("br", null),
"Strength: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.str, '0.000'),
react_1.default.createElement("br", null),
"Defense: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.def, '0.000'),
react_1.default.createElement("br", null),
"Dexterity: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.dex, '0.000'),
react_1.default.createElement("br", null),
"Agility: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.agi, '0.000'),
react_1.default.createElement("br", null),
"Charisma: x",
numeralFormat_1.numeralWrapper.format(ascendBenefits.cha, '0.000'),
react_1.default.createElement("br", null)),
react_1.default.createElement("button", { className: "std-button", onClick: confirm }, "Ascend"),
react_1.default.createElement("button", { className: "std-button", onClick: cancel }, "Cancel")));
}
exports.AscensionPopup = AscensionPopup;
/***/ }),
/* 949 */
/*!*****************************************!*\
!*** ./src/Gang/ui/GangMemberStats.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberStats = void 0;
/**
* React Component for the first part of a gang member details.
* Contains skills and exp.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const AscensionPopup_1 = __webpack_require__(/*! ./AscensionPopup */ 948);
function GangMemberStats(props) {
function ascend() {
const popupId = `gang-management-ascend-member ${props.member.name}`;
createPopup_1.createPopup(popupId, AscensionPopup_1.AscensionPopup, {
member: props.member,
gang: props.gang,
popupId: popupId,
onAscend: props.onAscend,
});
}
function openAscensionHelp() {
DialogBox_1.dialogBoxCreate(react_1.default.createElement(react_1.default.Fragment, null,
"Ascending a Gang Member resets the member's progress and stats in exchange for a permanent boost to their stat multipliers.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"The additional stat multiplier that the Gang Member gains upon ascension is based on the amount of exp they have.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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."));
}
const asc = {
hack: props.member.calculateAscensionMult(props.member.hack_asc_points),
str: props.member.calculateAscensionMult(props.member.str_asc_points),
def: props.member.calculateAscensionMult(props.member.def_asc_points),
dex: props.member.calculateAscensionMult(props.member.dex_asc_points),
agi: props.member.calculateAscensionMult(props.member.agi_asc_points),
cha: props.member.calculateAscensionMult(props.member.cha_asc_points),
};
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("span", { className: "tooltiptext smallfont" },
"Hk: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.hack_mult * asc.hack),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.hack_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.hack),
" Asc)",
react_1.default.createElement("br", null),
"St: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.str_mult * asc.str),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.str_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.str),
" Asc)",
react_1.default.createElement("br", null),
"Df: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.def_mult * asc.def),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.def_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.def),
" Asc)",
react_1.default.createElement("br", null),
"Dx: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.dex_mult * asc.dex),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.dex_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.dex),
" Asc)",
react_1.default.createElement("br", null),
"Ag: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.agi_mult * asc.agi),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.agi_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.agi),
" Asc)",
react_1.default.createElement("br", null),
"Ch: x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.cha_mult * asc.cha),
"(x",
numeralFormat_1.numeralWrapper.formatMultiplier(props.member.cha_mult),
" Eq, x",
numeralFormat_1.numeralWrapper.formatMultiplier(asc.cha),
" Asc)"),
react_1.default.createElement("pre", null,
"Hacking: ",
StringHelperFunctions_1.formatNumber(props.member.hack, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.hack_exp),
" exp)",
react_1.default.createElement("br", null),
"Strength: ",
StringHelperFunctions_1.formatNumber(props.member.str, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.str_exp),
" exp)",
react_1.default.createElement("br", null),
"Defense: ",
StringHelperFunctions_1.formatNumber(props.member.def, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.def_exp),
" exp)",
react_1.default.createElement("br", null),
"Dexterity: ",
StringHelperFunctions_1.formatNumber(props.member.dex, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.dex_exp),
" exp)",
react_1.default.createElement("br", null),
"Agility: ",
StringHelperFunctions_1.formatNumber(props.member.agi, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.agi_exp),
" exp)",
react_1.default.createElement("br", null),
"Charisma: ",
StringHelperFunctions_1.formatNumber(props.member.cha, 0),
" (",
numeralFormat_1.numeralWrapper.formatExp(props.member.cha_exp),
" exp)",
react_1.default.createElement("br", null)),
react_1.default.createElement("br", null),
props.member.canAscend() && react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("button", { className: "accordion-button noselect", onClick: ascend }, "Ascend"),
react_1.default.createElement("div", { className: "help-tip noselect", style: { marginTop: "5px" }, onClick: openAscensionHelp }, "?"))));
}
exports.GangMemberStats = GangMemberStats;
/***/ }),
/* 950 */
/*!****************************************************!*\
!*** ./src/Gang/ui/GangMemberAccordionContent.tsx ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberAccordionContent = void 0;
/**
* React Component for the content of the accordion of gang members on the
* management subpage.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const GangMemberStats_1 = __webpack_require__(/*! ./GangMemberStats */ 949);
const TaskSelector_1 = __webpack_require__(/*! ./TaskSelector */ 947);
const TaskDescription_1 = __webpack_require__(/*! ./TaskDescription */ 946);
function GangMemberAccordionContent(props) {
const setRerender = react_1.useState(false)[1];
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("div", { className: "gang-member-info-div tooltip" },
react_1.default.createElement(GangMemberStats_1.GangMemberStats, { onAscend: () => setRerender(old => !old), gang: props.gang, member: props.member })),
react_1.default.createElement("div", { className: "gang-member-info-div" },
react_1.default.createElement(TaskSelector_1.TaskSelector, { onTaskChange: () => setRerender(old => !old), gang: props.gang, member: props.member })),
react_1.default.createElement("div", { className: "gang-member-info-div" },
react_1.default.createElement(TaskDescription_1.TaskDescription, { member: props.member }))));
}
exports.GangMemberAccordionContent = GangMemberAccordionContent;
/***/ }),
/* 951 */
/*!*********************************************!*\
!*** ./src/Gang/ui/GangMemberAccordion.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberAccordion = void 0;
/**
* React Component for a gang member on the management subpage.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const Accordion_1 = __webpack_require__(/*! ../../ui/React/Accordion */ 161);
const GangMemberAccordionContent_1 = __webpack_require__(/*! ./GangMemberAccordionContent */ 950);
function GangMemberAccordion(props) {
return react_1.default.createElement(Accordion_1.Accordion, { panelInitiallyOpened: true, headerContent: react_1.default.createElement(react_1.default.Fragment, null, props.member.name), panelContent: react_1.default.createElement(GangMemberAccordionContent_1.GangMemberAccordionContent, { gang: props.gang, member: props.member }) });
}
exports.GangMemberAccordion = GangMemberAccordion;
/***/ }),
/* 952 */
/*!************************************************!*\
!*** ./src/Gang/ui/GangMemberUpgradePopup.tsx ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberUpgradePopup = void 0;
/**
* React Component for the popup that manages gang members upgrades
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const GangMemberUpgrades_1 = __webpack_require__(/*! ../GangMemberUpgrades */ 175);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const upgrades_1 = __webpack_require__(/*! ../data/upgrades */ 486);
function GangMemberUpgradePanel(props) {
const setRerender = react_1.useState(false)[1];
function filterUpgrades(list, type) {
return Object.keys(GangMemberUpgrades_1.GangMemberUpgrades).filter((upgName) => {
const upg = GangMemberUpgrades_1.GangMemberUpgrades[upgName];
if (props.player.money.lt(props.gang.getUpgradeCost(upg)))
return false;
if (upg.type !== type)
return false;
if (list.includes(upgName))
return false;
return true;
}).map((upgName) => GangMemberUpgrades_1.GangMemberUpgrades[upgName]);
}
const weaponUpgrades = filterUpgrades(props.member.upgrades, upgrades_1.UpgradeType.Weapon);
const armorUpgrades = filterUpgrades(props.member.upgrades, upgrades_1.UpgradeType.Armor);
const vehicleUpgrades = filterUpgrades(props.member.upgrades, upgrades_1.UpgradeType.Vehicle);
const rootkitUpgrades = filterUpgrades(props.member.upgrades, upgrades_1.UpgradeType.Rootkit);
const augUpgrades = filterUpgrades(props.member.augmentations, upgrades_1.UpgradeType.Augmentation);
function purchasedUpgrade(upgName) {
const upg = GangMemberUpgrades_1.GangMemberUpgrades[upgName];
return (react_1.default.createElement("div", { key: upgName, className: "gang-owned-upgrade tooltip" },
upg.name,
react_1.default.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: { __html: upg.desc } })));
}
function upgradeButton(upg, left = false) {
function onClick() {
props.member.buyUpgrade(upg, props.player, props.gang);
setRerender(old => !old);
}
return (react_1.default.createElement("a", { key: upg.name, className: "a-link-button tooltip", style: { margin: "2px", padding: "2px", display: "block", fontSize: "11px" }, onClick: onClick },
upg.name,
" - ",
Money_1.Money(props.gang.getUpgradeCost(upg)),
react_1.default.createElement("span", { className: left ? "tooltiptextleft" : "tooltiptext", dangerouslySetInnerHTML: { __html: upg.desc } })));
}
const asc = {
hack: props.member.calculateAscensionMult(props.member.hack_asc_points),
str: props.member.calculateAscensionMult(props.member.str_asc_points),
def: props.member.calculateAscensionMult(props.member.def_asc_points),
dex: props.member.calculateAscensionMult(props.member.dex_asc_points),
agi: props.member.calculateAscensionMult(props.member.agi_asc_points),
cha: props.member.calculateAscensionMult(props.member.cha_asc_points),
};
return (react_1.default.createElement("div", { style: { border: '1px solid white' } },
react_1.default.createElement("h1", null,
props.member.name,
"(",
props.member.task,
")"),
react_1.default.createElement("pre", { style: { fontSize: "14px", display: "inline-block", width: "20%" } },
"Hack: ",
props.member.hack,
" (x",
StringHelperFunctions_1.formatNumber(props.member.hack_mult * asc.hack, 2),
")",
react_1.default.createElement("br", null),
"Str: ",
props.member.str,
" (x",
StringHelperFunctions_1.formatNumber(props.member.str_mult * asc.str, 2),
")",
react_1.default.createElement("br", null),
"Def: ",
props.member.def,
" (x",
StringHelperFunctions_1.formatNumber(props.member.def_mult * asc.def, 2),
")",
react_1.default.createElement("br", null),
"Dex: ",
props.member.dex,
" (x",
StringHelperFunctions_1.formatNumber(props.member.dex_mult * asc.dex, 2),
")",
react_1.default.createElement("br", null),
"Agi: ",
props.member.agi,
" (x",
StringHelperFunctions_1.formatNumber(props.member.agi_mult * asc.agi, 2),
")",
react_1.default.createElement("br", null),
"Cha: ",
props.member.cha,
" (x",
StringHelperFunctions_1.formatNumber(props.member.cha_mult * asc.cha, 2),
")"),
react_1.default.createElement("div", { className: "gang-owned-upgrades-div noselect" },
"Purchased Upgrades: ",
props.member.upgrades.map((upg) => purchasedUpgrade(upg)),
props.member.augmentations.map((upg) => purchasedUpgrade(upg))),
react_1.default.createElement("div", { className: "noselect", style: { width: "20%", display: "inline-block" } },
react_1.default.createElement("h2", null, "Weapons"),
weaponUpgrades.map(upg => upgradeButton(upg))),
react_1.default.createElement("div", { className: "noselect", style: { width: "20%", display: "inline-block" } },
react_1.default.createElement("h2", null, "Armor"),
armorUpgrades.map(upg => upgradeButton(upg))),
react_1.default.createElement("div", { className: "noselect", style: { width: "20%", display: "inline-block" } },
react_1.default.createElement("h2", null, "Vehicles"),
vehicleUpgrades.map(upg => upgradeButton(upg))),
react_1.default.createElement("div", { className: "noselect", style: { width: "20%", display: "inline-block" } },
react_1.default.createElement("h2", null, "Rootkits"),
rootkitUpgrades.map(upg => upgradeButton(upg, true))),
react_1.default.createElement("div", { className: "noselect", style: { width: "20%", display: "inline-block" } },
react_1.default.createElement("h2", null, "Augmentations"),
augUpgrades.map(upg => upgradeButton(upg, true)))));
}
function GangMemberUpgradePopup(props) {
const setRerender = react_1.useState(false)[1];
const [filter, setFilter] = react_1.useState("");
function closePopup(ev) {
if (ev.keyCode !== 27)
return;
createPopup_1.removePopup(props.popupId);
}
react_1.useEffect(() => {
window.addEventListener('keydown', closePopup);
const id = setInterval(() => setRerender(old => !old), 1000);
return () => {
clearInterval(id);
window.removeEventListener('keydown', closePopup);
};
}, []);
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("input", { className: "text-input noselect", value: filter, placeholder: "Filter gang member", onChange: event => setFilter(event.target.value) }),
react_1.default.createElement("p", { className: "tooltip", style: { marginLeft: '6px', display: 'inline-block' } },
"Discount: -",
numeralFormat_1.numeralWrapper.formatPercentage(1 - 1 / props.gang.getDiscount()),
react_1.default.createElement("span", { className: "tooltiptext noselect" }, "You get a discount on equipment and upgrades based on your gang's respect and power. More respect and power leads to more discounts.")),
props.gang.members.map((member) => react_1.default.createElement(GangMemberUpgradePanel, { key: member.name, player: props.player, gang: props.gang, member: member }))));
}
exports.GangMemberUpgradePopup = GangMemberUpgradePopup;
/***/ }),
/* 953 */
/*!****************************************!*\
!*** ./src/Gang/ui/GangMemberList.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberList = void 0;
/**
* React Component for the list of gang members on the management subpage.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const GangMemberUpgradePopup_1 = __webpack_require__(/*! ./GangMemberUpgradePopup */ 952);
const GangMemberAccordion_1 = __webpack_require__(/*! ./GangMemberAccordion */ 951);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const RecruitButton_1 = __webpack_require__(/*! ./RecruitButton */ 945);
function GangMemberList(props) {
const [filter, setFilter] = react_1.useState("");
const setRerender = react_1.useState(false)[1];
function openUpgradePopup() {
const popupId = `gang-upgrade-popup`;
createPopup_1.createPopup(popupId, GangMemberUpgradePopup_1.GangMemberUpgradePopup, {
gang: props.gang,
player: props.player,
popupId: popupId,
});
}
function onFilterChange(event) {
setFilter(event.target.value);
}
const members = props.gang.members.filter((member) => member.name.indexOf(filter) > -1 || member.task.indexOf(filter) > -1);
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement(RecruitButton_1.RecruitButton, { onRecruit: () => setRerender(old => !old), gang: props.gang }),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { className: "text-input noselect", placeholder: "Filter gang member", style: { margin: "5px", padding: "5px" }, value: filter, onChange: onFilterChange }),
react_1.default.createElement("a", { className: "a-link-button", style: { display: 'inline-block' }, onClick: openUpgradePopup }, "Manage Equipment"),
react_1.default.createElement("ul", null, members.map((member) => react_1.default.createElement("li", { key: member.name },
react_1.default.createElement(GangMemberAccordion_1.GangMemberAccordion, { gang: props.gang, member: member }))))));
}
exports.GangMemberList = GangMemberList;
/***/ }),
/* 954 */
/*!***********************************!*\
!*** ./src/Gang/ui/BonusTime.tsx ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BonusTime = void 0;
/**
* React Component for displaying the bonus time remaining.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
function BonusTime(props) {
const CyclerPerSecond = 1000 / Constants_1.CONSTANTS._idleSpeed;
if (props.gang.storedCycles / CyclerPerSecond * 1000 <= 5000)
return (React.createElement(React.Fragment, null));
const bonusMillis = props.gang.storedCycles / CyclerPerSecond * 1000;
return (React.createElement(React.Fragment, null,
React.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Bonus time: ",
StringHelperFunctions_1.convertTimeMsToTimeElapsedString(bonusMillis),
React.createElement("span", { className: "tooltiptext noselect" }, "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.")),
React.createElement("br", null)));
}
exports.BonusTime = BonusTime;
/***/ }),
/* 955 */
/*!***********************************!*\
!*** ./src/Gang/ui/GangStats.tsx ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangStats = void 0;
/**
* React Component for the stats related to the gang, like total respect and
* money per second.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const Factions_1 = __webpack_require__(/*! ../../Faction/Factions */ 17);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../../utils/StringHelperFunctions */ 23);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const MoneyRate_1 = __webpack_require__(/*! ../../ui/React/MoneyRate */ 118);
const Reputation_1 = __webpack_require__(/*! ../../ui/React/Reputation */ 59);
const AllGangs_1 = __webpack_require__(/*! ../AllGangs */ 85);
const BonusTime_1 = __webpack_require__(/*! ./BonusTime */ 954);
function GangStats(props) {
const territoryMult = AllGangs_1.AllGangs[props.gang.facName].territory * 100;
let territoryStr;
if (territoryMult <= 0) {
territoryStr = StringHelperFunctions_1.formatNumber(0, 2);
}
else if (territoryMult >= 100) {
territoryStr = StringHelperFunctions_1.formatNumber(100, 2);
}
else {
territoryStr = StringHelperFunctions_1.formatNumber(territoryMult, 2);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Respect: ",
numeralFormat_1.numeralWrapper.formatRespect(props.gang.respect),
" (",
numeralFormat_1.numeralWrapper.formatRespect(5 * props.gang.respectGainRate),
" / sec)",
react_1.default.createElement("span", { className: "tooltiptext" }, "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.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Wanted Level: ",
numeralFormat_1.numeralWrapper.formatWanted(props.gang.wanted),
" (",
numeralFormat_1.numeralWrapper.formatWanted(5 * props.gang.wantedGainRate),
" / sec)",
react_1.default.createElement("span", { className: "tooltiptext" }, "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.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Wanted Level Penalty: -",
StringHelperFunctions_1.formatNumber((1 - props.gang.getWantedPenalty()) * 100, 2),
"%",
react_1.default.createElement("span", { className: "tooltiptext" }, "Penalty for respect and money gain rates due to Wanted Level")),
react_1.default.createElement("br", null),
react_1.default.createElement("div", null,
react_1.default.createElement("p", { style: { display: "inline-block" } },
"Money gain rate: ",
MoneyRate_1.MoneyRate(5 * props.gang.moneyGainRate))),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Territory: ",
territoryStr,
"%",
react_1.default.createElement("span", { className: "tooltiptext" }, "The percentage of total territory your Gang controls")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { style: { display: "inline-block" } },
"Faction reputation: ",
Reputation_1.Reputation(Factions_1.Factions[props.gang.facName].playerReputation)),
react_1.default.createElement("br", null),
react_1.default.createElement(BonusTime_1.BonusTime, { gang: props.gang })));
}
exports.GangStats = GangStats;
/***/ }),
/* 956 */
/*!*******************************************!*\
!*** ./src/Gang/ui/ManagementSubpage.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManagementSubpage = void 0;
/**
* React Component for the subpage that manages gang members, the main page.
*/
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const GangStats_1 = __webpack_require__(/*! ./GangStats */ 955);
const GangMemberList_1 = __webpack_require__(/*! ./GangMemberList */ 953);
function ManagementSubpage(props) {
return (react_1.default.createElement("div", { style: { display: 'block' } },
react_1.default.createElement("p", { className: "noselect", style: { width: "70%" } },
"This page is used to manage your gang members and get an overview of your gang's stats.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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 '",
props.gang.isHackingGang ? "Ethical Hacking" : "Vigilante Justice",
"' task to lower your wanted level.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"You can also manage your gang programmatically through Netscript using the Gang API"),
react_1.default.createElement("br", null),
react_1.default.createElement(GangStats_1.GangStats, { gang: props.gang }),
react_1.default.createElement("br", null),
react_1.default.createElement(GangMemberList_1.GangMemberList, { gang: props.gang, player: props.player })));
}
exports.ManagementSubpage = ManagementSubpage;
/***/ }),
/* 957 */
/*!******************************!*\
!*** ./src/Gang/ui/Root.tsx ***!
\******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Root = void 0;
/**
* React Component for all the gang stuff.
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const ManagementSubpage_1 = __webpack_require__(/*! ./ManagementSubpage */ 956);
const TerritorySubpage_1 = __webpack_require__(/*! ./TerritorySubpage */ 943);
const FactionHelpers_1 = __webpack_require__(/*! ../../Faction/FactionHelpers */ 71);
function Root(props) {
const [management, setManagement] = react_1.useState(true);
const setRerender = react_1.useState(false)[1];
react_1.useEffect(() => {
const id = setInterval(() => setRerender(old => !old), 1000);
return () => clearInterval(id);
}, []);
function back() {
props.engine.loadFactionContent();
FactionHelpers_1.displayFactionContent(props.gang.facName);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("a", { className: "a-link-button", style: { display: "inline-block" }, onClick: back }, "Back"),
react_1.default.createElement("a", { className: management ? "a-link-button-inactive" : "a-link-button", style: { display: "inline-block" }, onClick: () => setManagement(true) }, "Gang Management"),
react_1.default.createElement("a", { className: !management ? "a-link-button-inactive" : "a-link-button", style: { display: "inline-block" }, onClick: () => setManagement(false) }, "Gang Territory"),
management ?
react_1.default.createElement(ManagementSubpage_1.ManagementSubpage, { gang: props.gang, player: props.player }) :
react_1.default.createElement(TerritorySubpage_1.TerritorySubpage, { gang: props.gang })));
}
exports.Root = Root;
/***/ }),
/* 958 */
/*!********************************************************!*\
!*** ./src/Augmentation/ui/PurchasedAugmentations.tsx ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PurchasedAugmentations = void 0;
/**
* React component for displaying all of the player's purchased (but not installed)
* Augmentations on the Augmentations UI.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const AugmentationNames_1 = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const AugmentationAccordion_1 = __webpack_require__(/*! ../../ui/React/AugmentationAccordion */ 642);
function PurchasedAugmentations() {
const augs = [];
// Only render the last NeuroFlux (there are no findLastIndex btw)
let nfgIndex = -1;
for (let i = Player_1.Player.queuedAugmentations.length - 1; i >= 0; i--) {
if (Player_1.Player.queuedAugmentations[i].name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
nfgIndex = i;
break;
}
}
for (let i = 0; i < Player_1.Player.queuedAugmentations.length; i++) {
const ownedAug = Player_1.Player.queuedAugmentations[i];
if (ownedAug.name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor && i !== nfgIndex)
continue;
const aug = Augmentations_1.Augmentations[ownedAug.name];
let level = null;
if (ownedAug.name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
level = ownedAug.level;
}
augs.push(React.createElement("li", { key: `${ownedAug.name}${ownedAug.level}` },
React.createElement(AugmentationAccordion_1.AugmentationAccordion, { aug: aug, level: level })));
}
return (React.createElement("ul", { className: "augmentations-list" }, augs));
}
exports.PurchasedAugmentations = PurchasedAugmentations;
/***/ }),
/* 959 */
/*!***************************************************!*\
!*** ./src/Augmentation/ui/PlayerMultipliers.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayerMultipliers = void 0;
/**
* React component for displaying the player's multipliers on the Augmentation UI page
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Augmentations_1 = __webpack_require__(/*! ../Augmentations */ 12);
function calculateAugmentedStats() {
const augP = {};
for (const aug of Player_1.Player.queuedAugmentations) {
const augObj = Augmentations_1.Augmentations[aug.name];
for (const mult in augObj.mults) {
const v = augP[mult] ? augP[mult] : 1;
augP[mult] = v * augObj.mults[mult];
}
}
return augP;
}
function PlayerMultipliers() {
const mults = calculateAugmentedStats();
function MultiplierTable(rows) {
function improvements(r) {
let elems = [];
if (r) {
elems = [
React.createElement("td", { key: "2" },
"\u00A0",
"=>",
"\u00A0"),
React.createElement("td", { key: "3" }, numeralFormat_1.numeralWrapper.formatPercentage(r)),
];
}
return elems;
}
return React.createElement("table", null,
React.createElement("tbody", null, rows.map((r) => React.createElement("tr", { key: r[0] },
React.createElement("td", { key: "0" },
React.createElement("span", null,
r[0],
" multiplier:\u00A0")),
React.createElement("td", { key: "1", style: { textAlign: 'right' } }, numeralFormat_1.numeralWrapper.formatPercentage(r[1])),
improvements(r[2])))));
}
function BladeburnerMults() {
if (!Player_1.Player.canAccessBladeburner())
return (React.createElement(React.Fragment, null));
return (React.createElement(React.Fragment, null,
MultiplierTable([
['Bladeburner Success Chance', Player_1.Player.bladeburner_success_chance_mult, Player_1.Player.bladeburner_success_chance_mult * mults.bladeburner_success_chance_mult],
['Bladeburner Max Stamina', Player_1.Player.bladeburner_max_stamina_mult, Player_1.Player.bladeburner_max_stamina_mult * mults.bladeburner_max_stamina_mult],
['Bladeburner Stamina Gain', Player_1.Player.bladeburner_stamina_gain_mult, Player_1.Player.bladeburner_stamina_gain_mult * mults.bladeburner_stamina_gain_mult],
['Bladeburner Field Analysis', Player_1.Player.bladeburner_analysis_mult, Player_1.Player.bladeburner_analysis_mult * mults.bladeburner_analysis_mult],
]),
React.createElement("br", null)));
}
return (React.createElement(React.Fragment, null,
React.createElement("p", null,
React.createElement("strong", null,
React.createElement("u", null, "Multipliers:"))),
React.createElement("br", null),
MultiplierTable([
['Hacking Chance ', Player_1.Player.hacking_chance_mult, Player_1.Player.hacking_chance_mult * mults.hacking_chance_mult],
['Hacking Speed ', Player_1.Player.hacking_speed_mult, Player_1.Player.hacking_speed_mult * mults.hacking_speed_mult],
['Hacking Money ', Player_1.Player.hacking_money_mult, Player_1.Player.hacking_money_mult * mults.hacking_money_mult],
['Hacking Growth ', Player_1.Player.hacking_grow_mult, Player_1.Player.hacking_grow_mult * mults.hacking_grow_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Hacking Level ', Player_1.Player.hacking_mult, Player_1.Player.hacking_mult * mults.hacking_mult],
['Hacking Experience ', Player_1.Player.hacking_exp_mult, Player_1.Player.hacking_exp_mult * mults.hacking_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Strength Level ', Player_1.Player.strength_mult, Player_1.Player.strength_mult * mults.strength_mult],
['Strength Experience ', Player_1.Player.strength_exp_mult, Player_1.Player.strength_exp_mult * mults.strength_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Defense Level ', Player_1.Player.defense_mult, Player_1.Player.defense_mult * mults.defense_mult],
['Defense Experience ', Player_1.Player.defense_exp_mult, Player_1.Player.defense_exp_mult * mults.defense_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Dexterity Level ', Player_1.Player.dexterity_mult, Player_1.Player.dexterity_mult * mults.dexterity_mult],
['Dexterity Experience ', Player_1.Player.dexterity_exp_mult, Player_1.Player.dexterity_exp_mult * mults.dexterity_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Agility Level ', Player_1.Player.agility_mult, Player_1.Player.agility_mult * mults.agility_mult],
['Agility Experience ', Player_1.Player.agility_exp_mult, Player_1.Player.agility_exp_mult * mults.agility_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Charisma Level ', Player_1.Player.charisma_mult, Player_1.Player.charisma_mult * mults.charisma_mult],
['Charisma Experience ', Player_1.Player.charisma_exp_mult, Player_1.Player.charisma_exp_mult * mults.charisma_exp_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Hacknet Node production ', Player_1.Player.hacknet_node_money_mult, Player_1.Player.hacknet_node_money_mult * mults.hacknet_node_money_mult],
['Hacknet Node purchase cost ', Player_1.Player.hacknet_node_purchase_cost_mult, Player_1.Player.hacknet_node_purchase_cost_mult * mults.hacknet_node_purchase_cost_mult],
['Hacknet Node RAM upgrade cost ', Player_1.Player.hacknet_node_ram_cost_mult, Player_1.Player.hacknet_node_ram_cost_mult * mults.hacknet_node_ram_cost_mult],
['Hacknet Node Core purchase cost ', Player_1.Player.hacknet_node_core_cost_mult, Player_1.Player.hacknet_node_core_cost_mult * mults.hacknet_node_core_cost_mult],
['Hacknet Node level upgrade cost ', Player_1.Player.hacknet_node_level_cost_mult, Player_1.Player.hacknet_node_level_cost_mult * mults.hacknet_node_level_cost_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Company reputation gain ', Player_1.Player.company_rep_mult, Player_1.Player.company_rep_mult * mults.company_rep_mult],
['Faction reputation gain ', Player_1.Player.faction_rep_mult, Player_1.Player.faction_rep_mult * mults.faction_rep_mult],
['Salary ', Player_1.Player.work_money_mult, Player_1.Player.work_money_mult * mults.work_money_mult],
]),
React.createElement("br", null),
MultiplierTable([
['Crime success ', Player_1.Player.crime_success_mult, Player_1.Player.crime_success_mult * mults.crime_success_mult],
['Crime money ', Player_1.Player.crime_money_mult, Player_1.Player.crime_money_mult * mults.crime_money_mult],
]),
React.createElement("br", null),
React.createElement(BladeburnerMults, null)));
}
exports.PlayerMultipliers = PlayerMultipliers;
/***/ }),
/* 960 */
/*!**************************************************!*\
!*** ./src/Augmentation/ui/SourceFileMinus1.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceFileMinus1 = void 0;
/**
* React Component for displaying a list of the player's Source-Files
* on the Augmentations UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const Exploit_1 = __webpack_require__(/*! ../../Exploits/Exploit */ 168);
const Accordion_1 = __webpack_require__(/*! ../../ui/React/Accordion */ 161);
function SourceFileMinus1() {
const exploits = Player_1.Player.exploits;
if (exploits.length === 0) {
return React.createElement(React.Fragment, null);
}
return (React.createElement("li", { key: -1 },
React.createElement(Accordion_1.Accordion, { headerContent: React.createElement(React.Fragment, null,
"Source-File -1: Exploits in the BitNodes",
React.createElement("br", null),
"Level ",
exploits.length,
" / ?"), panelContent: React.createElement(React.Fragment, null,
React.createElement("p", null, "This Source-File can only be acquired with obscure knowledge of the game, javascript, and the web ecosystem."),
React.createElement("p", null, "It increases all of the player's multipliers by 0.1%"),
React.createElement("br", null),
React.createElement("p", null, "You have found the following exploits:"),
React.createElement("ul", null, exploits.map((c) => React.createElement("li", { key: c },
"* ",
Exploit_1.ExploitName(c))))) })));
}
exports.SourceFileMinus1 = SourceFileMinus1;
/***/ }),
/* 961 */
/*!**********************************************!*\
!*** ./src/ui/React/SourceFileAccordion.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceFileAccordion = void 0;
/**
* React Component for displaying a single Source-File as an accordion.
*
* The header of the accordion contains the Source-Files's name and level,
* and the accordion's panel contains the Source-File's description.
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Accordion_1 = __webpack_require__(/*! ./Accordion */ 161);
function SourceFileAccordion(props) {
const maxLevel = props.sf.n === 12 ? "∞" : "3";
return (React.createElement(Accordion_1.Accordion, { headerContent: React.createElement(React.Fragment, null,
props.sf.name,
React.createElement("br", null),
`Level ${props.level} / ${maxLevel}`), panelContent: React.createElement("p", { dangerouslySetInnerHTML: { __html: props.sf.info } }) }));
}
exports.SourceFileAccordion = SourceFileAccordion;
/***/ }),
/* 962 */
/*!**************************************************!*\
!*** ./src/Augmentation/ui/OwnedSourceFiles.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OwnedSourceFiles = void 0;
/**
* React Component for displaying a list of the player's Source-Files
* on the Augmentations UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const SettingEnums_1 = __webpack_require__(/*! ../../Settings/SettingEnums */ 222);
const SourceFiles_1 = __webpack_require__(/*! ../../SourceFile/SourceFiles */ 227);
const SourceFileAccordion_1 = __webpack_require__(/*! ../../ui/React/SourceFileAccordion */ 961);
function OwnedSourceFiles() {
const sourceSfs = Player_1.Player.sourceFiles.slice();
if (Settings_1.Settings.OwnedAugmentationsOrder === SettingEnums_1.OwnedAugmentationsOrderSetting.Alphabetically) {
sourceSfs.sort((sf1, sf2) => {
return sf1.n - sf2.n;
});
}
const sfs = sourceSfs.map((e) => {
const srcFileKey = "SourceFile" + e.n;
const sfObj = SourceFiles_1.SourceFiles[srcFileKey];
if (sfObj == null) {
console.error(`Invalid source file number: ${e.n}`);
return null;
}
return (React.createElement("li", { key: e.n },
React.createElement(SourceFileAccordion_1.SourceFileAccordion, { level: e.lvl, sf: sfObj })));
});
return (React.createElement(React.Fragment, null, sfs));
}
exports.OwnedSourceFiles = OwnedSourceFiles;
/***/ }),
/* 963 */
/*!***************************************************!*\
!*** ./src/Augmentation/ui/ListConfiguration.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListConfiguration = void 0;
/**
* React Component for configuring the way installed augmentations and
* Source-Files are displayed in the Augmentations UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
function ListConfiguration(props) {
return (React.createElement(React.Fragment, null,
React.createElement(StdButton_1.StdButton, { onClick: props.expandAllButtonsFn, text: "Expand All" }),
React.createElement(StdButton_1.StdButton, { onClick: props.collapseAllButtonsFn, text: "Collapse All" }),
React.createElement(StdButton_1.StdButton, { onClick: props.sortInOrderFn, text: "Sort in Order", tooltip: "Sorts the Augmentations alphabetically and Source-Files in numeral order" }),
React.createElement(StdButton_1.StdButton, { onClick: props.sortByAcquirementTimeFn, text: "Sort by Acquirement Time", tooltip: "Sorts the Augmentations and Source-Files based on when you acquired them (same as default)" })));
}
exports.ListConfiguration = ListConfiguration;
/***/ }),
/* 964 */
/*!*************************************************!*\
!*** ./src/Locations/data/LocationsMetadata.ts ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocationsMetadata = void 0;
/**
* Metadata for constructing Location objects for all Locations
* in the game
*/
const CityNames_1 = __webpack_require__(/*! ./CityNames */ 42);
const LocationNames_1 = __webpack_require__(/*! ./LocationNames */ 40);
const LocationTypeEnum_1 = __webpack_require__(/*! ../LocationTypeEnum */ 477);
exports.LocationsMetadata = [
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 12,
startingSecurityLevel: 8.18,
},
name: LocationNames_1.LocationName.AevumAeroCorp,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 15,
startingSecurityLevel: 8.19,
},
name: LocationNames_1.LocationName.AevumBachmanAndAssociates,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 18,
startingSecurityLevel: 9.55,
},
name: LocationNames_1.LocationName.AevumClarkeIncorporated,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
costMult: 3,
expMult: 2,
name: LocationNames_1.LocationName.AevumCrushFitnessGym,
types: [LocationTypeEnum_1.LocationType.Gym],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 37,
startingSecurityLevel: 17.02,
},
name: LocationNames_1.LocationName.AevumECorp,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 512,
techVendorMinRam: 128,
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 15.54,
},
name: LocationNames_1.LocationName.AevumFulcrumTechnologies,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 1024,
techVendorMinRam: 256,
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 12,
startingSecurityLevel: 7.89,
},
name: LocationNames_1.LocationName.AevumGalacticCybersystems,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 6,
startingSecurityLevel: 3.29,
},
name: LocationNames_1.LocationName.AevumNetLinkTechnologies,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 64,
techVendorMinRam: 8,
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 6,
startingSecurityLevel: 5.35,
},
name: LocationNames_1.LocationName.AevumPolice,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 5,
startingSecurityLevel: 5.02,
},
name: LocationNames_1.LocationName.AevumRhoConstruction,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
costMult: 10,
expMult: 5,
name: LocationNames_1.LocationName.AevumSnapFitnessGym,
types: [LocationTypeEnum_1.LocationType.Gym],
},
{
city: CityNames_1.CityName.Aevum,
costMult: 4,
expMult: 3,
name: LocationNames_1.LocationName.AevumSummitUniversity,
types: [LocationTypeEnum_1.LocationType.University],
},
{
city: CityNames_1.CityName.Aevum,
infiltrationData: {
maxClearanceLevel: 7,
startingSecurityLevel: 5.85,
},
name: LocationNames_1.LocationName.AevumWatchdogSecurity,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Aevum,
name: LocationNames_1.LocationName.AevumCasino,
types: [LocationTypeEnum_1.LocationType.Casino],
},
{
city: CityNames_1.CityName.Chongqing,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 16.25,
},
name: LocationNames_1.LocationName.ChongqingKuaiGongInternational,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Chongqing,
infiltrationData: {
maxClearanceLevel: 18,
startingSecurityLevel: 12.59,
},
name: LocationNames_1.LocationName.ChongqingSolarisSpaceSystems,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Ishima,
infiltrationData: {
maxClearanceLevel: 12,
startingSecurityLevel: 5.02,
},
name: LocationNames_1.LocationName.IshimaNovaMedical,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Ishima,
infiltrationData: {
maxClearanceLevel: 10,
startingSecurityLevel: 3.2,
},
name: LocationNames_1.LocationName.IshimaOmegaSoftware,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 128,
techVendorMinRam: 4,
},
{
city: CityNames_1.CityName.Ishima,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 5.38,
},
name: LocationNames_1.LocationName.IshimaStormTechnologies,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 512,
techVendorMinRam: 32,
},
{
city: CityNames_1.CityName.NewTokyo,
infiltrationData: {
maxClearanceLevel: 17,
startingSecurityLevel: 7.18,
},
name: LocationNames_1.LocationName.NewTokyoDefComm,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.NewTokyo,
infiltrationData: {
maxClearanceLevel: 20,
startingSecurityLevel: 5.9,
},
name: LocationNames_1.LocationName.NewTokyoGlobalPharmaceuticals,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.NewTokyo,
infiltrationData: {
maxClearanceLevel: 5,
startingSecurityLevel: 2.5,
},
name: LocationNames_1.LocationName.NewTokyoNoodleBar,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.Special],
},
{
city: CityNames_1.CityName.NewTokyo,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 5.52,
},
name: LocationNames_1.LocationName.NewTokyoVitaLife,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.Special],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 10,
startingSecurityLevel: 3.62,
},
name: LocationNames_1.LocationName.Sector12AlphaEnterprises,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 8,
techVendorMinRam: 2,
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 10.59,
},
name: LocationNames_1.LocationName.Sector12BladeIndustries,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
name: LocationNames_1.LocationName.Sector12CIA,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 15,
startingSecurityLevel: 4.66,
},
name: LocationNames_1.LocationName.Sector12CarmichaelSecurity,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
name: LocationNames_1.LocationName.Sector12CityHall,
types: [LocationTypeEnum_1.LocationType.Special],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 12,
startingSecurityLevel: 5.9,
},
name: LocationNames_1.LocationName.Sector12DeltaOne,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
name: LocationNames_1.LocationName.Sector12FoodNStuff,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 8.18,
},
name: LocationNames_1.LocationName.Sector12FourSigma,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 17,
startingSecurityLevel: 6.02,
},
name: LocationNames_1.LocationName.Sector12IcarusMicrosystems,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
expMult: 1,
costMult: 1,
name: LocationNames_1.LocationName.Sector12IronGym,
types: [LocationTypeEnum_1.LocationType.Gym],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 5,
startingSecurityLevel: 3.13,
},
name: LocationNames_1.LocationName.Sector12JoesGuns,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 31,
startingSecurityLevel: 16.36,
},
name: LocationNames_1.LocationName.Sector12MegaCorp,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Sector12,
name: LocationNames_1.LocationName.Sector12NSA,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.Special],
},
{
city: CityNames_1.CityName.Sector12,
costMult: 20,
expMult: 10,
name: LocationNames_1.LocationName.Sector12PowerhouseGym,
types: [LocationTypeEnum_1.LocationType.Gym],
},
{
city: CityNames_1.CityName.Sector12,
costMult: 3,
expMult: 2,
name: LocationNames_1.LocationName.Sector12RothmanUniversity,
types: [LocationTypeEnum_1.LocationType.University],
},
{
city: CityNames_1.CityName.Sector12,
infiltrationData: {
maxClearanceLevel: 12,
startingSecurityLevel: 5.9,
},
name: LocationNames_1.LocationName.Sector12UniversalEnergy,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 15,
startingSecurityLevel: 3.59,
},
name: LocationNames_1.LocationName.VolhavenCompuTek,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 256,
techVendorMinRam: 8,
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 18,
startingSecurityLevel: 7.28,
},
name: LocationNames_1.LocationName.VolhavenHeliosLabs,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 15,
startingSecurityLevel: 4.35,
},
name: LocationNames_1.LocationName.VolhavenLexoCorp,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
costMult: 7,
expMult: 4,
name: LocationNames_1.LocationName.VolhavenMilleniumFitnessGym,
types: [LocationTypeEnum_1.LocationType.Gym],
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 50,
startingSecurityLevel: 8.53,
},
name: LocationNames_1.LocationName.VolhavenNWO,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 25,
startingSecurityLevel: 7.74,
},
name: LocationNames_1.LocationName.VolhavenOmniTekIncorporated,
types: [LocationTypeEnum_1.LocationType.Company, LocationTypeEnum_1.LocationType.TechVendor],
techVendorMaxRam: 1024,
techVendorMinRam: 128,
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 22,
startingSecurityLevel: 6,
},
name: LocationNames_1.LocationName.VolhavenOmniaCybersystems,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
infiltrationData: {
maxClearanceLevel: 18,
startingSecurityLevel: 4.77,
},
name: LocationNames_1.LocationName.VolhavenSysCoreSecurities,
types: [LocationTypeEnum_1.LocationType.Company],
},
{
city: CityNames_1.CityName.Volhaven,
costMult: 5,
expMult: 4,
name: LocationNames_1.LocationName.VolhavenZBInstituteOfTechnology,
types: [LocationTypeEnum_1.LocationType.University],
},
{
city: null,
name: LocationNames_1.LocationName.Hospital,
types: [LocationTypeEnum_1.LocationType.Hospital],
},
{
city: null,
name: LocationNames_1.LocationName.Slums,
types: [LocationTypeEnum_1.LocationType.Slums],
},
{
city: null,
name: LocationNames_1.LocationName.TravelAgency,
types: [LocationTypeEnum_1.LocationType.TravelAgency],
},
{
city: null,
name: LocationNames_1.LocationName.WorldStockExchange,
types: [LocationTypeEnum_1.LocationType.StockMarket],
},
];
/***/ }),
/* 965 */
/*!***********************************!*\
!*** ./src/Locations/Location.ts ***!
\***********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Location = void 0;
const LocationNames_1 = __webpack_require__(/*! ./data/LocationNames */ 40);
class Location {
constructor(p) {
/**
* Name of city this location is in. If this property is null, it means this i
* is a generic location that is available in all cities
*/
this.city = null;
/**
* Cost multiplier that influences how expensive a gym/university is
*/
this.costMult = 0;
/**
* Exp multiplier that influences how effective a gym/university is
*/
this.expMult = 0;
/**
* Identifier for location
*/
this.name = LocationNames_1.LocationName.Void;
/**
* List of what type(s) this location is. A location can be multiple types
* (e.g. company and tech vendor)
*/
this.types = [];
/**
* Tech vendors allow you to purchase servers.
* This property defines the max RAM server you can purchase from this vendor
*/
this.techVendorMaxRam = 0;
/**
* Tech vendors allow you to purchase servers.
* This property defines the max RAM server you can purchase from this vendor
*/
this.techVendorMinRam = 0;
if (p.city) {
this.city = p.city;
}
if (p.costMult) {
this.costMult = p.costMult;
}
if (p.expMult) {
this.expMult = p.expMult;
}
if (p.infiltrationData) {
this.infiltrationData = p.infiltrationData;
}
if (p.name) {
this.name = p.name;
}
if (p.types) {
this.types = p.types;
}
if (p.techVendorMaxRam) {
this.techVendorMaxRam = p.techVendorMaxRam;
}
if (p.techVendorMinRam) {
this.techVendorMinRam = p.techVendorMinRam;
}
}
}
exports.Location = Location;
/***/ }),
/* 966 */
/*!*******************************!*\
!*** ./src/Locations/City.ts ***!
\*******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.City = void 0;
class City {
constructor(name, locations = [], asciiArt = '') {
this.name = name;
this.locations = locations;
this.asciiArt = asciiArt;
}
addLocation(loc) {
this.locations.push(loc);
}
}
exports.City = City;
/***/ }),
/* 967 */
/*!**************************************!*\
!*** ./src/SourceFile/SourceFile.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceFile = void 0;
const BitNode_1 = __webpack_require__(/*! ../BitNode/BitNode */ 127);
class SourceFile {
constructor(number, info = "") {
this.lvl = 1;
this.owned = false;
const bitnodeKey = "BitNode" + number;
const bitnode = BitNode_1.BitNodes[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.info = info;
}
}
exports.SourceFile = SourceFile;
/***/ }),
/* 968 */,
/* 969 */,
/* 970 */,
/* 971 */,
/* 972 */,
/* 973 */,
/* 974 */,
/* 975 */,
/* 976 */,
/* 977 */,
/* 978 */,
/* 979 */,
/* 980 */,
/* 981 */
/*!****************************************!*\
!*** ./src/ui/React/ErrorBoundary.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorBoundary = void 0;
/**
* React Component for a simple Error Boundary. The fallback UI for
* this error boundary is simply a bordered text box
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const EventEmitter_1 = __webpack_require__(/*! ../../utils/EventEmitter */ 487);
// TODO: Move this out to a css file
const styleMarkup = {
border: "1px solid red",
display: "inline-block",
margin: "4px",
padding: "4px",
};
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
errorInfo: "",
hasError: false,
};
}
componentDidCatch(error, info) {
console.error(`Caught error in React ErrorBoundary. Component stack:`);
console.error(info.componentStack);
}
componentDidMount() {
const cb = () => {
this.setState({
hasError: false,
});
};
if (this.hasEventEmitter()) {
this.props.eventEmitterForReset.addSubscriber({
cb: cb,
id: this.props.id,
});
}
}
componentWillUnmount() {
if (this.hasEventEmitter()) {
this.props.eventEmitterForReset.removeSubscriber(this.props.id);
}
}
hasEventEmitter() {
return this.props.eventEmitterForReset != null &&
this.props.eventEmitterForReset instanceof EventEmitter_1.EventEmitter &&
this.props.id != null &&
typeof this.props.id === "string";
}
render() {
if (this.state.hasError) {
return (React.createElement("div", { style: styleMarkup },
React.createElement("p", null, `Error rendering UI. This is (probably) a bug. Please report to game developer.`),
React.createElement("p", null, `In the meantime, try refreshing the game WITHOUT saving.`),
React.createElement("p", null, `Error info: ${this.state.errorInfo}`)));
}
return this.props.children;
}
static getDerivedStateFromError(error) {
return {
errorInfo: error.message,
hasError: true,
};
}
}
exports.ErrorBoundary = ErrorBoundary;
/***/ }),
/* 982 */
/*!***************************************************!*\
!*** ./src/StockMarket/ui/StockTickersConfig.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickersConfig = exports.TickerDisplayMode = void 0;
/**
* React component for the tickers configuration section of the Stock Market UI.
* This config lets you change the way stock tickers are displayed (watchlist,
* all/portoflio mode, etc)
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
var TickerDisplayMode;
(function (TickerDisplayMode) {
TickerDisplayMode[TickerDisplayMode["AllStocks"] = 0] = "AllStocks";
TickerDisplayMode[TickerDisplayMode["Portfolio"] = 1] = "Portfolio";
})(TickerDisplayMode = exports.TickerDisplayMode || (exports.TickerDisplayMode = {}));
class StockTickersConfig extends React.Component {
constructor(props) {
super(props);
}
renderDisplayModeButton() {
let txt = "";
let tooltip = "";
if (this.props.tickerDisplayMode === TickerDisplayMode.Portfolio) {
txt = "Switch to 'All Stocks' Mode";
tooltip = "Displays all stocks on the WSE";
}
else {
txt = "Switch to 'Portfolio' Mode";
tooltip = "Displays only the stocks for which you have shares or orders";
}
return (React.createElement(StdButton_1.StdButton, { onClick: this.props.changeDisplayMode, text: txt, tooltip: tooltip }));
}
render() {
return (React.createElement("div", null,
this.renderDisplayModeButton(),
React.createElement(StdButton_1.StdButton, { onClick: this.props.expandAllTickers, text: "Expand Tickers" }),
React.createElement(StdButton_1.StdButton, { onClick: this.props.collapseAllTickers, text: "Collapse Tickers" }),
React.createElement("input", { className: "text-input", id: "stock-market-watchlist-filter", onChange: this.props.changeWatchlistFilter, placeholder: "Filter Stocks by symbol (comma-separated list)", type: "text" })));
}
}
exports.StockTickersConfig = StockTickersConfig;
/***/ }),
/* 983 */
/*!****************************************************!*\
!*** ./src/StockMarket/ui/StockTickerTxButton.tsx ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickerTxButton = void 0;
/**
* React Component for a button that initiates a transaction on the Stock Market UI
* (Buy, Sell, Buy Max, etc.)
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
function StockTickerTxButton(props) {
let className = "stock-market-input std-button";
const hasTooltip = (props.tooltip != null);
if (hasTooltip) {
className += " tooltip";
}
return (React.createElement("button", { className: className, onClick: props.onClick },
props.text,
props.tooltip != null &&
React.createElement("span", { className: "tooltiptext" }, props.tooltip)));
}
exports.StockTickerTxButton = StockTickerTxButton;
/***/ }),
/* 984 */
/*!********************************************************!*\
!*** ./src/StockMarket/ui/StockTickerPositionText.tsx ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickerPositionText = void 0;
/**
* React Component for the text on a stock ticker that display's information
* about the player's position in that stock
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const SourceFileFlags_1 = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
const blockStyleMarkup = {
display: "block",
};
class StockTickerPositionText extends React.Component {
renderLongPosition() {
const stock = this.props.stock;
// Caculate total returns
const totalCost = stock.playerShares * stock.playerAvgPx;
const gains = (stock.getBidPrice() - stock.playerAvgPx) * stock.playerShares;
let percentageGains = gains / totalCost;
if (isNaN(percentageGains)) {
percentageGains = 0;
}
return (React.createElement("div", null,
React.createElement("h3", { className: "tooltip" },
"Long Position:",
React.createElement("span", { className: "tooltiptext" }, "Shares in the long position will increase in value if the price of the corresponding stock increases")),
React.createElement("br", null),
React.createElement("p", null,
"Shares: ",
numeralFormat_1.numeralWrapper.formatShares(stock.playerShares)),
React.createElement("br", null),
React.createElement("p", null,
"Average Price: ",
Money_1.Money(stock.playerAvgPx),
" (Total Cost: ",
Money_1.Money(totalCost),
")"),
React.createElement("br", null),
React.createElement("p", null,
"Profit: ",
Money_1.Money(gains),
" (",
numeralFormat_1.numeralWrapper.formatPercentage(percentageGains),
")"),
React.createElement("br", null)));
}
renderShortPosition() {
const stock = this.props.stock;
// Caculate total returns
const totalCost = stock.playerShortShares * stock.playerAvgShortPx;
const gains = (stock.playerAvgShortPx - stock.getAskPrice()) * stock.playerShortShares;
let percentageGains = gains / totalCost;
if (isNaN(percentageGains)) {
percentageGains = 0;
}
if (this.props.p.bitNodeN === 8 || (SourceFileFlags_1.SourceFileFlags[8] >= 2)) {
return (React.createElement("div", null,
React.createElement("h3", { className: "tooltip" },
"Short Position:",
React.createElement("span", { className: "tooltiptext" }, "Shares in the short position will increase in value if the price of the corresponding stock decreases")),
React.createElement("br", null),
React.createElement("p", null,
"Shares: ",
numeralFormat_1.numeralWrapper.formatShares(stock.playerShortShares)),
React.createElement("br", null),
React.createElement("p", null,
"Average Price: ",
Money_1.Money(stock.playerAvgShortPx),
" (Total Cost: ",
Money_1.Money(totalCost),
")"),
React.createElement("br", null),
React.createElement("p", null,
"Profit: ",
Money_1.Money(gains),
" (",
numeralFormat_1.numeralWrapper.formatPercentage(percentageGains),
")"),
React.createElement("br", null)));
}
else {
return null;
}
}
render() {
const stock = this.props.stock;
return (React.createElement("div", { className: "stock-market-position-text" },
React.createElement("p", { style: blockStyleMarkup },
"Max Shares: ",
numeralFormat_1.numeralWrapper.formatShares(stock.maxShares)),
React.createElement("p", { className: "tooltip" },
"Ask Price: ",
Money_1.Money(stock.getAskPrice()),
React.createElement("span", { className: "tooltiptext" }, "See Investopedia for details on what this is")),
React.createElement("br", null),
React.createElement("p", { className: "tooltip" },
"Bid Price: ",
Money_1.Money(stock.getBidPrice()),
React.createElement("span", { className: "tooltiptext" }, "See Investopedia for details on what this is")),
this.renderLongPosition(),
this.renderShortPosition()));
}
}
exports.StockTickerPositionText = StockTickerPositionText;
/***/ }),
/* 985 */
/*!*************************************************!*\
!*** ./src/StockMarket/ui/StockTickerOrder.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickerOrder = void 0;
/**
* React component for displaying a single order in a stock's order book
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const PositionTypes_1 = __webpack_require__(/*! ../data/PositionTypes */ 98);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
class StockTickerOrder extends React.Component {
constructor(props) {
super(props);
this.handleCancelOrderClick = this.handleCancelOrderClick.bind(this);
}
handleCancelOrderClick() {
this.props.cancelOrder({ order: this.props.order });
}
render() {
const order = this.props.order;
const posTxt = order.pos === PositionTypes_1.PositionTypes.Long ? "Long Position" : "Short Position";
const txt = React.createElement(React.Fragment, null,
order.type,
" - ",
posTxt,
" - ",
numeralFormat_1.numeralWrapper.formatShares(order.shares),
" @ ",
Money_1.Money(order.price));
return (React.createElement("li", null,
txt,
React.createElement("button", { className: "std-button stock-market-order-cancel-btn", onClick: this.handleCancelOrderClick }, "Cancel Order")));
}
}
exports.StockTickerOrder = StockTickerOrder;
/***/ }),
/* 986 */
/*!*****************************************************!*\
!*** ./src/StockMarket/ui/StockTickerOrderList.tsx ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickerOrderList = void 0;
/**
* React component for displaying a stock's order list in the Stock Market UI.
* This component resides in the stock ticker
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StockTickerOrder_1 = __webpack_require__(/*! ./StockTickerOrder */ 985);
class StockTickerOrderList extends React.Component {
render() {
const orders = [];
for (let i = 0; i < this.props.orders.length; ++i) {
const o = this.props.orders[i];
orders.push(React.createElement(StockTickerOrder_1.StockTickerOrder, { cancelOrder: this.props.cancelOrder, order: o, key: i }));
}
return (React.createElement("ul", { className: "stock-market-order-list" }, orders));
}
}
exports.StockTickerOrderList = StockTickerOrderList;
/***/ }),
/* 987 */
/*!********************************************************!*\
!*** ./src/StockMarket/data/TickerHeaderFormatData.ts ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TickerHeaderFormatData = void 0;
const StockSymbols_1 = __webpack_require__(/*! ./StockSymbols */ 284);
exports.TickerHeaderFormatData = {
longestName: 0,
longestSymbol: 0,
};
for (const key in StockSymbols_1.StockSymbols) {
exports.TickerHeaderFormatData.longestName = Math.max(key.length, exports.TickerHeaderFormatData.longestName);
exports.TickerHeaderFormatData.longestSymbol = Math.max(StockSymbols_1.StockSymbols[key].length, exports.TickerHeaderFormatData.longestSymbol);
}
/***/ }),
/* 988 */
/*!******************************************************!*\
!*** ./src/StockMarket/ui/StockTickerHeaderText.tsx ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickerHeaderText = void 0;
/**
* React Component for the text on a stock ticker's header. This text displays
* general information on the stock such as the name, symbol, price, and
* 4S Market Data
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const TickerHeaderFormatData_1 = __webpack_require__(/*! ../data/TickerHeaderFormatData */ 987);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const localesWithLongPriceFormat = [
"cs",
"lv",
"pl",
"ru",
];
function StockTickerHeaderText(props) {
const stock = props.stock;
const stockPriceFormat = numeralFormat_1.numeralWrapper.formatMoney(stock.price);
const spacesAllottedForStockPrice = localesWithLongPriceFormat.includes(Settings_1.Settings.Locale) ? 15 : 12;
const spacesAfterStockName = " ".repeat(1 + TickerHeaderFormatData_1.TickerHeaderFormatData.longestName - stock.name.length + (TickerHeaderFormatData_1.TickerHeaderFormatData.longestSymbol - stock.symbol.length));
const spacesBeforePrice = " ".repeat(spacesAllottedForStockPrice - stockPriceFormat.length);
let hdrText = `${stock.name}${spacesAfterStockName}${stock.symbol} -${spacesBeforePrice}${stockPriceFormat}`;
if (props.p.has4SData) {
hdrText += ` - Volatility: ${numeralFormat_1.numeralWrapper.formatPercentage(stock.mv / 100)} - Price Forecast: `;
let plusOrMinus = stock.b; // True for "+", false for "-"
if (stock.otlkMag < 0) {
plusOrMinus = !plusOrMinus;
}
hdrText += (plusOrMinus ? "+" : "-").repeat(Math.floor(Math.abs(stock.otlkMag) / 10) + 1);
// Debugging:
// hdrText += ` - ${stock.getAbsoluteForecast()} / ${stock.otlkMagForecast}`;
}
const styleMarkup = {
color: "#66ff33",
};
if (stock.lastPrice === stock.price) {
styleMarkup.color = "white";
}
else if (stock.lastPrice > stock.price) {
styleMarkup.color = "red";
}
return React.createElement("pre", { style: styleMarkup }, hdrText);
}
exports.StockTickerHeaderText = StockTickerHeaderText;
/***/ }),
/* 989 */
/*!********************************************!*\
!*** ./src/StockMarket/ui/StockTicker.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTicker = void 0;
/**
* React Component for a single stock ticker in the Stock Market UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StockTickerHeaderText_1 = __webpack_require__(/*! ./StockTickerHeaderText */ 988);
const StockTickerOrderList_1 = __webpack_require__(/*! ./StockTickerOrderList */ 986);
const StockTickerPositionText_1 = __webpack_require__(/*! ./StockTickerPositionText */ 984);
const StockTickerTxButton_1 = __webpack_require__(/*! ./StockTickerTxButton */ 983);
const StockMarketHelpers_1 = __webpack_require__(/*! ../StockMarketHelpers */ 288);
const OrderTypes_1 = __webpack_require__(/*! ../data/OrderTypes */ 111);
const PositionTypes_1 = __webpack_require__(/*! ../data/PositionTypes */ 98);
const SourceFileFlags_1 = __webpack_require__(/*! ../../SourceFile/SourceFileFlags */ 37);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Accordion_1 = __webpack_require__(/*! ../../ui/React/Accordion */ 161);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const YesNoBox_1 = __webpack_require__(/*! ../../../utils/YesNoBox */ 61);
var SelectorOrderType;
(function (SelectorOrderType) {
SelectorOrderType["Market"] = "Market Order";
SelectorOrderType["Limit"] = "Limit Order";
SelectorOrderType["Stop"] = "Stop Order";
})(SelectorOrderType || (SelectorOrderType = {}));
class StockTicker extends React.Component {
constructor(props) {
super(props);
this.state = {
orderType: SelectorOrderType.Market,
position: PositionTypes_1.PositionTypes.Long,
qty: "",
};
this.getBuyTransactionCostContent = this.getBuyTransactionCostContent.bind(this);
this.getSellTransactionCostContent = this.getSellTransactionCostContent.bind(this);
this.handleBuyButtonClick = this.handleBuyButtonClick.bind(this);
this.handleBuyMaxButtonClick = this.handleBuyMaxButtonClick.bind(this);
this.handleHeaderClick = this.handleHeaderClick.bind(this);
this.handleOrderTypeChange = this.handleOrderTypeChange.bind(this);
this.handlePositionTypeChange = this.handlePositionTypeChange.bind(this);
this.handleQuantityChange = this.handleQuantityChange.bind(this);
this.handleSellButtonClick = this.handleSellButtonClick.bind(this);
this.handleSellAllButtonClick = this.handleSellAllButtonClick.bind(this);
}
createPlaceOrderPopupBox(yesTxt, popupTxt, yesBtnCb) {
const yesBtn = YesNoBox_1.yesNoTxtInpBoxGetYesButton();
const noBtn = YesNoBox_1.yesNoTxtInpBoxGetNoButton();
yesBtn.innerText = yesTxt;
yesBtn.addEventListener("click", () => {
const price = parseFloat(YesNoBox_1.yesNoTxtInpBoxGetInput());
if (isNaN(price)) {
DialogBox_1.dialogBoxCreate(`Invalid input for price: ${YesNoBox_1.yesNoTxtInpBoxGetInput()}`);
return false;
}
yesBtnCb(price);
YesNoBox_1.yesNoTxtInpBoxClose();
});
noBtn.innerText = "Cancel Order";
noBtn.addEventListener("click", () => {
YesNoBox_1.yesNoTxtInpBoxClose();
});
YesNoBox_1.yesNoTxtInpBoxCreate(popupTxt);
}
getBuyTransactionCostContent() {
const stock = this.props.stock;
const qty = this.getQuantity();
if (isNaN(qty)) {
return null;
}
const cost = StockMarketHelpers_1.getBuyTransactionCost(stock, qty, this.state.position);
if (cost == null) {
return null;
}
return React.createElement(React.Fragment, null,
"Purchasing ",
numeralFormat_1.numeralWrapper.formatShares(qty),
" shares (",
this.state.position === PositionTypes_1.PositionTypes.Long ? "Long" : "Short",
") will cost ",
Money_1.Money(cost),
".");
}
getQuantity() {
return Math.round(parseFloat(this.state.qty));
}
getSellTransactionCostContent() {
const stock = this.props.stock;
const qty = this.getQuantity();
if (isNaN(qty)) {
return null;
}
if (this.state.position === PositionTypes_1.PositionTypes.Long) {
if (qty > stock.playerShares) {
return React.createElement(React.Fragment, null, "You do not have this many shares in the Long position");
}
}
else {
if (qty > stock.playerShortShares) {
return React.createElement(React.Fragment, null, "You do not have this many shares in the Short position");
}
}
const cost = StockMarketHelpers_1.getSellTransactionGain(stock, qty, this.state.position);
if (cost == null) {
return null;
}
return React.createElement(React.Fragment, null,
"Selling ",
numeralFormat_1.numeralWrapper.formatShares(qty),
" shares (",
this.state.position === PositionTypes_1.PositionTypes.Long ? "Long" : "Short",
") will result in a gain of ",
Money_1.Money(cost),
".");
}
handleBuyButtonClick() {
const shares = this.getQuantity();
if (isNaN(shares)) {
DialogBox_1.dialogBoxCreate(`Invalid input for quantity (number of shares): ${this.state.qty}`);
return;
}
switch (this.state.orderType) {
case SelectorOrderType.Market: {
if (this.state.position === PositionTypes_1.PositionTypes.Short) {
this.props.buyStockShort(this.props.stock, shares);
}
else {
this.props.buyStockLong(this.props.stock, shares);
}
this.props.rerenderAllTickers();
break;
}
case SelectorOrderType.Limit: {
this.createPlaceOrderPopupBox("Place Buy Limit Order", "Enter the price for your Limit Order", (price) => {
this.props.placeOrder(this.props.stock, shares, price, OrderTypes_1.OrderTypes.LimitBuy, this.state.position);
});
break;
}
case SelectorOrderType.Stop: {
this.createPlaceOrderPopupBox("Place Buy Stop Order", "Enter the price for your Stop Order", (price) => {
this.props.placeOrder(this.props.stock, shares, price, OrderTypes_1.OrderTypes.StopBuy, this.state.position);
});
break;
}
default:
break;
}
}
handleBuyMaxButtonClick() {
const playerMoney = this.props.p.money.toNumber();
const stock = this.props.stock;
let maxShares = StockMarketHelpers_1.calculateBuyMaxAmount(stock, this.state.position, playerMoney);
maxShares = Math.min(maxShares, Math.round(stock.maxShares - stock.playerShares - stock.playerShortShares));
switch (this.state.orderType) {
case SelectorOrderType.Market: {
if (this.state.position === PositionTypes_1.PositionTypes.Short) {
this.props.buyStockShort(stock, maxShares);
}
else {
this.props.buyStockLong(stock, maxShares);
}
this.props.rerenderAllTickers();
break;
}
default: {
DialogBox_1.dialogBoxCreate(`ERROR: 'Buy Max' only works for Market Orders`);
break;
}
}
}
handleHeaderClick(e) {
const elem = e.currentTarget;
elem.classList.toggle("active");
const panel = elem.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
}
else {
panel.style.display = "block";
}
}
handleOrderTypeChange(e) {
const val = e.target.value;
// The select value returns a string. Afaik TypeScript doesnt make it easy
// to convert that string back to an enum type so we'll just do this for now
switch (val) {
case SelectorOrderType.Limit:
this.setState({
orderType: SelectorOrderType.Limit,
});
break;
case SelectorOrderType.Stop:
this.setState({
orderType: SelectorOrderType.Stop,
});
break;
case SelectorOrderType.Market:
default:
this.setState({
orderType: SelectorOrderType.Market,
});
}
}
handlePositionTypeChange(e) {
const val = e.target.value;
if (val === PositionTypes_1.PositionTypes.Short) {
this.setState({
position: PositionTypes_1.PositionTypes.Short,
});
}
else {
this.setState({
position: PositionTypes_1.PositionTypes.Long,
});
}
}
handleQuantityChange(e) {
this.setState({
qty: e.target.value,
});
}
handleSellButtonClick() {
const shares = this.getQuantity();
if (isNaN(shares)) {
DialogBox_1.dialogBoxCreate(`Invalid input for quantity (number of shares): ${this.state.qty}`);
return;
}
switch (this.state.orderType) {
case SelectorOrderType.Market: {
if (this.state.position === PositionTypes_1.PositionTypes.Short) {
this.props.sellStockShort(this.props.stock, shares);
}
else {
this.props.sellStockLong(this.props.stock, shares);
}
this.props.rerenderAllTickers();
break;
}
case SelectorOrderType.Limit: {
this.createPlaceOrderPopupBox("Place Sell Limit Order", "Enter the price for your Limit Order", (price) => {
this.props.placeOrder(this.props.stock, shares, price, OrderTypes_1.OrderTypes.LimitSell, this.state.position);
});
break;
}
case SelectorOrderType.Stop: {
this.createPlaceOrderPopupBox("Place Sell Stop Order", "Enter the price for your Stop Order", (price) => {
this.props.placeOrder(this.props.stock, shares, price, OrderTypes_1.OrderTypes.StopSell, this.state.position);
});
break;
}
default:
break;
}
}
handleSellAllButtonClick() {
const stock = this.props.stock;
switch (this.state.orderType) {
case SelectorOrderType.Market: {
if (this.state.position === PositionTypes_1.PositionTypes.Short) {
this.props.sellStockShort(stock, stock.playerShortShares);
}
else {
this.props.sellStockLong(stock, stock.playerShares);
}
this.props.rerenderAllTickers();
break;
}
default: {
DialogBox_1.dialogBoxCreate(`ERROR: 'Sell All' only works for Market Orders`);
break;
}
}
}
// Whether the player has access to orders besides market orders (limit/stop)
hasOrderAccess() {
return (this.props.p.bitNodeN === 8 || (SourceFileFlags_1.SourceFileFlags[8] >= 3));
}
// Whether the player has access to shorting stocks
hasShortAccess() {
return (this.props.p.bitNodeN === 8 || (SourceFileFlags_1.SourceFileFlags[8] >= 2));
}
render() {
return (React.createElement("li", null,
React.createElement(Accordion_1.Accordion, { headerContent: React.createElement(StockTickerHeaderText_1.StockTickerHeaderText, { p: this.props.p, stock: this.props.stock }), panelContent: React.createElement("div", null,
React.createElement("input", { className: "stock-market-input", onChange: this.handleQuantityChange, placeholder: "Quantity (Shares)", value: this.state.qty }),
React.createElement("select", { className: "stock-market-input dropdown", onChange: this.handlePositionTypeChange, value: this.state.position },
React.createElement("option", { value: PositionTypes_1.PositionTypes.Long }, "Long"),
this.hasShortAccess() &&
React.createElement("option", { value: PositionTypes_1.PositionTypes.Short }, "Short")),
React.createElement("select", { className: "stock-market-input dropdown", onChange: this.handleOrderTypeChange, value: this.state.orderType },
React.createElement("option", { value: SelectorOrderType.Market }, SelectorOrderType.Market),
this.hasOrderAccess() &&
React.createElement("option", { value: SelectorOrderType.Limit }, SelectorOrderType.Limit),
this.hasOrderAccess() &&
React.createElement("option", { value: SelectorOrderType.Stop }, SelectorOrderType.Stop)),
React.createElement(StockTickerTxButton_1.StockTickerTxButton, { onClick: this.handleBuyButtonClick, text: "Buy", tooltip: this.getBuyTransactionCostContent() }),
React.createElement(StockTickerTxButton_1.StockTickerTxButton, { onClick: this.handleSellButtonClick, text: "Sell", tooltip: this.getSellTransactionCostContent() }),
React.createElement(StockTickerTxButton_1.StockTickerTxButton, { onClick: this.handleBuyMaxButtonClick, text: "Buy MAX" }),
React.createElement(StockTickerTxButton_1.StockTickerTxButton, { onClick: this.handleSellAllButtonClick, text: "Sell ALL" }),
React.createElement(StockTickerPositionText_1.StockTickerPositionText, { p: this.props.p, stock: this.props.stock }),
React.createElement(StockTickerOrderList_1.StockTickerOrderList, { cancelOrder: this.props.cancelOrder, orders: this.props.orders, p: this.props.p, stock: this.props.stock })) })));
}
}
exports.StockTicker = StockTicker;
/***/ }),
/* 990 */
/*!*********************************************!*\
!*** ./src/StockMarket/ui/StockTickers.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockTickers = void 0;
/**
* React Component for the Stock Market UI. This is the container for all
* of the stock tickers. It also contains the configuration for the
* stock ticker UI (watchlist filter, portfolio vs all mode, etc.)
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StockTicker_1 = __webpack_require__(/*! ./StockTicker */ 989);
const StockTickersConfig_1 = __webpack_require__(/*! ./StockTickersConfig */ 982);
const Stock_1 = __webpack_require__(/*! ../Stock */ 191);
const ErrorBoundary_1 = __webpack_require__(/*! ../../ui/React/ErrorBoundary */ 981);
class StockTickers extends React.Component {
constructor(props) {
super(props);
this.state = {
rerenderFlag: false,
tickerDisplayMode: StockTickersConfig_1.TickerDisplayMode.AllStocks,
watchlistFilter: "",
watchlistSymbols: [],
};
this.changeDisplayMode = this.changeDisplayMode.bind(this);
this.changeWatchlistFilter = this.changeWatchlistFilter.bind(this);
this.collapseAllTickers = this.collapseAllTickers.bind(this);
this.expandAllTickers = this.expandAllTickers.bind(this);
this.rerender = this.rerender.bind(this);
this.listRef = React.createRef();
}
changeDisplayMode() {
if (this.state.tickerDisplayMode === StockTickersConfig_1.TickerDisplayMode.AllStocks) {
this.setState({
tickerDisplayMode: StockTickersConfig_1.TickerDisplayMode.Portfolio,
});
}
else {
this.setState({
tickerDisplayMode: StockTickersConfig_1.TickerDisplayMode.AllStocks,
});
}
}
changeWatchlistFilter(e) {
const watchlist = e.target.value;
const sanitizedWatchlist = watchlist.replace(/\s/g, '');
this.setState({
watchlistFilter: watchlist,
});
if (sanitizedWatchlist !== "") {
this.setState({
watchlistSymbols: sanitizedWatchlist.split(","),
});
}
else {
this.setState({
watchlistSymbols: [],
});
}
}
collapseAllTickers() {
const ul = this.listRef.current;
if (ul == null) {
return;
}
const tickers = ul.getElementsByClassName("accordion-header");
for (let i = 0; i < tickers.length; ++i) {
const ticker = tickers[i];
if (!(ticker instanceof HTMLButtonElement)) {
continue;
}
if (ticker.classList.contains("active")) {
ticker.click();
}
}
}
expandAllTickers() {
const ul = this.listRef.current;
if (ul == null) {
return;
}
const tickers = ul.getElementsByClassName("accordion-header");
for (let i = 0; i < tickers.length; ++i) {
const ticker = tickers[i];
if (!(ticker instanceof HTMLButtonElement)) {
continue;
}
if (!ticker.classList.contains("active")) {
ticker.click();
}
}
}
rerender() {
this.setState((prevState) => {
return {
rerenderFlag: !prevState.rerenderFlag,
};
});
}
render() {
const tickers = [];
for (const stockMarketProp in this.props.stockMarket) {
const val = this.props.stockMarket[stockMarketProp];
if (val instanceof Stock_1.Stock) {
// Skip if there's a filter and the stock isnt in that filter
if (this.state.watchlistSymbols.length > 0 && !this.state.watchlistSymbols.includes(val.symbol)) {
continue;
}
let orders = this.props.stockMarket.Orders[val.symbol];
if (orders == null) {
orders = [];
}
// Skip if we're in portfolio mode and the player doesnt own this or have any active orders
if (this.state.tickerDisplayMode === StockTickersConfig_1.TickerDisplayMode.Portfolio) {
if (val.playerShares === 0 && val.playerShortShares === 0 && orders.length === 0) {
continue;
}
}
tickers.push(React.createElement(StockTicker_1.StockTicker, { buyStockLong: this.props.buyStockLong, buyStockShort: this.props.buyStockShort, cancelOrder: this.props.cancelOrder, key: val.symbol, orders: orders, p: this.props.p, placeOrder: this.props.placeOrder, rerenderAllTickers: this.rerender, sellStockLong: this.props.sellStockLong, sellStockShort: this.props.sellStockShort, stock: val }));
}
}
const errorBoundaryProps = {
eventEmitterForReset: this.props.eventEmitterForReset,
id: "StockTickersErrorBoundary",
};
return (React.createElement(ErrorBoundary_1.ErrorBoundary, Object.assign({}, errorBoundaryProps),
React.createElement(StockTickersConfig_1.StockTickersConfig, { changeDisplayMode: this.changeDisplayMode, changeWatchlistFilter: this.changeWatchlistFilter, collapseAllTickers: this.collapseAllTickers, expandAllTickers: this.expandAllTickers, tickerDisplayMode: this.state.tickerDisplayMode }),
React.createElement("ul", { id: "stock-market-list", ref: this.listRef }, tickers)));
}
}
exports.StockTickers = StockTickers;
/***/ }),
/* 991 */
/*!*************************************************!*\
!*** ./src/StockMarket/ui/InfoAndPurchases.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InfoAndPurchases = void 0;
/**
* React component for the Stock Market UI. This component displays
* general information about the stock market, buttons for the various purchases,
* and a link to the documentation (Investopedia)
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const StockMarketCosts_1 = __webpack_require__(/*! ../StockMarketCosts */ 245);
const Constants_1 = __webpack_require__(/*! ../../Constants */ 11);
const StdButton_1 = __webpack_require__(/*! ../../ui/React/StdButton */ 56);
const StdButtonPurchased_1 = __webpack_require__(/*! ../../ui/React/StdButtonPurchased */ 647);
const Money_1 = __webpack_require__(/*! ../../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const blockStyleMarkup = {
display: "block",
};
class InfoAndPurchases extends React.Component {
constructor(props) {
super(props);
this.handleClick4SMarketDataHelpTip = this.handleClick4SMarketDataHelpTip.bind(this);
this.purchaseWseAccount = this.purchaseWseAccount.bind(this);
this.purchaseTixApiAccess = this.purchaseTixApiAccess.bind(this);
this.purchase4SMarketData = this.purchase4SMarketData.bind(this);
this.purchase4SMarketDataTixApiAccess = this.purchase4SMarketDataTixApiAccess.bind(this);
}
handleClick4SMarketDataHelpTip() {
DialogBox_1.dialogBoxCreate("Access to the 4S Market Data feed will display two additional pieces " +
"of information about each stock: Price Forecast & Volatility
" +
"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.
" +
"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).
" +
"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.");
}
purchaseWseAccount() {
if (this.props.p.hasWseAccount) {
return;
}
if (!this.props.p.canAfford(Constants_1.CONSTANTS.WSEAccountCost)) {
return;
}
this.props.p.hasWseAccount = true;
this.props.initStockMarket();
this.props.p.loseMoney(Constants_1.CONSTANTS.WSEAccountCost);
this.props.rerender();
const worldHeader = document.getElementById("world-menu-header");
if (worldHeader instanceof HTMLElement) {
worldHeader.click();
worldHeader.click();
}
}
purchaseTixApiAccess() {
if (this.props.p.hasTixApiAccess) {
return;
}
if (!this.props.p.canAfford(Constants_1.CONSTANTS.TIXAPICost)) {
return;
}
this.props.p.hasTixApiAccess = true;
this.props.p.loseMoney(Constants_1.CONSTANTS.TIXAPICost);
this.props.rerender();
}
purchase4SMarketData() {
if (this.props.p.has4SData) {
return;
}
if (!this.props.p.canAfford(StockMarketCosts_1.getStockMarket4SDataCost())) {
return;
}
this.props.p.has4SData = true;
this.props.p.loseMoney(StockMarketCosts_1.getStockMarket4SDataCost());
this.props.rerender();
}
purchase4SMarketDataTixApiAccess() {
if (this.props.p.has4SDataTixApi) {
return;
}
if (!this.props.p.canAfford(StockMarketCosts_1.getStockMarket4STixApiCost())) {
return;
}
this.props.p.has4SDataTixApi = true;
this.props.p.loseMoney(StockMarketCosts_1.getStockMarket4STixApiCost());
this.props.rerender();
}
renderPurchaseWseAccountButton() {
if (this.props.p.hasWseAccount) {
return (React.createElement(StdButtonPurchased_1.StdButtonPurchased, { text: "WSE Account - Purchased" }));
}
else {
const cost = Constants_1.CONSTANTS.WSEAccountCost;
return (React.createElement(StdButton_1.StdButton, { disabled: !this.props.p.canAfford(cost), onClick: this.purchaseWseAccount, text: React.createElement(React.Fragment, null,
"Buy WSE Account - ",
Money_1.Money(cost)) }));
}
}
renderPurchaseTixApiAccessButton() {
if (this.props.p.hasTixApiAccess) {
return (React.createElement(StdButtonPurchased_1.StdButtonPurchased, { text: "TIX API Access - Purchased" }));
}
else {
const cost = Constants_1.CONSTANTS.TIXAPICost;
return (React.createElement(StdButton_1.StdButton, { disabled: !this.props.p.canAfford(cost) || !this.props.p.hasWseAccount, onClick: this.purchaseTixApiAccess, style: blockStyleMarkup, text: React.createElement(React.Fragment, null,
"Buy Trade Information eXchange (TIX) API Access - ",
Money_1.Money(cost)) }));
}
}
renderPurchase4SMarketDataButton() {
if (this.props.p.has4SData) {
return (React.createElement(StdButtonPurchased_1.StdButtonPurchased, { text: "4S Market Data - Purchased", tooltip: "Lets you view additional pricing and volatility information about stocks" }));
}
else {
const cost = StockMarketCosts_1.getStockMarket4SDataCost();
return (React.createElement(StdButton_1.StdButton, { disabled: !this.props.p.canAfford(cost) || !this.props.p.hasWseAccount, onClick: this.purchase4SMarketData, text: React.createElement(React.Fragment, null,
"Buy 4S Market Data Access - ",
Money_1.Money(cost)), tooltip: "Lets you view additional pricing and volatility information about stocks" }));
}
}
renderPurchase4SMarketDataTixApiAccessButton() {
if (!this.props.p.hasTixApiAccess) {
return (React.createElement(StdButton_1.StdButton, { disabled: true, text: `Buy 4S Market Data TIX API Access`, tooltip: "Requires TIX API Access" }));
}
else if (this.props.p.has4SDataTixApi) {
return (React.createElement(StdButtonPurchased_1.StdButtonPurchased, { text: "4S Market Data TIX API - Purchased", tooltip: "Let you access 4S Market Data through Netscript" }));
}
else {
const cost = StockMarketCosts_1.getStockMarket4STixApiCost();
return (React.createElement(StdButton_1.StdButton, { disabled: !this.props.p.canAfford(cost), onClick: this.purchase4SMarketDataTixApiAccess, text: React.createElement(React.Fragment, null,
"Buy 4S Market Data TIX API Access - ",
Money_1.Money(cost)), tooltip: "Let you access 4S Market Data through Netscript" }));
}
}
render() {
const documentationLink = "https://bitburner.readthedocs.io/en/latest/basicgameplay/stockmarket.html";
return (React.createElement("div", { className: "stock-market-info-and-purchases" },
React.createElement("p", null, "Welcome to the World Stock Exchange (WSE)!"),
React.createElement("button", { className: "std-button" },
React.createElement("a", { href: documentationLink, target: "_blank" }, "Investopedia")),
React.createElement("br", null),
React.createElement("p", null, "To begin trading, you must first purchase an account:"),
this.renderPurchaseWseAccountButton(),
React.createElement("h2", null, "Trade Information eXchange (TIX) API"),
React.createElement("p", null, "TIX, short for Trade Information eXchange, is the communications protocol used by the WSE. Purchasing access to the TIX API lets you write code to create your own algorithmic/automated trading strategies."),
this.renderPurchaseTixApiAccessButton(),
React.createElement("h2", null, "Four Sigma (4S) Market Data Feed"),
React.createElement("p", null, "Four Sigma's (4S) Market Data Feed provides information about stocks that will help your trading strategies."),
this.renderPurchase4SMarketDataButton(),
React.createElement("button", { className: "help-tip-big", onClick: this.handleClick4SMarketDataHelpTip }, "?"),
this.renderPurchase4SMarketDataTixApiAccessButton(),
React.createElement("p", null,
"Commission Fees: Every transaction you make has a ",
Money_1.Money(Constants_1.CONSTANTS.StockMarketCommission),
" commission fee."),
React.createElement("br", null),
React.createElement("p", null, "WARNING: When you reset after installing Augmentations, the Stock Market is reset. You will retain your WSE Account, access to the TIX API, and 4S Market Data access. However, all of your stock positions are lost, so make sure to sell your stocks before installing Augmentations!")));
}
}
exports.InfoAndPurchases = InfoAndPurchases;
/***/ }),
/* 992 */
/*!*************************************!*\
!*** ./src/StockMarket/ui/Root.tsx ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StockMarketRoot = void 0;
/**
* Root React component for the Stock Market UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const InfoAndPurchases_1 = __webpack_require__(/*! ./InfoAndPurchases */ 991);
const StockTickers_1 = __webpack_require__(/*! ./StockTickers */ 990);
class StockMarketRoot extends React.Component {
constructor(props) {
super(props);
this.state = {
rerenderFlag: false,
};
this.rerender = this.rerender.bind(this);
}
rerender() {
this.setState((prevState) => {
return {
rerenderFlag: !prevState.rerenderFlag,
};
});
}
render() {
return (React.createElement("div", null,
React.createElement(InfoAndPurchases_1.InfoAndPurchases, { initStockMarket: this.props.initStockMarket, p: this.props.p, rerender: this.rerender }),
this.props.p.hasWseAccount &&
React.createElement(StockTickers_1.StockTickers, { buyStockLong: this.props.buyStockLong, buyStockShort: this.props.buyStockShort, cancelOrder: this.props.cancelOrder, eventEmitterForReset: this.props.eventEmitterForReset, p: this.props.p, placeOrder: this.props.placeOrder, sellStockLong: this.props.sellStockLong, sellStockShort: this.props.sellStockShort, stockMarket: this.props.stockMarket })));
}
}
exports.StockMarketRoot = StockMarketRoot;
/***/ }),
/* 993 */
/*!***************************************************!*\
!*** ./src/StockMarket/data/InitStockMetadata.ts ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitStockMetadata = void 0;
/**
* Initialization metadata for all Stocks. This is used to generate the
* stock parameter values upon a reset
*
* Some notes:
* - Megacorporations have better otlkMags
* - Higher volatility -> Bigger spread
* - Lower price -> Bigger spread
* - Share tx required for movement used for balancing
*/
const StockSymbols_1 = __webpack_require__(/*! ./StockSymbols */ 284);
const LocationNames_1 = __webpack_require__(/*! ../../Locations/data/LocationNames */ 40);
exports.InitStockMetadata = [
{
b: true,
initPrice: {
max: 28e3,
min: 17e3,
},
marketCap: 2.4e12,
mv: {
divisor: 100,
max: 50,
min: 40,
},
name: LocationNames_1.LocationName.AevumECorp,
otlkMag: 19,
spreadPerc: {
divisor: 10,
max: 5,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumECorp],
},
{
b: true,
initPrice: {
max: 34e3,
min: 24e3,
},
marketCap: 2.4e12,
mv: {
divisor: 100,
max: 50,
min: 40,
},
name: LocationNames_1.LocationName.Sector12MegaCorp,
otlkMag: 19,
spreadPerc: {
divisor: 10,
max: 5,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12MegaCorp],
},
{
b: true,
initPrice: {
max: 25e3,
min: 12e3,
},
marketCap: 1.6e12,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: LocationNames_1.LocationName.Sector12BladeIndustries,
otlkMag: 13,
spreadPerc: {
divisor: 10,
max: 6,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12BladeIndustries],
},
{
b: true,
initPrice: {
max: 25e3,
min: 10e3,
},
marketCap: 1.5e12,
mv: {
divisor: 100,
max: 75,
min: 65,
},
name: LocationNames_1.LocationName.AevumClarkeIncorporated,
otlkMag: 12,
spreadPerc: {
divisor: 10,
max: 5,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumClarkeIncorporated],
},
{
b: true,
initPrice: {
max: 43e3,
min: 32e3,
},
marketCap: 1.8e12,
mv: {
divisor: 100,
max: 70,
min: 60,
},
name: LocationNames_1.LocationName.VolhavenOmniTekIncorporated,
otlkMag: 12,
spreadPerc: {
divisor: 10,
max: 6,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenOmniTekIncorporated],
},
{
b: true,
initPrice: {
max: 80e3,
min: 50e3,
},
marketCap: 2e12,
mv: {
divisor: 100,
max: 110,
min: 100,
},
name: LocationNames_1.LocationName.Sector12FourSigma,
otlkMag: 17,
spreadPerc: {
divisor: 10,
max: 10,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12FourSigma],
},
{
b: true,
initPrice: {
max: 28e3,
min: 16e3,
},
marketCap: 1.9e12,
mv: {
divisor: 100,
max: 85,
min: 75,
},
name: LocationNames_1.LocationName.ChongqingKuaiGongInternational,
otlkMag: 10,
spreadPerc: {
divisor: 10,
max: 7,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.ChongqingKuaiGongInternational],
},
{
b: true,
initPrice: {
max: 36e3,
min: 29e3,
},
marketCap: 2e12,
mv: {
divisor: 100,
max: 130,
min: 120,
},
name: LocationNames_1.LocationName.AevumFulcrumTechnologies,
otlkMag: 16,
spreadPerc: {
divisor: 10,
max: 10,
min: 1,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumFulcrumTechnologies],
},
{
b: true,
initPrice: {
max: 25e3,
min: 20e3,
},
marketCap: 1.2e12,
mv: {
divisor: 100,
max: 90,
min: 80,
},
name: LocationNames_1.LocationName.IshimaStormTechnologies,
otlkMag: 7,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.IshimaStormTechnologies],
},
{
b: true,
initPrice: {
max: 19e3,
min: 6e3,
},
marketCap: 900e9,
mv: {
divisor: 100,
max: 70,
min: 60,
},
name: LocationNames_1.LocationName.NewTokyoDefComm,
otlkMag: 10,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.NewTokyoDefComm],
},
{
b: true,
initPrice: {
max: 18e3,
min: 10e3,
},
marketCap: 825e9,
mv: {
divisor: 100,
max: 65,
min: 55,
},
name: LocationNames_1.LocationName.VolhavenHeliosLabs,
otlkMag: 9,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenHeliosLabs],
},
{
b: true,
initPrice: {
max: 14e3,
min: 8e3,
},
marketCap: 1e12,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: LocationNames_1.LocationName.NewTokyoVitaLife,
otlkMag: 7,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.NewTokyoVitaLife],
},
{
b: true,
initPrice: {
max: 24e3,
min: 12e3,
},
marketCap: 800e9,
mv: {
divisor: 100,
max: 70,
min: 60,
},
name: LocationNames_1.LocationName.Sector12IcarusMicrosystems,
otlkMag: 7.5,
spreadPerc: {
divisor: 10,
max: 10,
min: 3,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12IcarusMicrosystems],
},
{
b: true,
initPrice: {
max: 29e3,
min: 16e3,
},
marketCap: 900e9,
mv: {
divisor: 100,
max: 60,
min: 50,
},
name: LocationNames_1.LocationName.Sector12UniversalEnergy,
otlkMag: 10,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12UniversalEnergy],
},
{
b: true,
initPrice: {
max: 17e3,
min: 8e3,
},
marketCap: 640e9,
mv: {
divisor: 100,
max: 65,
min: 55,
},
name: LocationNames_1.LocationName.AevumAeroCorp,
otlkMag: 6,
spreadPerc: {
divisor: 10,
max: 10,
min: 3,
},
shareTxForMovement: {
max: 126e3,
min: 42e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumAeroCorp],
},
{
b: true,
initPrice: {
max: 15e3,
min: 6e3,
},
marketCap: 600e9,
mv: {
divisor: 100,
max: 75,
min: 65,
},
name: LocationNames_1.LocationName.VolhavenOmniaCybersystems,
otlkMag: 4.5,
spreadPerc: {
divisor: 10,
max: 11,
min: 4,
},
shareTxForMovement: {
max: 126e3,
min: 42e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenOmniaCybersystems],
},
{
b: true,
initPrice: {
max: 28e3,
min: 14e3,
},
marketCap: 705e9,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: LocationNames_1.LocationName.ChongqingSolarisSpaceSystems,
otlkMag: 8.5,
spreadPerc: {
divisor: 10,
max: 12,
min: 4,
},
shareTxForMovement: {
max: 126e3,
min: 42e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.ChongqingSolarisSpaceSystems],
},
{
b: true,
initPrice: {
max: 30e3,
min: 12e3,
},
marketCap: 695e9,
mv: {
divisor: 100,
max: 65,
min: 55,
},
name: LocationNames_1.LocationName.NewTokyoGlobalPharmaceuticals,
otlkMag: 10.5,
spreadPerc: {
divisor: 10,
max: 10,
min: 4,
},
shareTxForMovement: {
max: 126e3,
min: 42e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.NewTokyoGlobalPharmaceuticals],
},
{
b: true,
initPrice: {
max: 27e3,
min: 15e3,
},
marketCap: 600e9,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: LocationNames_1.LocationName.IshimaNovaMedical,
otlkMag: 5,
spreadPerc: {
divisor: 10,
max: 11,
min: 4,
},
shareTxForMovement: {
max: 126e3,
min: 42e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.IshimaNovaMedical],
},
{
b: true,
initPrice: {
max: 8.5e3,
min: 4e3,
},
marketCap: 450e9,
mv: {
divisor: 100,
max: 260,
min: 240,
},
name: LocationNames_1.LocationName.AevumWatchdogSecurity,
otlkMag: 1.5,
spreadPerc: {
divisor: 10,
max: 12,
min: 5,
},
shareTxForMovement: {
max: 54e3,
min: 12e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumWatchdogSecurity],
},
{
b: true,
initPrice: {
max: 8e3,
min: 4.5e3,
},
marketCap: 300e9,
mv: {
divisor: 100,
max: 135,
min: 115,
},
name: LocationNames_1.LocationName.VolhavenLexoCorp,
otlkMag: 6,
spreadPerc: {
divisor: 10,
max: 12,
min: 5,
},
shareTxForMovement: {
max: 108e3,
min: 36e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenLexoCorp],
},
{
b: true,
initPrice: {
max: 7e3,
min: 2e3,
},
marketCap: 180e9,
mv: {
divisor: 100,
max: 70,
min: 50,
},
name: LocationNames_1.LocationName.AevumRhoConstruction,
otlkMag: 1,
spreadPerc: {
divisor: 10,
max: 10,
min: 3,
},
shareTxForMovement: {
max: 126e3,
min: 60e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumRhoConstruction],
},
{
b: true,
initPrice: {
max: 8.5e3,
min: 4e3,
},
marketCap: 240e9,
mv: {
divisor: 100,
max: 205,
min: 175,
},
name: LocationNames_1.LocationName.Sector12AlphaEnterprises,
otlkMag: 10,
spreadPerc: {
divisor: 10,
max: 16,
min: 5,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12AlphaEnterprises],
},
{
b: true,
initPrice: {
max: 8e3,
min: 3e3,
},
marketCap: 200e9,
mv: {
divisor: 100,
max: 170,
min: 150,
},
name: LocationNames_1.LocationName.VolhavenSysCoreSecurities,
otlkMag: 3,
spreadPerc: {
divisor: 10,
max: 12,
min: 5,
},
shareTxForMovement: {
max: 90e3,
min: 15e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenSysCoreSecurities],
},
{
b: true,
initPrice: {
max: 6e3,
min: 1e3,
},
marketCap: 185e9,
mv: {
divisor: 100,
max: 100,
min: 80,
},
name: LocationNames_1.LocationName.VolhavenCompuTek,
otlkMag: 4,
spreadPerc: {
divisor: 10,
max: 12,
min: 4,
},
shareTxForMovement: {
max: 126e3,
min: 60e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.VolhavenCompuTek],
},
{
b: true,
initPrice: {
max: 5e3,
min: 1e3,
},
marketCap: 58e9,
mv: {
divisor: 100,
max: 400,
min: 200,
},
name: LocationNames_1.LocationName.AevumNetLinkTechnologies,
otlkMag: 1,
spreadPerc: {
divisor: 10,
max: 20,
min: 5,
},
shareTxForMovement: {
max: 54e3,
min: 18e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.AevumNetLinkTechnologies],
},
{
b: true,
initPrice: {
max: 8e3,
min: 1e3,
},
marketCap: 60e9,
mv: {
divisor: 100,
max: 110,
min: 90,
},
name: LocationNames_1.LocationName.IshimaOmegaSoftware,
otlkMag: 0.5,
spreadPerc: {
divisor: 10,
max: 13,
min: 4,
},
shareTxForMovement: {
max: 90e3,
min: 30e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.IshimaOmegaSoftware],
},
{
b: false,
initPrice: {
max: 4.5e3,
min: 500,
},
marketCap: 45e9,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: LocationNames_1.LocationName.Sector12FoodNStuff,
otlkMag: 1,
spreadPerc: {
divisor: 10,
max: 10,
min: 6,
},
shareTxForMovement: {
max: 180e3,
min: 60e3,
},
symbol: StockSymbols_1.StockSymbols[LocationNames_1.LocationName.Sector12FoodNStuff],
},
{
b: true,
initPrice: {
max: 3.5e3,
min: 1.5e3,
},
marketCap: 30e9,
mv: {
divisor: 100,
max: 275,
min: 100,
},
name: "Sigma Cosmetics",
otlkMag: 0,
spreadPerc: {
divisor: 10,
max: 14,
min: 6,
},
shareTxForMovement: {
max: 70e3,
min: 20e3,
},
symbol: StockSymbols_1.StockSymbols["Sigma Cosmetics"],
},
{
b: true,
initPrice: {
max: 1.5e3,
min: 250,
},
marketCap: 42e9,
mv: {
divisor: 100,
max: 350,
min: 200,
},
name: "Joes Guns",
otlkMag: 1,
spreadPerc: {
divisor: 10,
max: 14,
min: 6,
},
shareTxForMovement: {
max: 52e3,
min: 15e3,
},
symbol: StockSymbols_1.StockSymbols["Joes Guns"],
},
{
b: true,
initPrice: {
max: 1.5e3,
min: 250,
},
marketCap: 100e9,
mv: {
divisor: 100,
max: 175,
min: 120,
},
name: "Catalyst Ventures",
otlkMag: 13.5,
spreadPerc: {
divisor: 10,
max: 14,
min: 5,
},
shareTxForMovement: {
max: 72e3,
min: 24e3,
},
symbol: StockSymbols_1.StockSymbols["Catalyst Ventures"],
},
{
b: true,
initPrice: {
max: 30e3,
min: 15e3,
},
marketCap: 360e9,
mv: {
divisor: 100,
max: 80,
min: 70,
},
name: "Microdyne Technologies",
otlkMag: 8,
spreadPerc: {
divisor: 10,
max: 10,
min: 3,
},
shareTxForMovement: {
max: 216e3,
min: 90e3,
},
symbol: StockSymbols_1.StockSymbols["Microdyne Technologies"],
},
{
b: true,
initPrice: {
max: 24e3,
min: 12e3,
},
marketCap: 420e9,
mv: {
divisor: 100,
max: 70,
min: 50,
},
name: "Titan Laboratories",
otlkMag: 11,
spreadPerc: {
divisor: 10,
max: 10,
min: 2,
},
shareTxForMovement: {
max: 216e3,
min: 90e3,
},
symbol: StockSymbols_1.StockSymbols["Titan Laboratories"],
},
];
/***/ }),
/* 994 */
/*!*************************************************!*\
!*** ./src/StockMarket/StockMarketConstants.ts ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TicksPerCycle = void 0;
/**
* How many stock market 'ticks' before a 'cycle' is triggered.
* A 'tick' is whenver stock prices update
*/
exports.TicksPerCycle = 75;
/***/ }),
/* 995 */
/*!*********************************************!*\
!*** ./src/StockMarket/OrderProcessing.tsx ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.processOrders = void 0;
/**
* Helper functions for determine whether Limit and Stop orders should
* be executed (and executing them)
*/
const BuyingAndSelling_1 = __webpack_require__(/*! ./BuyingAndSelling */ 174);
const Stock_1 = __webpack_require__(/*! ./Stock */ 191);
const OrderTypes_1 = __webpack_require__(/*! ./data/OrderTypes */ 111);
const PositionTypes_1 = __webpack_require__(/*! ./data/PositionTypes */ 98);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const Money_1 = __webpack_require__(/*! ../ui/React/Money */ 27);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const React = __importStar(__webpack_require__(/*! react */ 0));
/**
* Search for all orders of a specific type and execute them if appropriate
* @param {Stock} stock - Stock for which orders should be processed
* @param {OrderTypes} orderType - Type of order to check (Limit/Stop buy/sell)
* @param {PositionTypes} posType - Long or short
* @param {IProcessOrderRefs} refs - References to objects/functions that are required for this function
*/
function processOrders(stock, orderType, posType, refs) {
const orderBook = refs.stockMarket["Orders"];
if (orderBook == null) {
const orders = {};
for (const name in refs.stockMarket) {
const stock = refs.stockMarket[name];
if (!(stock instanceof Stock_1.Stock)) {
continue;
}
orders[stock.symbol] = [];
}
refs.stockMarket["Orders"] = orders;
return; // Newly created, so no orders to process
}
let stockOrders = orderBook[stock.symbol];
if (stockOrders == null || !(stockOrders.constructor === Array)) {
console.error(`Invalid Order book for ${stock.symbol} in processOrders(): ${stockOrders}`);
stockOrders = [];
return;
}
for (const order of stockOrders) {
if (order.type === orderType && order.pos === posType) {
switch (order.type) {
case OrderTypes_1.OrderTypes.LimitBuy:
if (order.pos === PositionTypes_1.PositionTypes.Long && stock.price <= order.price) {
executeOrder /*66*/(order, refs);
}
else if (order.pos === PositionTypes_1.PositionTypes.Short && stock.price >= order.price) {
executeOrder /*66*/(order, refs);
}
break;
case OrderTypes_1.OrderTypes.LimitSell:
if (order.pos === PositionTypes_1.PositionTypes.Long && stock.price >= order.price) {
executeOrder /*66*/(order, refs);
}
else if (order.pos === PositionTypes_1.PositionTypes.Short && stock.price <= order.price) {
executeOrder /*66*/(order, refs);
}
break;
case OrderTypes_1.OrderTypes.StopBuy:
if (order.pos === PositionTypes_1.PositionTypes.Long && stock.price >= order.price) {
executeOrder /*66*/(order, refs);
}
else if (order.pos === PositionTypes_1.PositionTypes.Short && stock.price <= order.price) {
executeOrder /*66*/(order, refs);
}
break;
case OrderTypes_1.OrderTypes.StopSell:
if (order.pos === PositionTypes_1.PositionTypes.Long && stock.price <= order.price) {
executeOrder /*66*/(order, refs);
}
else if (order.pos === PositionTypes_1.PositionTypes.Short && stock.price >= order.price) {
executeOrder /*66*/(order, refs);
}
break;
default:
console.warn(`Invalid order type: ${order.type}`);
return;
}
}
}
}
exports.processOrders = processOrders;
/**
* Execute a Stop or Limit Order.
* @param {Order} order - Order being executed
* @param {IProcessOrderRefs} refs - References to objects/functions that are required for this function
*/
function executeOrder(order, refs) {
const stock = refs.symbolToStockMap[order.stockSymbol];
if (!(stock instanceof Stock_1.Stock)) {
console.error(`Could not find stock for this order: ${order.stockSymbol}`);
return;
}
const stockMarket = refs.stockMarket;
const orderBook = stockMarket["Orders"];
const stockOrders = orderBook[stock.symbol];
// When orders are executed, the buying and selling functions shouldn't
// emit popup dialog boxes. This options object configures the functions for that
const opts = {
rerenderFn: refs.rerenderFn,
suppressDialog: true,
};
let res = true;
let isBuy = false;
switch (order.type) {
case OrderTypes_1.OrderTypes.LimitBuy:
case OrderTypes_1.OrderTypes.StopBuy:
isBuy = true;
if (order.pos === PositionTypes_1.PositionTypes.Long) {
res = BuyingAndSelling_1.buyStock(stock, order.shares, null, opts) && res;
}
else if (order.pos === PositionTypes_1.PositionTypes.Short) {
res = BuyingAndSelling_1.shortStock(stock, order.shares, null, opts) && res;
}
break;
case OrderTypes_1.OrderTypes.LimitSell:
case OrderTypes_1.OrderTypes.StopSell:
if (order.pos === PositionTypes_1.PositionTypes.Long) {
res = BuyingAndSelling_1.sellStock(stock, order.shares, null, opts) && res;
}
else if (order.pos === PositionTypes_1.PositionTypes.Short) {
res = BuyingAndSelling_1.sellShort(stock, order.shares, null, opts) && res;
}
break;
default:
console.warn(`Invalid order type: ${order.type}`);
return;
}
// Position type, for logging/message purposes
const pos = order.pos === PositionTypes_1.PositionTypes.Long ? "Long" : "Short";
if (res) {
for (let i = 0; i < stockOrders.length; ++i) {
if (order == stockOrders[i]) {
stockOrders.splice(i, 1);
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
order.type,
" for ",
stock.symbol,
" @ ",
Money_1.Money(order.price),
" (",
pos,
") was filled (",
numeralFormat_1.numeralWrapper.formatShares(Math.round(order.shares)),
" shares)"));
refs.rerenderFn();
return;
}
}
console.error("Could not find the following Order in Order Book: ");
console.error(order);
}
else {
if (isBuy) {
DialogBox_1.dialogBoxCreate(React.createElement(React.Fragment, null,
"Failed to execute ",
order.type,
" for ",
stock.symbol,
" @ ",
Money_1.Money(order.price),
" (",
pos,
"). This is most likely because you do not have enough money or the order would exceed the stock's maximum number of shares"));
}
}
}
/***/ }),
/* 996 */
/*!**********************************!*\
!*** ./src/StockMarket/Order.ts ***!
\**********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Order = void 0;
/**
* Represents a Limit or Buy Order on the stock market. Does not represent
* a Market Order since those are just executed immediately
*/
const OrderTypes_1 = __webpack_require__(/*! ./data/OrderTypes */ 111);
const PositionTypes_1 = __webpack_require__(/*! ./data/PositionTypes */ 98);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class Order {
constructor(stockSymbol = "", shares = 0, price = 0, typ = OrderTypes_1.OrderTypes.LimitBuy, pos = PositionTypes_1.PositionTypes.Long) {
// Validate arguments
let invalidArgs = false;
if (typeof shares !== "number" || typeof price !== "number") {
invalidArgs = true;
}
if (isNaN(shares) || isNaN(price)) {
invalidArgs = true;
}
if (typeof stockSymbol !== "string") {
invalidArgs = true;
}
if (invalidArgs) {
throw new Error(`Invalid constructor paramters for Order`);
}
this.stockSymbol = stockSymbol;
this.shares = shares;
this.price = price;
this.type = typ;
this.pos = pos;
}
/**
* Serialize the Order to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Order", this);
}
/**
* Initializes a Order from a JSON save state
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Order, value.data);
}
}
exports.Order = Order;
JSONReviver_1.Reviver.constructors.Order = Order;
/***/ }),
/* 997 */
/*!***************************************!*\
!*** ./utils/helpers/isPowerOfTwo.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPowerOfTwo = void 0;
/**
* 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;
/***/ }),
/* 998 */,
/* 999 */,
/* 1000 */,
/* 1001 */,
/* 1002 */,
/* 1003 */,
/* 1004 */,
/* 1005 */,
/* 1006 */,
/* 1007 */,
/* 1008 */,
/* 1009 */,
/* 1010 */,
/* 1011 */,
/* 1012 */,
/* 1013 */,
/* 1014 */,
/* 1015 */,
/* 1016 */,
/* 1017 */,
/* 1018 */,
/* 1019 */,
/* 1020 */,
/* 1021 */,
/* 1022 */,
/* 1023 */,
/* 1024 */,
/* 1025 */,
/* 1026 */,
/* 1027 */,
/* 1028 */,
/* 1029 */,
/* 1030 */,
/* 1031 */,
/* 1032 */,
/* 1033 */,
/* 1034 */,
/* 1035 */,
/* 1036 */,
/* 1037 */,
/* 1038 */,
/* 1039 */,
/* 1040 */,
/* 1041 */,
/* 1042 */,
/* 1043 */,
/* 1044 */,
/* 1045 */
/*!**********************!*\
!*** util (ignored) ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 1046 */,
/* 1047 */
/*!**********************!*\
!*** util (ignored) ***!
\**********************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 1048 */,
/* 1049 */,
/* 1050 */,
/* 1051 */,
/* 1052 */
/*!************************************************!*\
!*** ./src/Terminal/DirectoryServerHelpers.ts ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSubdirectories = void 0;
/**
* Helper functions that implement "directory" functionality in the Terminal.
* These aren't "real" directories, it's more of a pseudo-directory implementation
* that uses mainly string manipulation.
*
* This file contains function that deal with Server-related directory things.
* Functions that deal with the string manipulation can be found in
* ./DirectoryHelpers.ts
*/
const DirectoryHelpers_1 = __webpack_require__(/*! ./DirectoryHelpers */ 86);
/**
* Given a directory (by the full directory path) and a server, returns all
* subdirectories of that directory. This is only for FIRST-LEVEl/immediate subdirectories
*/
function getSubdirectories(serv, dir) {
const res = [];
if (!DirectoryHelpers_1.isValidDirectoryPath(dir)) {
return res;
}
let t_dir = dir;
if (!t_dir.endsWith("/")) {
t_dir += "/";
}
function processFile(fn) {
if (t_dir === "/" && DirectoryHelpers_1.isInRootDirectory(fn)) {
const subdir = DirectoryHelpers_1.getFirstParentDirectory(fn);
if (subdir !== "/" && !res.includes(subdir)) {
res.push(subdir);
}
}
else if (fn.startsWith(t_dir)) {
const remaining = fn.slice(t_dir.length);
const subdir = DirectoryHelpers_1.getFirstParentDirectory(remaining);
if (subdir !== "/" && !res.includes(subdir)) {
res.push(subdir);
}
}
}
for (const script of serv.scripts) {
processFile(script.filename);
}
for (const txt of serv.textFiles) {
processFile(txt.fn);
}
return res;
}
exports.getSubdirectories = getSubdirectories;
/***/ }),
/* 1053 */
/*!***************************************!*\
!*** ./src/Gang/GangMemberUpgrade.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMemberUpgrade = void 0;
const upgrades_1 = __webpack_require__(/*! ./data/upgrades */ 486);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
class GangMemberUpgrade {
constructor(name = "", cost = 0, type = upgrades_1.UpgradeType.Weapon, mults = {}) {
this.name = name;
this.cost = cost;
this.type = type;
this.mults = mults;
this.desc = this.createDescription();
}
createDescription() {
const lines = ["Effects:"];
if (this.mults.str != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.str - 1, 0)} strength skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.str - 1) / 4, 2)} strength exp`);
}
if (this.mults.def != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.def - 1, 0)} defense skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.def - 1) / 4, 2)} defense exp`);
}
if (this.mults.dex != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.dex - 1, 0)} dexterity skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.dex - 1) / 4, 2)} dexterity exp`);
}
if (this.mults.agi != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.agi - 1, 0)} agility skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.agi - 1) / 4, 2)} agility exp`);
}
if (this.mults.cha != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.cha - 1, 0)} charisma skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.cha - 1) / 4, 2)} charisma exp`);
}
if (this.mults.hack != null) {
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage(this.mults.hack - 1, 0)} hacking skill`);
lines.push(`+${numeralFormat_1.numeralWrapper.formatPercentage((this.mults.hack - 1) / 4, 2)} hacking exp`);
}
return lines.join(" ");
}
// User friendly version of type.
getType() {
switch (this.type) {
case upgrades_1.UpgradeType.Weapon:
return "Weapon";
case upgrades_1.UpgradeType.Armor:
return "Armor";
case upgrades_1.UpgradeType.Vehicle:
return "Vehicle";
case upgrades_1.UpgradeType.Rootkit:
return "Rootkit";
case upgrades_1.UpgradeType.Augmentation:
return "Augmentation";
default:
return "";
}
}
}
exports.GangMemberUpgrade = GangMemberUpgrade;
/***/ }),
/* 1054 */
/*!********************************!*\
!*** ./src/Gang/GangMember.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GangMember = void 0;
const GangMemberTask_1 = __webpack_require__(/*! ./GangMemberTask */ 677);
const GangMemberTasks_1 = __webpack_require__(/*! ./GangMemberTasks */ 285);
const GangMemberUpgrades_1 = __webpack_require__(/*! ./GangMemberUpgrades */ 175);
const AllGangs_1 = __webpack_require__(/*! ./AllGangs */ 85);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
class GangMember {
constructor(name = "") {
this.task = "Unassigned";
this.earnedRespect = 0;
this.hack = 1;
this.str = 1;
this.def = 1;
this.dex = 1;
this.agi = 1;
this.cha = 1;
this.hack_exp = 0;
this.str_exp = 0;
this.def_exp = 0;
this.dex_exp = 0;
this.agi_exp = 0;
this.cha_exp = 0;
this.hack_mult = 1;
this.str_mult = 1;
this.def_mult = 1;
this.dex_mult = 1;
this.agi_mult = 1;
this.cha_mult = 1;
this.hack_asc_points = 0;
this.str_asc_points = 0;
this.def_asc_points = 0;
this.dex_asc_points = 0;
this.agi_asc_points = 0;
this.cha_asc_points = 0;
this.upgrades = []; // Names of upgrades
this.augmentations = []; // Names of augmentations only
this.name = name;
}
calculateSkill(exp, mult = 1) {
return Math.max(Math.floor(mult * (32 * Math.log(exp + 534.5) - 200)), 1);
}
calculateAscensionMult(points) {
return Math.max(Math.pow(points / 4000, 0.7), 1);
}
updateSkillLevels() {
this.hack = this.calculateSkill(this.hack_exp, this.hack_mult * this.calculateAscensionMult(this.hack_asc_points));
this.str = this.calculateSkill(this.str_exp, this.str_mult * this.calculateAscensionMult(this.str_asc_points));
this.def = this.calculateSkill(this.def_exp, this.def_mult * this.calculateAscensionMult(this.def_asc_points));
this.dex = this.calculateSkill(this.dex_exp, this.dex_mult * this.calculateAscensionMult(this.dex_asc_points));
this.agi = this.calculateSkill(this.agi_exp, this.agi_mult * this.calculateAscensionMult(this.agi_asc_points));
this.cha = this.calculateSkill(this.cha_exp, this.cha_mult * this.calculateAscensionMult(this.cha_asc_points));
}
calculatePower() {
return (this.hack +
this.str +
this.def +
this.dex +
this.agi +
this.cha) / 95;
}
assignToTask(taskName) {
if (!GangMemberTasks_1.GangMemberTasks.hasOwnProperty(taskName)) {
this.task = "Unassigned";
return false;
}
this.task = taskName;
return true;
}
unassignFromTask() {
this.task = "Unassigned";
}
getTask() {
// TODO(hydroflame): transfer that to a save file migration function
// Backwards compatibility
if (this.task instanceof GangMemberTask_1.GangMemberTask) {
this.task = this.task.name;
}
if (GangMemberTasks_1.GangMemberTasks.hasOwnProperty(this.task)) {
return GangMemberTasks_1.GangMemberTasks[this.task];
}
return GangMemberTasks_1.GangMemberTasks["Unassigned"];
}
calculateRespectGain(gang) {
const task = this.getTask();
if (task.baseRespect === 0)
return 0;
let 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.max(0.005, Math.pow(AllGangs_1.AllGangs[gang.facName].territory * 100, task.territory.respect) / 100);
if (isNaN(territoryMult) || territoryMult <= 0)
return 0;
const respectMult = gang.getWantedPenalty();
return 11 * task.baseRespect * statWeight * territoryMult * respectMult;
}
calculateWantedLevelGain(gang) {
const task = this.getTask();
if (task.baseWanted === 0)
return 0;
let 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.max(0.005, Math.pow(AllGangs_1.AllGangs[gang.facName].territory * 100, task.territory.wanted) / 100);
if (isNaN(territoryMult) || territoryMult <= 0)
return 0;
if (task.baseWanted < 0) {
return 0.4 * task.baseWanted * statWeight * territoryMult;
}
const calc = 7 * task.baseWanted / (Math.pow(3 * statWeight * territoryMult, 0.8));
// Put an arbitrary cap on this to prevent wanted level from rising too fast if the
// denominator is very small. Might want to rethink formula later
return Math.min(100, calc);
}
calculateMoneyGain(gang) {
const task = this.getTask();
if (task.baseMoney === 0)
return 0;
let 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.max(0.005, Math.pow(AllGangs_1.AllGangs[gang.facName].territory * 100, task.territory.money) / 100);
if (isNaN(territoryMult) || territoryMult <= 0)
return 0;
const respectMult = gang.getWantedPenalty();
return 5 * task.baseMoney * statWeight * territoryMult * respectMult;
}
expMult() {
return {
hack: (this.hack_mult - 1) / 4 + 1,
str: (this.str_mult - 1) / 4 + 1,
def: (this.def_mult - 1) / 4 + 1,
dex: (this.dex_mult - 1) / 4 + 1,
agi: (this.agi_mult - 1) / 4 + 1,
cha: (this.cha_mult - 1) / 4 + 1,
};
}
gainExperience(numCycles = 1) {
const task = this.getTask();
if (task === GangMemberTasks_1.GangMemberTasks["Unassigned"])
return;
const difficultyMult = Math.pow(task.difficulty, 0.9);
const difficultyPerCycles = difficultyMult * numCycles;
const weightDivisor = 1500;
const expMult = this.expMult();
this.hack_exp += (task.hackWeight / weightDivisor) * difficultyPerCycles * expMult.hack;
this.str_exp += (task.strWeight / weightDivisor) * difficultyPerCycles * expMult.str;
this.def_exp += (task.defWeight / weightDivisor) * difficultyPerCycles * expMult.def;
this.dex_exp += (task.dexWeight / weightDivisor) * difficultyPerCycles * expMult.dex;
this.agi_exp += (task.agiWeight / weightDivisor) * difficultyPerCycles * expMult.agi;
this.cha_exp += (task.chaWeight / weightDivisor) * difficultyPerCycles * expMult.cha;
}
recordEarnedRespect(numCycles = 1, gang) {
this.earnedRespect += (this.calculateRespectGain(gang) * numCycles);
}
getGainedAscensionPoints() {
return {
hack: Math.max(this.hack_exp - 1000, 0),
str: Math.max(this.str_exp - 1000, 0),
def: Math.max(this.def_exp - 1000, 0),
dex: Math.max(this.dex_exp - 1000, 0),
agi: Math.max(this.agi_exp - 1000, 0),
cha: Math.max(this.cha_exp - 1000, 0),
};
}
canAscend() {
const points = this.getGainedAscensionPoints();
return points.hack > 0 ||
points.str > 0 ||
points.def > 0 ||
points.dex > 0 ||
points.agi > 0 ||
points.cha > 0;
}
getAscensionResults() {
const points = this.getGainedAscensionPoints();
return {
hack: this.calculateAscensionMult(this.hack_asc_points + points.hack) / this.calculateAscensionMult(this.hack_asc_points),
str: this.calculateAscensionMult(this.str_asc_points + points.str) / this.calculateAscensionMult(this.str_asc_points),
def: this.calculateAscensionMult(this.def_asc_points + points.def) / this.calculateAscensionMult(this.def_asc_points),
dex: this.calculateAscensionMult(this.dex_asc_points + points.dex) / this.calculateAscensionMult(this.dex_asc_points),
agi: this.calculateAscensionMult(this.agi_asc_points + points.agi) / this.calculateAscensionMult(this.agi_asc_points),
cha: this.calculateAscensionMult(this.cha_asc_points + points.cha) / this.calculateAscensionMult(this.cha_asc_points),
};
}
ascend() {
const res = this.getAscensionResults();
const points = this.getGainedAscensionPoints();
this.hack_asc_points += points.hack;
this.str_asc_points += points.str;
this.def_asc_points += points.def;
this.dex_asc_points += points.dex;
this.agi_asc_points += points.agi;
this.cha_asc_points += points.cha;
// 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) {
const aug = GangMemberUpgrades_1.GangMemberUpgrades[this.augmentations[i]];
this.applyUpgrade(aug);
}
// 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: res.hack,
str: res.str,
def: res.def,
dex: res.dex,
agi: res.agi,
cha: res.cha,
};
}
applyUpgrade(upg) {
if (upg.mults.str != null)
this.str_mult *= upg.mults.str;
if (upg.mults.def != null)
this.def_mult *= upg.mults.def;
if (upg.mults.dex != null)
this.dex_mult *= upg.mults.dex;
if (upg.mults.agi != null)
this.agi_mult *= upg.mults.agi;
if (upg.mults.cha != null)
this.cha_mult *= upg.mults.cha;
if (upg.mults.hack != null)
this.hack_mult *= upg.mults.hack;
}
buyUpgrade(upg, player, gang) {
// Prevent purchasing of already-owned upgrades
if (this.augmentations.includes(upg.name) ||
this.upgrades.includes(upg.name))
return false;
if (player.money.lt(gang.getUpgradeCost(upg)))
return false;
player.loseMoney(gang.getUpgradeCost(upg));
if (upg.type === "g") {
this.augmentations.push(upg.name);
}
else {
this.upgrades.push(upg.name);
}
this.applyUpgrade(upg);
return true;
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("GangMember", this);
}
/**
* Initiatizes a GangMember object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(GangMember, value.data);
}
}
exports.GangMember = GangMember;
JSONReviver_1.Reviver.constructors.GangMember = GangMember;
/***/ }),
/* 1055 */
/*!********************************!*\
!*** ./src/Gang/data/tasks.ts ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gangMemberTasksMetadata = void 0;
/**
* 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 }, // This is just to get by the weight check in the GangMemberTask constructor
},
{
desc: "Assign this gang member to create and distribute ransomware
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
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
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
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
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
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
`;
}
const prodMult = props.corp.getProductionMultiplier(), storageMult = props.corp.getStorageMultiplier(), advMult = props.corp.getAdvertisingMultiplier(), empCreMult = props.corp.getEmployeeCreMultiplier(), empChaMult = props.corp.getEmployeeChaMultiplier(), empIntMult = props.corp.getEmployeeIntMultiplier(), empEffMult = props.corp.getEmployeeEffMultiplier(), salesMult = props.corp.getSalesMultiplier(), sciResMult = props.corp.getScientificResearchMultiplier();
if (prodMult > 1) {
txt += "Production Multiplier: " + numeralFormat_1.numeralWrapper.format(prodMult, "0.000") + " ";
}
if (storageMult > 1) {
txt += "Storage Multiplier: " + numeralFormat_1.numeralWrapper.format(storageMult, "0.000") + " ";
}
if (advMult > 1) {
txt += "Advertising Multiplier: " + numeralFormat_1.numeralWrapper.format(advMult, "0.000") + " ";
}
if (empCreMult > 1) {
txt += "Empl. Creativity Multiplier: " + numeralFormat_1.numeralWrapper.format(empCreMult, "0.000") + " ";
}
if (empChaMult > 1) {
txt += "Empl. Charisma Multiplier: " + numeralFormat_1.numeralWrapper.format(empChaMult, "0.000") + " ";
}
if (empIntMult > 1) {
txt += "Empl. Intelligence Multiplier: " + numeralFormat_1.numeralWrapper.format(empIntMult, "0.000") + " ";
}
if (empEffMult > 1) {
txt += "Empl. Efficiency Multiplier: " + numeralFormat_1.numeralWrapper.format(empEffMult, "0.000") + " ";
}
if (salesMult > 1) {
txt += "Sales Multiplier: " + numeralFormat_1.numeralWrapper.format(salesMult, "0.000") + " ";
}
if (sciResMult > 1) {
txt += "Scientific Research Multiplier: " + numeralFormat_1.numeralWrapper.format(sciResMult, "0.000") + " ";
}
return txt;
}
// Render the buttons that lie below the overview text.
// These are mainly for things such as managing finances/stock
function renderButtons() {
// Create a "Getting Started Guide" button that lets player view the
// handbook and adds it to the players home computer
const getStarterGuideBtn = createButton({
class: "a-link-button",
display: "inline-block",
onClick: () => props.corp.getStarterGuide(props.player),
text: "Getting Started Guide",
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.",
});
function openBribeFactionPopup() {
const popupId = "corp-bribe-popup";
createPopup_1.createPopup(popupId, BribeFactionPopup_1.BribeFactionPopup, {
player: props.player,
popupId: popupId,
corp: props.corp,
});
}
// Create a "Bribe Factions" button if your Corporation is powerful enough.
// This occurs regardless of whether you're public or private
const canBribe = (props.corp.determineValuation() >= Constants_1.CorporationConstants.BribeThreshold) || true;
const bribeFactionsClass = (canBribe ? "a-link-button" : "a-link-button-inactive");
const bribeFactionsBtn = createButton({
class: bribeFactionsClass,
display: "inline-block",
onClick: openBribeFactionPopup,
text: "Bribe Factions",
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"),
});
const generalBtns = {
bribeFactions: bribeFactionsBtn,
getStarterGuide: getStarterGuideBtn,
};
if (props.corp.public) {
return renderPublicButtons(generalBtns);
}
else {
return renderPrivateButtons(generalBtns);
}
}
// Render the buttons for when your Corporation is still private
function renderPrivateButtons(generalBtns) {
const fundingAvailable = (props.corp.fundingRound < 4);
const findInvestorsClassName = fundingAvailable ? "std-button" : "a-link-button-inactive";
const findInvestorsTooltip = fundingAvailable ? "Search for private investors who will give you startup funding in exchangefor equity (stock shares) in your company" : undefined;
function openFindInvestorsPopup() {
const popupId = "cmpy-mgmt-find-investors-popup";
createPopup_1.createPopup(popupId, FindInvestorsPopup_1.FindInvestorsPopup, {
player: props.player,
popupId: popupId,
corp: props.corp,
});
}
function openGoPublicPopup() {
const popupId = "cmpy-mgmt-go-public-popup";
createPopup_1.createPopup(popupId, GoPublicPopup_1.GoPublicPopup, {
player: props.player,
popupId: popupId,
corp: props.corp,
});
}
const findInvestorsBtn = createButton({
class: findInvestorsClassName,
onClick: openFindInvestorsPopup,
text: "Find Investors",
tooltip: findInvestorsTooltip,
display: "inline-block",
});
const goPublicBtn = createButton({
class: "std-button",
onClick: openGoPublicPopup,
display: "inline-block",
text: "Go Public",
tooltip: "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.",
});
return (react_1.default.createElement("div", null,
generalBtns.getStarterGuide,
findInvestorsBtn,
goPublicBtn,
react_1.default.createElement("br", null),
generalBtns.bribeFactions));
}
// Render the buttons for when your Corporation has gone public
function renderPublicButtons(generalBtns) {
const corp = props.corp;
const sellSharesOnCd = (corp.shareSaleCooldown > 0);
const sellSharesClass = sellSharesOnCd ? "a-link-button-inactive" : "std-button";
const sellSharesTooltip = sellSharesOnCd
? "Cannot sell shares for " + corp.convertCooldownToString(corp.shareSaleCooldown)
: "Sell your shares in the company. The money earned from selling your " +
"shares goes into your personal account, not the Corporation's. " +
"This is one of the only ways to profit from your business venture.";
const sellSharesBtn = createButton({
class: sellSharesClass,
display: "inline-block",
onClick: function (event) {
if (!event.isTrusted)
return;
const popupId = "cmpy-mgmt-sell-shares-popup";
createPopup_1.createPopup(popupId, SellSharesPopup_1.SellSharesPopup, {
corp: props.corp,
player: props.player,
popupId: popupId,
});
},
text: "Sell Shares",
tooltip: sellSharesTooltip,
});
function openBuybackSharesPopup() {
const popupId = "corp-buyback-shares-popup";
createPopup_1.createPopup(popupId, BuybackSharesPopup_1.BuybackSharesPopup, {
player: props.player,
popupId: popupId,
corp: props.corp,
});
}
const buybackSharesBtn = createButton({
class: "std-button",
display: "inline-block",
onClick: openBuybackSharesPopup,
text: "Buyback shares",
tooltip: "Buy back shares you that previously issued or sold at market price.",
});
function openIssueNewSharesPopup() {
const popupId = "cmpy-mgmt-issue-new-shares-popup";
createPopup_1.createPopup(popupId, IssueNewSharesPopup_1.IssueNewSharesPopup, {
popupId: popupId,
corp: props.corp,
});
}
const issueNewSharesOnCd = (corp.issueNewSharesCooldown > 0);
const issueNewSharesClass = issueNewSharesOnCd ? "a-link-button-inactive" : "std-button";
const issueNewSharesTooltip = issueNewSharesOnCd
? "Cannot issue new shares for " + corp.convertCooldownToString(corp.issueNewSharesCooldown)
: "Issue new equity shares to raise capital.";
const issueNewSharesBtn = createButton({
class: issueNewSharesClass,
display: "inline-block",
onClick: openIssueNewSharesPopup,
text: "Issue New Shares",
tooltip: issueNewSharesTooltip,
});
function openIssueDividendsPopup() {
const popupId = "cmpy-mgmt-issue-dividends-popup";
createPopup_1.createPopup(popupId, IssueDividendsPopup_1.IssueDividendsPopup, {
popupId: popupId,
corp: props.corp,
});
}
const issueDividendsBtn = createButton({
class: "std-button",
display: "inline-block",
onClick: openIssueDividendsPopup,
text: "Issue Dividends",
tooltip: "Manage the dividends that are paid out to shareholders (including yourself)",
});
return (react_1.default.createElement("div", null,
generalBtns.getStarterGuide,
sellSharesBtn,
buybackSharesBtn,
react_1.default.createElement("br", null),
issueNewSharesBtn,
issueDividendsBtn,
react_1.default.createElement("br", null),
generalBtns.bribeFactions));
}
// Render the UI for Corporation upgrades
function renderUpgrades() {
// Don't show upgrades
if (props.corp.divisions.length <= 0) {
return (react_1.default.createElement(react_1.default.Fragment, null));
}
// Create an array of all Unlocks
const unlockUpgrades = [];
Object.values(CorporationUnlockUpgrades_1.CorporationUnlockUpgrades).forEach((unlockData) => {
if (props.corp.unlockUpgrades[unlockData[0]] === 0) {
unlockUpgrades.push(react_1.default.createElement(UnlockUpgrade_1.UnlockUpgrade, { player: props.player, corp: props.corp, upgradeData: unlockData, key: unlockData[0] }));
}
});
// Create an array of properties of all unlocks
const levelableUpgradeProps = [];
for (let i = 0; i < props.corp.upgrades.length; ++i) {
const upgradeData = CorporationUpgrades_1.CorporationUpgrades[i];
const level = props.corp.upgrades[i];
levelableUpgradeProps.push({
upgradeData: upgradeData,
upgradeLevel: level,
});
}
return (react_1.default.createElement("div", { className: "cmpy-mgmt-upgrade-container" },
react_1.default.createElement("h1", { className: "cmpy-mgmt-upgrade-header" }, " Unlocks "),
unlockUpgrades,
react_1.default.createElement("h1", { className: "cmpy-mgmt-upgrade-header" }, " Upgrades "),
levelableUpgradeProps.map((data) => react_1.default.createElement(LevelableUpgrade_1.LevelableUpgrade, { player: props.player, corp: props.corp, upgradeData: data.upgradeData, upgradeLevel: data.upgradeLevel, key: data.upgradeData[0] }))));
}
return (react_1.default.createElement("div", null,
react_1.default.createElement("p", { dangerouslySetInnerHTML: { __html: getOverviewText() } }),
renderButtons(),
react_1.default.createElement("br", null),
renderUpgrades()));
}
exports.Overview = Overview;
/***/ }),
/* 1100 */
/*!*****************************************************!*\
!*** ./src/Corporation/ui/ProductMarketTaPopup.tsx ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProductMarketTaPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function MarketTA2(props) {
const markupLimit = props.product.rat / props.product.mku;
const [value, setValue] = react_1.useState(props.product.pCost);
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
function onChange(event) {
setValue(parseFloat(event.target.value));
}
function onCheckedChange(event) {
props.product.marketTa2 = event.target.checked;
rerender();
}
const sCost = value;
let markup = 1;
if (sCost > props.product.pCost) {
if ((sCost - props.product.pCost) > markupLimit) {
markup = markupLimit / (sCost - props.product.pCost);
}
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
react_1.default.createElement("br", null),
react_1.default.createElement("u", null,
react_1.default.createElement("strong", null, "Market-TA.II")),
react_1.default.createElement("br", null),
"If you sell at ",
numeralFormat_1.numeralWrapper.formatMoney(sCost),
", then you will sell ",
numeralFormat_1.numeralWrapper.format(markup, "0.00000"),
"x as much compared to if you sold at market price."),
react_1.default.createElement("input", { className: "text-input", onChange: onChange, value: value, type: "number", style: { marginTop: "4px" } }),
react_1.default.createElement("div", { style: { display: 'block' } },
react_1.default.createElement("label", { className: "tooltip", htmlFor: "cmpy-mgmt-marketa2-checkbox", style: { color: "white" } },
"Use Market-TA.II for Auto-Sale Price",
react_1.default.createElement("span", { className: "tooltiptext" }, "If this is enabled, then this Product will automatically be sold at the optimal price such that the amount sold matches the amount produced. (i.e. the highest possible price, while still ensuring that all produced materials will be sold).")),
react_1.default.createElement("input", { className: "text-input", onChange: onCheckedChange, id: "cmpy-mgmt-marketa2-checkbox", style: { margin: "3px" }, type: "checkbox", checked: props.product.marketTa2 })),
react_1.default.createElement("p", null, "Note that Market-TA.II overrides Market-TA.I. This means that if both are enabled, then Market-TA.II will take effect, not Market-TA.I")));
}
// Create a popup that lets the player use the Market TA research for Products
function ProductMarketTaPopup(props) {
const markupLimit = props.product.rat / props.product.mku;
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
function onChange(event) {
props.product.marketTa1 = event.target.checked;
rerender();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
react_1.default.createElement("u", null,
react_1.default.createElement("strong", null, "Market-TA.I")),
react_1.default.createElement("br", null),
"The maximum sale price you can mark this up to is ",
numeralFormat_1.numeralWrapper.formatMoney(props.product.pCost + markupLimit),
". This means that if you set the sale price higher than this, you will begin to experience a loss in number of sales."),
react_1.default.createElement("div", { style: { display: 'block' } },
react_1.default.createElement("label", { className: "tooltip", htmlFor: "cmpy-mgmt-marketa1-checkbox", style: { color: "white" } },
"Use Market-TA.I for Auto-Sale Price",
react_1.default.createElement("span", { className: "tooltiptext" }, "If this is enabled, then this Product will automatically be sold at the price identified by Market-TA.I (i.e. the price shown above).")),
react_1.default.createElement("input", { onChange: onChange, className: "text-input", id: "cmpy-mgmt-marketa1-checkbox", style: { margin: "3px" }, type: "checkbox", checked: props.product.marketTa1 })),
props.industry.hasResearch("Market-TA.II") && react_1.default.createElement(MarketTA2, { product: props.product, industry: props.industry, popupId: props.popupId })));
}
exports.ProductMarketTaPopup = ProductMarketTaPopup;
/***/ }),
/* 1101 */
/*!******************************************************!*\
!*** ./src/Corporation/ui/PurchaseMaterialPopup.tsx ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PurchaseMaterialPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const MaterialSizes_1 = __webpack_require__(/*! ../MaterialSizes */ 400);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function BulkPurchaseText(props) {
const parsedAmt = parseFloat(props.amount);
const cost = parsedAmt * props.mat.bCost;
const matSize = MaterialSizes_1.MaterialSizes[props.mat.name];
const maxAmount = ((props.warehouse.size - props.warehouse.sizeUsed) / matSize);
if (parsedAmt * matSize > maxAmount) {
return (react_1.default.createElement(react_1.default.Fragment, null, "Not enough warehouse space to purchase this amount"));
}
else if (isNaN(cost)) {
return (react_1.default.createElement(react_1.default.Fragment, null, "Invalid put for Bulk Purchase amount"));
}
else {
return (react_1.default.createElement(react_1.default.Fragment, null,
"Purchasing ",
numeralFormat_1.numeralWrapper.format(parsedAmt, "0,0.00"),
" of",
props.mat.name,
" will cost ",
numeralFormat_1.numeralWrapper.formatMoney(cost)));
}
}
function BulkPurchase(props) {
const [buyAmt, setBuyAmt] = react_1.useState('');
function bulkPurchase() {
const amount = parseFloat(buyAmt);
const matSize = MaterialSizes_1.MaterialSizes[props.mat.name];
const maxAmount = ((props.warehouse.size - props.warehouse.sizeUsed) / matSize);
if (amount * matSize > maxAmount) {
DialogBox_1.dialogBoxCreate(`You do not have enough warehouse size to fit this purchase`);
return;
}
if (isNaN(amount)) {
DialogBox_1.dialogBoxCreate("Invalid input amount");
}
else {
const cost = amount * props.mat.bCost;
if (props.corp.funds.gt(cost)) {
props.corp.funds = props.corp.funds.minus(cost);
props.mat.qty += amount;
}
else {
DialogBox_1.dialogBoxCreate(`You cannot afford this purchase.`);
return;
}
createPopup_1.removePopup(props.popupId);
}
}
function onKeyDown(event) {
if (event.keyCode === 13)
bulkPurchase();
}
function onChange(event) {
setBuyAmt(event.target.value);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
"Enter the amount of ",
props.mat.name,
" you would like to bulk purchase. This purchases the specified amount instantly (all at once)."),
react_1.default.createElement(BulkPurchaseText, { warehouse: props.warehouse, mat: props.mat, amount: buyAmt }),
react_1.default.createElement("input", { onChange: onChange, type: "number", placeholder: "Bulk Purchase amount", style: { margin: "5px" }, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { className: "std-button" }, "Confirm Bulk Purchase")));
}
// Create a popup that lets the player purchase a Material
function PurchaseMaterialPopup(props) {
const [buyAmt, setBuyAmt] = react_1.useState(props.mat.buy ? props.mat.buy : null);
function purchaseMaterial() {
if (buyAmt === null)
return;
if (isNaN(buyAmt)) {
DialogBox_1.dialogBoxCreate("Invalid amount");
}
else {
props.mat.buy = buyAmt;
if (isNaN(props.mat.buy))
props.mat.buy = 0;
createPopup_1.removePopup(props.popupId);
}
}
function clearPurchase() {
props.mat.buy = 0;
createPopup_1.removePopup(props.popupId);
}
function onKeyDown(event) {
if (event.keyCode === 13)
purchaseMaterial();
}
function onChange(event) {
setBuyAmt(parseFloat(event.target.value));
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
"Enter the amount of ",
props.mat.name,
" you would like to purchase per second. This material's cost changes constantly."),
react_1.default.createElement("input", { onChange: onChange, className: "text-input", autoFocus: true, placeholder: "Purchase amount", type: "number", style: { margin: "5px" }, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { onClick: purchaseMaterial, className: "std-button" }, "Confirm"),
react_1.default.createElement("button", { onClick: clearPurchase, className: "std-button" }, "Clear Purchase"),
props.industry.hasResearch("Bulk Purchasing") && react_1.default.createElement(BulkPurchase, { corp: props.corp, mat: props.mat, industry: props.industry, warehouse: props.warehouse, popupId: props.popupId })));
}
exports.PurchaseMaterialPopup = PurchaseMaterialPopup;
/***/ }),
/* 1102 */
/*!*************************************************!*\
!*** ./src/Corporation/ui/SellProductPopup.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SellProductPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const Cities_1 = __webpack_require__(/*! ../../Locations/Cities */ 192);
function initialPrice(product) {
let val = product.sCost ? product.sCost + '' : '';
if (product.marketTa2) {
val += " (Market-TA.II)";
}
else if (product.marketTa1) {
val += " (Market-TA.I)";
}
return val;
}
// Create a popup that let the player manage sales of a material
function SellProductPopup(props) {
const [checked, setChecked] = react_1.useState(true);
const [iQty, setQty] = react_1.useState(props.product.sllman[props.city][1] ? props.product.sllman[props.city][1] : '');
const [px, setPx] = react_1.useState(initialPrice(props.product));
function onCheckedChange(event) {
setChecked(event.target.checked);
}
function sellProduct() {
//Parse price
if (px.includes("MP")) {
//Dynamically evaluated quantity. First test to make sure its valid
//Sanitize input, then replace dynamic variables with arbitrary numbers
let price = px.replace(/\s+/g, '');
price = price.replace(/[^-()\d/*+.MP]/g, '');
let temp = price.replace(/MP/g, '1');
try {
temp = eval(temp);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell quantity field: " + e);
return;
}
if (temp == null || isNaN(parseFloat(temp))) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell quantity field.");
return;
}
props.product.sCost = price; //Use sanitized price
}
else {
const cost = parseFloat(px);
if (isNaN(cost)) {
DialogBox_1.dialogBoxCreate("Invalid value for sell price field");
return;
}
props.product.sCost = cost;
}
// Array of all cities. Used later
const cities = Object.keys(Cities_1.Cities);
// Parse quantity
if (iQty.includes("MAX") || iQty.includes("PROD")) {
//Dynamically evaluated quantity. First test to make sure its valid
let qty = iQty.replace(/\s+/g, '');
qty = qty.replace(/[^-()\d/*+.MAXPROD]/g, '');
let temp = qty.replace(/MAX/g, '1');
temp = temp.replace(/PROD/g, '1');
try {
temp = eval(temp);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field: " + e);
return;
}
if (temp == null || isNaN(parseFloat(temp))) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field");
return;
}
if (checked) {
for (let i = 0; i < cities.length; ++i) {
const tempCity = cities[i];
props.product.sllman[tempCity][0] = true;
props.product.sllman[tempCity][1] = qty; //Use sanitized input
}
}
else {
props.product.sllman[props.city][0] = true;
props.product.sllman[props.city][1] = qty; //Use sanitized input
}
}
else if (isNaN(parseFloat(iQty))) {
DialogBox_1.dialogBoxCreate("Invalid value for sell quantity field! Must be numeric");
return;
}
else {
let qty = parseFloat(iQty);
if (isNaN(qty)) {
qty = 0;
}
if (qty === 0) {
if (checked) {
for (let i = 0; i < cities.length; ++i) {
const tempCity = cities[i];
props.product.sllman[tempCity][0] = false;
props.product.sllman[tempCity][1] = '';
}
}
else {
props.product.sllman[props.city][0] = false;
props.product.sllman[props.city][1] = '';
}
}
else {
if (checked) {
for (let i = 0; i < cities.length; ++i) {
const tempCity = cities[i];
props.product.sllman[tempCity][0] = true;
props.product.sllman[tempCity][1] = qty;
}
}
else {
props.product.sllman[props.city][0] = true;
props.product.sllman[props.city][1] = qty;
}
}
}
createPopup_1.removePopup(props.popupId);
}
function onAmtChange(event) {
setQty(event.target.value);
}
function onPriceChange(event) {
setPx(event.target.value);
}
function onKeyDown(event) {
if (event.keyCode === 13)
sellProduct();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
"Enter the maximum amount of ",
props.product.name,
" you would like to sell per second, as well as the price at which you would like to sell it at.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Setting the sell amount to 'MAX' will result in you always selling the maximum possible amount of the material.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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."),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { className: "text-input", value: iQty, autoFocus: true, type: "text", placeholder: "Sell amount", style: { marginTop: "4px" }, onChange: onAmtChange, onKeyDown: onKeyDown }),
react_1.default.createElement("input", { className: "text-input", value: px, type: "text", placeholder: "Sell price", style: { marginTop: "4px" }, onChange: onPriceChange, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { className: "std-button", onClick: sellProduct }, "Confirm"),
react_1.default.createElement("div", { style: { border: "1px solid white", display: "inline-block" } },
react_1.default.createElement("label", { htmlFor: props.popupId + '-checkbox' }, "Use same 'Sell Amount' for all cities"),
react_1.default.createElement("input", { checked: checked, onChange: onCheckedChange, id: props.popupId + "-checkbox", style: { margin: "2px" }, type: "checkbox" }))));
}
exports.SellProductPopup = SellProductPopup;
/***/ }),
/* 1103 */
/*!**************************************************!*\
!*** ./src/Corporation/ui/SellMaterialPopup.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SellMaterialPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function initialPrice(mat) {
let val = mat.sCost ? mat.sCost + '' : '';
if (mat.marketTa2) {
val += " (Market-TA.II)";
}
else if (mat.marketTa1) {
val += " (Market-TA.I)";
}
return val;
}
// Create a popup that let the player manage sales of a material
function SellMaterialPopup(props) {
const [amt, setAmt] = react_1.useState(props.mat.sllman[1] ? props.mat.sllman[1] : '');
const [price, setPrice] = react_1.useState(initialPrice(props.mat));
function sellMaterial() {
let p = price;
let qty = amt;
if (p === '')
p = '0';
if (qty === '')
qty = '0';
let cost = p.replace(/\s+/g, '');
cost = cost.replace(/[^-()\d/*+.MP]/g, ''); //Sanitize cost
let temp = cost.replace(/MP/g, props.mat.bCost + '');
try {
temp = eval(temp);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field: " + e);
return;
}
if (temp == null || isNaN(parseFloat(temp))) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field");
return;
}
if (cost.includes("MP")) {
props.mat.sCost = cost; //Dynamically evaluated
}
else {
props.mat.sCost = temp;
}
//Parse quantity
if (qty.includes("MAX") || qty.includes("PROD")) {
let q = qty.replace(/\s+/g, '');
q = q.replace(/[^-()\d/*+.MAXPROD]/g, '');
let tempQty = q.replace(/MAX/g, '1');
tempQty = tempQty.replace(/PROD/g, '1');
try {
tempQty = eval(tempQty);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field: " + e);
return;
}
if (tempQty == null || isNaN(parseFloat(tempQty))) {
DialogBox_1.dialogBoxCreate("Invalid value or expression for sell price field");
return;
}
props.mat.sllman[0] = true;
props.mat.sllman[1] = q; //Use sanitized input
}
else if (isNaN(parseFloat(qty))) {
DialogBox_1.dialogBoxCreate("Invalid value for sell quantity field! Must be numeric or 'MAX'");
return;
}
else {
let q = parseFloat(qty);
if (isNaN(q)) {
q = 0;
}
if (q === 0) {
props.mat.sllman[0] = false;
props.mat.sllman[1] = 0;
}
else {
props.mat.sllman[0] = true;
props.mat.sllman[1] = q;
}
}
createPopup_1.removePopup(props.popupId);
}
function onAmtChange(event) {
setAmt(event.target.value);
}
function onPriceChange(event) {
setPrice(event.target.value);
}
function onKeyDown(event) {
if (event.keyCode === 13)
sellMaterial();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
"Enter the maximum amount of ",
props.mat.name,
" you would like to sell per second, as well as the price at which you would like to sell at.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"Setting the sell amount to 'MAX' will result in you always selling the maximum possible amount of the material.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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.",
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
"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."),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { className: "text-input", value: amt, autoFocus: true, type: "text", placeholder: "Sell amount", style: { marginTop: "4px" }, onChange: onAmtChange, onKeyDown: onKeyDown }),
react_1.default.createElement("input", { className: "text-input", value: price, type: "text", placeholder: "Sell price", style: { marginTop: "4px" }, onChange: onPriceChange, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { className: "std-button", onClick: sellMaterial }, "Confirm")));
}
exports.SellMaterialPopup = SellMaterialPopup;
/***/ }),
/* 1104 */
/*!******************************************************!*\
!*** ./src/Corporation/ui/MaterialMarketTaPopup.tsx ***!
\******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaterialMarketTaPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
function MarketTA2(props) {
if (!props.industry.hasResearch("Market-TA.II"))
return (react_1.default.createElement(react_1.default.Fragment, null));
const [newCost, setNewCost] = react_1.useState(props.mat.bCost);
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
const markupLimit = props.mat.getMarkupLimit();
function onChange(event) {
if (event.target.value === "")
setNewCost(0);
else
setNewCost(parseFloat(event.target.value));
}
const sCost = newCost;
let markup = 1;
if (sCost > props.mat.bCost) {
//Penalty if difference between sCost and bCost is greater than markup limit
if ((sCost - props.mat.bCost) > markupLimit) {
markup = Math.pow(markupLimit / (sCost - props.mat.bCost), 2);
}
}
else if (sCost < props.mat.bCost) {
if (sCost <= 0) {
markup = 1e12; //Sell everything, essentially discard
}
else {
//Lower prices than market increases sales
markup = props.mat.bCost / sCost;
}
}
function onMarketTA2(event) {
props.mat.marketTa2 = event.target.checked;
rerender();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
react_1.default.createElement("br", null),
react_1.default.createElement("u", null,
react_1.default.createElement("strong", null, "Market-TA.II")),
react_1.default.createElement("br", null),
"If you sell at ",
numeralFormat_1.numeralWrapper.formatMoney(sCost),
", then you will sell ",
numeralFormat_1.numeralWrapper.format(markup, "0.00000"),
"x as much compared to if you sold at market price."),
react_1.default.createElement("input", { className: "text-input", type: "number", style: { marginTop: "4px" }, onChange: onChange, value: newCost }),
react_1.default.createElement("div", { style: { display: "block" } },
react_1.default.createElement("label", { className: "tooltip", htmlFor: "cmpy-mgmt-marketa2-checkbox", style: { color: "white" } },
"Use Market-TA.II for Auto-Sale Price",
react_1.default.createElement("span", { className: "tooltiptext" }, "If this is enabled, then this Material will automatically be sold at the optimal price such that the amount sold matches the amount produced. (i.e. the highest possible price, while still ensuring that all produced materials will be sold)")),
react_1.default.createElement("input", { id: "cmpy-mgmt-marketa2-checkbox", type: "checkbox", onChange: onMarketTA2, checked: props.mat.marketTa2, style: { margin: "3px" } })),
react_1.default.createElement("p", null, "Note that Market-TA.II overrides Market-TA.I. This means that if both are enabled, then Market-TA.II will take effect, not Market-TA.I")));
}
// Create a popup that lets the player use the Market TA research for Materials
function MaterialMarketTaPopup(props) {
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
const markupLimit = props.mat.getMarkupLimit();
function onMarketTA1(event) {
props.mat.marketTa1 = event.target.checked;
rerender();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
react_1.default.createElement("u", null,
react_1.default.createElement("strong", null, "Market-TA.I")),
react_1.default.createElement("br", null),
"The maximum sale price you can mark this up to is ",
numeralFormat_1.numeralWrapper.formatMoney(props.mat.bCost + markupLimit),
". This means that if you set the sale price higher than this, you will begin to experience a loss in number of sales"),
react_1.default.createElement("div", { style: { display: 'block' } },
react_1.default.createElement("label", { className: "tooltip", htmlFor: "cmpy-mgmt-marketa1-checkbox", style: { color: "white" } },
"Use Market-TA.I for Auto-Sale Price",
react_1.default.createElement("span", { className: "tooltiptext" }, "If this is enabled, then this Material will automatically be sold at the price identified by Market-TA.I (i.e. the price shown above)")),
react_1.default.createElement("input", { id: "cmpy-mgmt-marketa1-checkbox", type: "checkbox", onChange: onMarketTA1, checked: props.mat.marketTa1, style: { margin: "3px" } })),
react_1.default.createElement(MarketTA2, { mat: props.mat, industry: props.industry })));
}
exports.MaterialMarketTaPopup = MaterialMarketTaPopup;
/***/ }),
/* 1105 */
/*!************************************************************!*\
!*** ./src/Corporation/ui/LimitProductProductionPopup.tsx ***!
\************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LimitProductProductionPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
// Create a popup that lets the player limit the production of a product
function LimitProductProductionPopup(props) {
const [limit, setLimit] = react_1.useState(null);
function limitProductProduction() {
if (limit === null) {
props.product.prdman[props.city][0] = false;
createPopup_1.removePopup(props.popupId);
return;
}
const qty = limit;
if (isNaN(qty)) {
DialogBox_1.dialogBoxCreate("Invalid value entered");
return;
}
if (qty < 0) {
props.product.prdman[props.city][0] = false;
}
else {
props.product.prdman[props.city][0] = true;
props.product.prdman[props.city][1] = qty;
}
createPopup_1.removePopup(props.popupId);
}
function onKeyDown(event) {
if (event.keyCode === 13)
limitProductProduction();
}
function onChange(event) {
if (event.target.value === "")
setLimit(null);
else
setLimit(parseFloat(event.target.value));
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "Enter a limit to the amount of this product you would like to product per second. Leave the box empty to set no limit."),
react_1.default.createElement("input", { autoFocus: true, className: "text-input", style: { margin: "5px" }, placeholder: "Limit", type: "number", onChange: onChange, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { className: "std-button", style: { margin: "5px", display: "inline-block" }, onClick: limitProductProduction }, "Limit production")));
}
exports.LimitProductProductionPopup = LimitProductProductionPopup;
/***/ }),
/* 1106 */
/*!********************************************!*\
!*** ./src/Corporation/ui/ExportPopup.tsx ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExportPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
// Create a popup that lets the player manage exports
function ExportPopup(props) {
if (props.corp.divisions.length === 0)
throw new Error('Export popup created with no divisions.');
if (Object.keys(props.corp.divisions[0].warehouses).length === 0)
throw new Error('Export popup created in a division with no warehouses.');
const [industry, setIndustry] = react_1.useState(props.corp.divisions[0].name);
const [city, setCity] = react_1.useState(Object.keys(props.corp.divisions[0].warehouses)[0]);
const [amt, setAmt] = react_1.useState('');
const setRerender = react_1.useState(false)[1];
function rerender() {
setRerender(old => !old);
}
function onCityChange(event) {
setCity(event.target.value);
}
function onIndustryChange(event) {
setIndustry(event.target.value);
}
function onAmtChange(event) {
setAmt(event.target.value);
}
function exportMaterial() {
const industryName = industry;
const cityName = city;
console.log(`${industryName}, ${cityName}, ${amt}`);
// Sanitize amt
let sanitizedAmt = amt.replace(/\s+/g, '');
sanitizedAmt = sanitizedAmt.replace(/[^-()\d/*+.MAX]/g, '');
let temp = sanitizedAmt.replace(/MAX/g, '1');
try {
temp = eval(temp);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Invalid expression entered for export amount: " + e);
return;
}
const n = parseFloat(temp);
if (n == null || isNaN(n) || n < 0) {
DialogBox_1.dialogBoxCreate("Invalid amount entered for export");
return;
}
const exportObj = { ind: industryName, city: cityName, amt: sanitizedAmt };
console.log(exportObj);
props.mat.exp.push(exportObj);
createPopup_1.removePopup(props.popupId);
}
function removeExport(exp) {
for (let i = 0; i < props.mat.exp.length; ++i) {
if (props.mat.exp[i].ind !== exp.ind ||
props.mat.exp[i].city !== exp.city ||
props.mat.exp[i].amt !== exp.amt)
continue;
props.mat.exp.splice(i, 1);
break;
}
rerender();
}
const currentDivision = props.corp.divisions.find((division) => division.name === industry);
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "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."),
react_1.default.createElement("select", { className: "dropdown", onChange: onIndustryChange, defaultValue: industry }, props.corp.divisions.map((division) => react_1.default.createElement("option", { key: division.name, value: division.name }, division.name))),
react_1.default.createElement("select", { className: "dropdown", onChange: onCityChange, defaultValue: city }, currentDivision && Object.keys(currentDivision.warehouses).map((cityName) => {
if (currentDivision.warehouses[cityName] === 0)
return;
return (react_1.default.createElement("option", { key: cityName, value: cityName }, cityName));
})),
react_1.default.createElement("input", { className: "text-input", placeholder: "Export amount / s", onChange: onAmtChange }),
react_1.default.createElement("button", { className: "std-button", style: { display: "inline-block" }, onClick: exportMaterial }, "Export"),
react_1.default.createElement("p", null, "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."),
props.mat.exp.map((exp, index) => react_1.default.createElement("div", { key: index, className: "cmpy-mgmt-existing-export", onClick: () => removeExport(exp) },
"Industry: ",
exp.ind,
react_1.default.createElement("br", null),
"City: ",
exp.city,
react_1.default.createElement("br", null),
"Amount/s: ",
exp.amt))));
}
exports.ExportPopup = ExportPopup;
/***/ }),
/* 1107 */
/*!********************************************************!*\
!*** ./src/Corporation/ui/DiscontinueProductPopup.tsx ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscontinueProductPopup = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
// Create a popup that lets the player discontinue a product
function DiscontinueProductPopup(props) {
function discontinue() {
props.industry.discontinueProduct(props.product);
createPopup_1.removePopup(props.popupId);
props.corp.rerender(props.player);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "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"),
react_1.default.createElement("button", { className: "popup-box-button", onClick: discontinue }, "Discontinue")));
}
exports.DiscontinueProductPopup = DiscontinueProductPopup;
/***/ }),
/* 1108 */
/*!**************************************************!*\
!*** ./src/Corporation/ui/IndustryWarehouse.tsx ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndustryWarehouse = void 0;
// React Component for displaying an Industry's warehouse information
// (right-side panel in the Industry UI)
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 107);
const OfficeSpace_1 = __webpack_require__(/*! ../OfficeSpace */ 223);
const Material_1 = __webpack_require__(/*! ../Material */ 494);
const Product_1 = __webpack_require__(/*! ../Product */ 492);
const Warehouse_1 = __webpack_require__(/*! ../Warehouse */ 495);
const DiscontinueProductPopup_1 = __webpack_require__(/*! ./DiscontinueProductPopup */ 1107);
const ExportPopup_1 = __webpack_require__(/*! ./ExportPopup */ 1106);
const LimitProductProductionPopup_1 = __webpack_require__(/*! ./LimitProductProductionPopup */ 1105);
const MaterialMarketTaPopup_1 = __webpack_require__(/*! ./MaterialMarketTaPopup */ 1104);
const SellMaterialPopup_1 = __webpack_require__(/*! ./SellMaterialPopup */ 1103);
const SellProductPopup_1 = __webpack_require__(/*! ./SellProductPopup */ 1102);
const PurchaseMaterialPopup_1 = __webpack_require__(/*! ./PurchaseMaterialPopup */ 1101);
const ProductMarketTaPopup_1 = __webpack_require__(/*! ./ProductMarketTaPopup */ 1100);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const isString_1 = __webpack_require__(/*! ../../../utils/helpers/isString */ 72);
// Creates the UI for a single Product type
function ProductComponent(props) {
const corp = props.corp;
const division = props.division;
const city = props.city;
const product = props.product;
// Numeraljs formatters
const nf = "0.000";
const nfB = "0.000a"; // For numbers that might be big
const hasUpgradeDashboard = division.hasResearch("uPgrade: Dashboard");
// Total product gain = production - sale
const totalGain = product.data[city][1] - product.data[city][2];
// Sell button
let sellButtonText;
if (product.sllman[city][0]) {
if (isString_1.isString(product.sllman[city][1])) {
sellButtonText = `Sell (${numeralFormat_1.numeralWrapper.format(product.data[city][2], nfB)}/${product.sllman[city][1]})`;
}
else {
sellButtonText = `Sell (${numeralFormat_1.numeralWrapper.format(product.data[city][2], nfB)}/${numeralFormat_1.numeralWrapper.format(product.sllman[city][1], nfB)})`;
}
}
else {
sellButtonText = "Sell (0.000/0.000)";
}
if (product.marketTa2) {
sellButtonText += (" @ " + numeralFormat_1.numeralWrapper.formatMoney(product.marketTa2Price[city]));
}
else if (product.marketTa1) {
const markupLimit = product.rat / product.mku;
sellButtonText += (" @ " + numeralFormat_1.numeralWrapper.formatMoney(product.pCost + markupLimit));
}
else if (product.sCost) {
if (isString_1.isString(product.sCost)) {
sellButtonText += (" @ " + product.sCost);
}
else {
sellButtonText += (" @ " + numeralFormat_1.numeralWrapper.formatMoney(product.sCost));
}
}
function openSellProductPopup() {
const popupId = "cmpy-mgmt-limit-product-production-popup";
createPopup_1.createPopup(popupId, SellProductPopup_1.SellProductPopup, {
product: product,
city: city,
popupId: popupId,
});
}
// Limit Production button
let limitProductionButtonText = "Limit Production";
if (product.prdman[city][0]) {
limitProductionButtonText += " (" + numeralFormat_1.numeralWrapper.format(product.prdman[city][1], nf) + ")";
}
function openLimitProductProdutionPopup() {
const popupId = "cmpy-mgmt-limit-product-production-popup";
createPopup_1.createPopup(popupId, LimitProductProductionPopup_1.LimitProductProductionPopup, {
product: product,
city: city,
popupId: popupId,
});
}
function openDiscontinueProductPopup() {
const popupId = "cmpy-mgmt-discontinue-product-popup";
createPopup_1.createPopup(popupId, DiscontinueProductPopup_1.DiscontinueProductPopup, {
product: product,
industry: division,
corp: props.corp,
popupId: popupId,
player: props.player,
});
}
function openProductMarketTaPopup() {
const popupId = "cmpy-mgmt-marketta-popup";
createPopup_1.createPopup(popupId, ProductMarketTaPopup_1.ProductMarketTaPopup, {
product: product,
industry: division,
popupId: popupId,
});
}
// Unfinished Product
if (!product.fin) {
if (hasUpgradeDashboard) {
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-product-div" },
react_1.default.createElement("p", null,
"Designing ",
product.name,
"..."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
numeralFormat_1.numeralWrapper.format(product.prog, "0.00"),
"% complete"),
react_1.default.createElement("br", null),
react_1.default.createElement("div", null,
react_1.default.createElement("button", { className: "std-button", onClick: openSellProductPopup }, sellButtonText),
react_1.default.createElement("br", null),
react_1.default.createElement("button", { className: "std-button", onClick: openLimitProductProdutionPopup }, limitProductionButtonText),
react_1.default.createElement("button", { className: "std-button", onClick: openDiscontinueProductPopup }, "Discontinue"),
division.hasResearch("Market-TA.I") &&
react_1.default.createElement("button", { className: "std-button", onClick: openProductMarketTaPopup }, "Market-TA"))));
}
else {
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-product-div" },
react_1.default.createElement("p", null,
"Designing ",
product.name,
"..."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
numeralFormat_1.numeralWrapper.format(product.prog, "0.00"),
"% complete")));
}
}
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-product-div" },
react_1.default.createElement("p", { className: "tooltip" },
product.name,
": ",
numeralFormat_1.numeralWrapper.format(product.data[city][0], nfB),
" (",
numeralFormat_1.numeralWrapper.format(totalGain, nfB),
"/s)",
react_1.default.createElement("span", { className: "tooltiptext" },
"Prod: ",
numeralFormat_1.numeralWrapper.format(product.data[city][1], nfB),
"/s",
react_1.default.createElement("br", null),
"Sell: ",
numeralFormat_1.numeralWrapper.format(product.data[city][2], nfB),
" /s")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Rating: ",
numeralFormat_1.numeralWrapper.format(product.rat, nf),
react_1.default.createElement("span", { className: "tooltiptext" },
"Quality: ",
numeralFormat_1.numeralWrapper.format(product.qlt, nf),
" ",
react_1.default.createElement("br", null),
"Performance: ",
numeralFormat_1.numeralWrapper.format(product.per, nf),
" ",
react_1.default.createElement("br", null),
"Durability: ",
numeralFormat_1.numeralWrapper.format(product.dur, nf),
" ",
react_1.default.createElement("br", null),
"Reliability: ",
numeralFormat_1.numeralWrapper.format(product.rel, nf),
" ",
react_1.default.createElement("br", null),
"Aesthetics: ",
numeralFormat_1.numeralWrapper.format(product.aes, nf),
" ",
react_1.default.createElement("br", null),
"Features: ",
numeralFormat_1.numeralWrapper.format(product.fea, nf),
corp.unlockUpgrades[2] === 1 && react_1.default.createElement("br", null),
corp.unlockUpgrades[2] === 1 &&
"Demand: " + numeralFormat_1.numeralWrapper.format(product.dmd, nf),
corp.unlockUpgrades[3] === 1 && react_1.default.createElement("br", null),
corp.unlockUpgrades[3] === 1 &&
"Competition: " + numeralFormat_1.numeralWrapper.format(product.cmp, nf))),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Est. Production Cost: ",
numeralFormat_1.numeralWrapper.formatMoney(product.pCost / Constants_1.CorporationConstants.ProductProductionCostRatio),
react_1.default.createElement("span", { className: "tooltiptext" }, "An estimate of the material cost it takes to create this Product.")),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Est. Market Price: ",
numeralFormat_1.numeralWrapper.formatMoney(product.pCost),
react_1.default.createElement("span", { className: "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.")),
react_1.default.createElement("div", null,
react_1.default.createElement("button", { className: "std-button", onClick: openSellProductPopup }, sellButtonText),
react_1.default.createElement("br", null),
react_1.default.createElement("button", { className: "std-button", onClick: openLimitProductProdutionPopup }, limitProductionButtonText),
react_1.default.createElement("button", { className: "std-button", onClick: openDiscontinueProductPopup }, "Discontinue"),
division.hasResearch("Market-TA.I") &&
react_1.default.createElement("button", { className: "std-button", onClick: openProductMarketTaPopup }, "Market-TA"))));
}
// Creates the UI for a single Material type
function MaterialComponent(props) {
const corp = props.corp;
const division = props.division;
const warehouse = props.warehouse;
const city = props.city;
const mat = props.mat;
const markupLimit = mat.getMarkupLimit();
const office = division.offices[city];
if (!(office instanceof OfficeSpace_1.OfficeSpace)) {
throw new Error(`Could not get OfficeSpace object for this city (${city})`);
}
// Numeraljs formatter
const nf = "0.000";
const nfB = "0.000a"; // For numbers that might be biger
// Total gain or loss of this material (per second)
const totalGain = mat.buy + mat.prd + mat.imp - mat.sll - mat.totalExp;
// Flag that determines whether this industry is "new" and the current material should be
// marked with flashing-red lights
const tutorial = division.newInd && Object.keys(division.reqMats).includes(mat.name) &&
mat.buy === 0 && mat.imp === 0;
// Purchase material button
const purchaseButtonText = `Buy (${numeralFormat_1.numeralWrapper.format(mat.buy, nfB)})`;
const purchaseButtonClass = tutorial ? "std-button flashing-button tooltip" : "std-button";
function openPurchaseMaterialPopup() {
const popupId = "cmpy-mgmt-material-purchase-popup";
createPopup_1.createPopup(popupId, PurchaseMaterialPopup_1.PurchaseMaterialPopup, {
mat: mat,
industry: division,
warehouse: warehouse,
corp: props.corp,
popupId: popupId,
});
}
function openExportPopup() {
const popupId = "cmpy-mgmt-export-popup";
createPopup_1.createPopup(popupId, ExportPopup_1.ExportPopup, {
mat: mat,
corp: props.corp,
popupId: popupId,
});
}
// Sell material button
let sellButtonText;
if (mat.sllman[0]) {
if (isString_1.isString(mat.sllman[1])) {
sellButtonText = `Sell (${numeralFormat_1.numeralWrapper.format(mat.sll, nfB)}/${mat.sllman[1]})`;
}
else {
sellButtonText = `Sell (${numeralFormat_1.numeralWrapper.format(mat.sll, nfB)}/${numeralFormat_1.numeralWrapper.format(mat.sllman[1], nfB)})`;
}
if (mat.marketTa2) {
sellButtonText += " @ " + numeralFormat_1.numeralWrapper.formatMoney(mat.marketTa2Price);
}
else if (mat.marketTa1) {
sellButtonText += " @ " + numeralFormat_1.numeralWrapper.formatMoney(mat.bCost + markupLimit);
}
else if (mat.sCost) {
if (isString_1.isString(mat.sCost)) {
const sCost = mat.sCost.replace(/MP/g, mat.bCost + '');
sellButtonText += " @ " + numeralFormat_1.numeralWrapper.formatMoney(eval(sCost));
}
else {
sellButtonText += " @ " + numeralFormat_1.numeralWrapper.formatMoney(mat.sCost);
}
}
}
else {
sellButtonText = "Sell (0.000/0.000)";
}
function openSellMaterialPopup() {
const popupId = "cmpy-mgmt-material-sell-popup";
createPopup_1.createPopup(popupId, SellMaterialPopup_1.SellMaterialPopup, {
mat: mat,
corp: props.corp,
popupId: popupId,
});
}
function openMaterialMarketTaPopup() {
const popupId = "cmpy-mgmt-export-popup";
createPopup_1.createPopup(popupId, MaterialMarketTaPopup_1.MaterialMarketTaPopup, {
mat: mat,
industry: division,
corp: props.corp,
popupId: popupId,
});
}
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-material-div" },
react_1.default.createElement("div", { style: { display: "inline-block" } },
react_1.default.createElement("p", { className: "tooltip" },
mat.name,
": ",
numeralFormat_1.numeralWrapper.format(mat.qty, nfB),
" (",
numeralFormat_1.numeralWrapper.format(totalGain, nfB),
"/s)",
react_1.default.createElement("span", { className: "tooltiptext" },
"Buy: ",
numeralFormat_1.numeralWrapper.format(mat.buy, nfB),
" ",
react_1.default.createElement("br", null),
"Prod: ",
numeralFormat_1.numeralWrapper.format(mat.prd, nfB),
" ",
react_1.default.createElement("br", null),
"Sell: ",
numeralFormat_1.numeralWrapper.format(mat.sll, nfB),
" ",
react_1.default.createElement("br", null),
"Export: ",
numeralFormat_1.numeralWrapper.format(mat.totalExp, nfB),
" ",
react_1.default.createElement("br", null),
"Import: ",
numeralFormat_1.numeralWrapper.format(mat.imp, nfB),
corp.unlockUpgrades[2] === 1 && react_1.default.createElement("br", null),
corp.unlockUpgrades[2] === 1 &&
"Demand: " + numeralFormat_1.numeralWrapper.format(mat.dmd, nf),
corp.unlockUpgrades[3] === 1 && react_1.default.createElement("br", null),
corp.unlockUpgrades[3] === 1 &&
"Competition: " + numeralFormat_1.numeralWrapper.format(mat.cmp, nf))),
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"MP: ",
numeralFormat_1.numeralWrapper.formatMoney(mat.bCost),
react_1.default.createElement("span", { className: "tooltiptext" }, "Market Price: The price you would pay if you were to buy this material on the market")),
" ",
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Quality: ",
numeralFormat_1.numeralWrapper.format(mat.qlt, "0.00a"),
react_1.default.createElement("span", { className: "tooltiptext" }, "The quality of your material. Higher quality will lead to more sales"))),
react_1.default.createElement("div", { style: { display: "inline-block" } },
react_1.default.createElement("button", { className: purchaseButtonClass, onClick: openPurchaseMaterialPopup },
purchaseButtonText,
tutorial &&
react_1.default.createElement("span", { className: "tooltiptext" }, "Purchase your required materials to get production started!")),
corp.unlockUpgrades[0] === 1 &&
react_1.default.createElement("button", { className: "std-button", onClick: openExportPopup }, "Export"),
react_1.default.createElement("br", null),
react_1.default.createElement("button", { className: "std-button", onClick: openSellMaterialPopup }, sellButtonText),
division.hasResearch("Market-TA.I") &&
react_1.default.createElement("button", { className: "std-button", onClick: openMaterialMarketTaPopup }, "Market-TA"))));
}
function IndustryWarehouse(props) {
// Returns a boolean indicating whether the given material is relevant for the
// current industry.
function isRelevantMaterial(matName, division) {
// Materials that affect Production multiplier
const prodMultiplierMats = ["Hardware", "Robots", "AICores", "RealEstate"];
if (Object.keys(division.reqMats).includes(matName)) {
return true;
}
if (division.prodMats.includes(matName)) {
return true;
}
if (prodMultiplierMats.includes(matName)) {
return true;
}
return false;
}
function renderWarehouseUI() {
const corp = props.corp;
const division = props.routing.currentDivision; // Validated in render()
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
const warehouse = division.warehouses[props.currentCity]; // Validated in render()
// General Storage information at the top
const sizeUsageStyle = {
color: warehouse.sizeUsed >= warehouse.size ? "red" : "white",
margin: "5px",
};
// Upgrade Warehouse size button
const sizeUpgradeCost = Constants_1.CorporationConstants.WarehouseUpgradeBaseCost * Math.pow(1.07, warehouse.level + 1);
const canAffordUpgrade = (corp.funds.gt(sizeUpgradeCost));
const upgradeWarehouseClass = canAffordUpgrade ? "std-button" : "a-link-button-inactive";
function upgradeWarehouseOnClick() {
++warehouse.level;
warehouse.updateSize(corp, division);
corp.funds = corp.funds.minus(sizeUpgradeCost);
corp.rerender(props.player);
}
// Industry material Requirements
let generalReqsText = "This Industry uses [" + Object.keys(division.reqMats).join(", ") +
"] in order to ";
if (division.prodMats.length > 0) {
generalReqsText += "produce [" + division.prodMats.join(", ") + "] ";
if (division.makesProducts) {
generalReqsText += " and " + division.getProductDescriptionText();
}
}
else if (division.makesProducts) {
generalReqsText += (division.getProductDescriptionText() + ".");
}
const ratioLines = [];
for (const matName in division.reqMats) {
if (division.reqMats.hasOwnProperty(matName)) {
const text = [" *", division.reqMats[matName], matName].join(" ");
ratioLines.push((react_1.default.createElement("div", { key: matName },
react_1.default.createElement("p", null, text))));
}
}
let createdItemsText = "in order to create ";
if (division.prodMats.length > 0) {
createdItemsText += "one of each produced Material (" + division.prodMats.join(", ") + ") ";
if (division.makesProducts) {
createdItemsText += "or to create one of its Products";
}
}
else if (division.makesProducts) {
createdItemsText += "one of its Products";
}
// Current State:
let stateText;
switch (division.state) {
case "START":
stateText = "Current state: Preparing...";
break;
case "PURCHASE":
stateText = "Current state: Purchasing materials...";
break;
case "PRODUCTION":
stateText = "Current state: Producing materials and/or products...";
break;
case "SALE":
stateText = "Current state: Selling materials and/or products...";
break;
case "EXPORT":
stateText = "Current state: Exporting materials and/or products...";
break;
default:
console.error(`Invalid state: ${division.state}`);
break;
}
// Smart Supply Checkbox
const smartSupplyCheckboxId = "cmpy-mgmt-smart-supply-checkbox";
function smartSupplyOnChange(e) {
warehouse.smartSupplyEnabled = e.target.checked;
corp.rerender(props.player);
}
// Create React components for materials
const mats = [];
for (const matName in warehouse.materials) {
if (warehouse.materials[matName] instanceof Material_1.Material) {
// Only create UI for materials that are relevant for the industry
if (isRelevantMaterial(matName, division)) {
mats.push(react_1.default.createElement(MaterialComponent, { city: props.currentCity, corp: corp, division: division, key: matName, mat: warehouse.materials[matName], warehouse: warehouse }));
}
}
}
// Create React components for products
const products = [];
if (division.makesProducts && Object.keys(division.products).length > 0) {
for (const productName in division.products) {
if (division.products[productName] instanceof Product_1.Product) {
products.push(react_1.default.createElement(ProductComponent, { player: props.player, city: props.currentCity, corp: corp, division: division, key: productName, product: division.products[productName] }));
}
}
}
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-panel" },
react_1.default.createElement("p", { className: "tooltip", style: sizeUsageStyle },
"Storage: ",
numeralFormat_1.numeralWrapper.formatBigNumber(warehouse.sizeUsed),
" / ",
numeralFormat_1.numeralWrapper.formatBigNumber(warehouse.size),
react_1.default.createElement("span", { className: "tooltiptext", dangerouslySetInnerHTML: { __html: warehouse.breakdown } })),
react_1.default.createElement("button", { className: upgradeWarehouseClass, onClick: upgradeWarehouseOnClick },
"Upgrade Warehouse Size - ",
numeralFormat_1.numeralWrapper.formatMoney(sizeUpgradeCost)),
react_1.default.createElement("p", null,
generalReqsText,
". The exact requirements for production are:"),
react_1.default.createElement("br", null),
ratioLines,
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, createdItemsText),
react_1.default.createElement("p", null, "To get started with production, purchase your required materials or import them from another of your company's divisions."),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, stateText),
corp.unlockUpgrades[1] &&
react_1.default.createElement("div", null,
react_1.default.createElement("label", { style: { color: "white" }, htmlFor: smartSupplyCheckboxId }, "Enable Smart Supply"),
react_1.default.createElement("input", { type: "checkbox", id: smartSupplyCheckboxId, onChange: smartSupplyOnChange, style: { margin: "3px" }, checked: warehouse.smartSupplyEnabled })),
mats,
products));
}
const division = props.routing.currentDivision;
if (division == null) {
throw new Error(`Routing does not hold reference to the current Industry`);
}
const warehouse = division.warehouses[props.currentCity];
function purchaseWarehouse(division, city) {
if (props.corp.funds.lt(Constants_1.CorporationConstants.WarehouseInitialCost)) {
DialogBox_1.dialogBoxCreate("You do not have enough funds to do this!");
}
else {
division.warehouses[city] = new Warehouse_1.Warehouse({
corp: props.corp,
industry: division,
loc: city,
size: Constants_1.CorporationConstants.WarehouseInitialSize,
});
props.corp.funds = props.corp.funds.minus(Constants_1.CorporationConstants.WarehouseInitialCost);
props.corp.rerender(props.player);
}
}
if (warehouse instanceof Warehouse_1.Warehouse) {
return renderWarehouseUI();
}
else {
return (react_1.default.createElement("div", { className: "cmpy-mgmt-warehouse-panel" },
react_1.default.createElement("button", { className: "std-button", onClick: () => purchaseWarehouse(division, props.currentCity) },
"Purchase Warehouse (",
numeralFormat_1.numeralWrapper.formatMoney(Constants_1.CorporationConstants.WarehouseInitialCost),
")")));
}
}
exports.IndustryWarehouse = IndustryWarehouse;
/***/ }),
/* 1109 */,
/* 1110 */
/*!**********************************************!*\
!*** ./src/Corporation/ui/ResearchPopup.tsx ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResearchPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createElement_1 = __webpack_require__(/*! ../../../utils/uiHelpers/createElement */ 51);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const IndustryData_1 = __webpack_require__(/*! ../IndustryData */ 165);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 107);
const ResearchMap_1 = __webpack_require__(/*! ../ResearchMap */ 493);
const treant_js_1 = __webpack_require__(/*! treant-js */ 1109);
// Create the Research Tree UI for this Industry
function ResearchPopup(props) {
react_1.useEffect(() => {
const researchTree = IndustryData_1.IndustryResearchTrees[props.industry.type];
if (researchTree === undefined)
return;
// Get the tree's markup (i.e. config) for Treant
const markup = researchTree.createTreantMarkup();
markup.chart.container = "#" + props.popupId + "-content";
markup.chart.nodeAlign = "BOTTOM";
markup.chart.rootOrientation = "WEST";
markup.chart.siblingSeparation = 40;
markup.chart.connectors = {
type: "step",
style: {
"arrow-end": "block-wide-long",
"stroke": "white",
"stroke-width": 2,
},
};
treant_js_1.Treant(markup);
// Add Event Listeners for all Nodes
const allResearch = researchTree.getAllNodes();
for (let i = 0; i < allResearch.length; ++i) {
// If this is already Researched, skip it
if (props.industry.researched[allResearch[i]] === true) {
continue;
}
// Get the Research object
const research = ResearchMap_1.ResearchMap[allResearch[i]];
// Get the DOM Element to add a click listener to it
const sanitizedName = allResearch[i].replace(/\s/g, '');
const div = document.getElementById(sanitizedName + "-corp-research-click-listener");
if (div == null) {
console.warn(`Could not find Research Tree div for ${sanitizedName}`);
continue;
}
div.addEventListener("click", () => {
if (props.industry.sciResearch.qty >= research.cost) {
props.industry.sciResearch.qty -= research.cost;
// Get the Node from the Research Tree and set its 'researched' property
researchTree.research(allResearch[i]);
props.industry.researched[allResearch[i]] = true;
DialogBox_1.dialogBoxCreate(`Researched ${allResearch[i]}. It may take a market cycle ` +
`(~${Constants_1.CorporationConstants.SecsPerMarketCycle} seconds) before the effects of ` +
`the Research apply.`);
createPopup_1.removePopup(props.popupId);
}
else {
DialogBox_1.dialogBoxCreate(`You do not have enough Scientific Research for ${research.name}`);
}
});
}
const boxContent = document.getElementById(`${props.popupId}-content`);
if (boxContent != null) {
// Add information about multipliers from research at the bottom of the popup
//appendLineBreaks(boxContent, 2);
boxContent.appendChild(createElement_1.createElement("pre", {
display: "block",
innerText: `Multipliers from research:\n` +
` * Advertising Multiplier: x${researchTree.getAdvertisingMultiplier()}\n` +
` * Employee Charisma Multiplier: x${researchTree.getEmployeeChaMultiplier()}\n` +
` * Employee Creativity Multiplier: x${researchTree.getEmployeeCreMultiplier()}\n` +
` * Employee Efficiency Multiplier: x${researchTree.getEmployeeEffMultiplier()}\n` +
` * Employee Intelligence Multiplier: x${researchTree.getEmployeeIntMultiplier()}\n` +
` * Production Multiplier: x${researchTree.getProductionMultiplier()}\n` +
` * Sales Multiplier: x${researchTree.getSalesMultiplier()}\n` +
` * Scientific Research Multiplier: x${researchTree.getScientificResearchMultiplier()}\n` +
` * Storage Multiplier: x${researchTree.getStorageMultiplier()}`,
}));
}
});
return react_1.default.createElement("div", { id: props.popupId },
react_1.default.createElement("div", { id: props.popupId + 'outer-box' }));
}
exports.ResearchPopup = ResearchPopup;
/***/ }),
/* 1111 */
/*!*************************************************!*\
!*** ./src/Corporation/ui/MakeProductPopup.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MakeProductPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const IndustryData_1 = __webpack_require__(/*! ../IndustryData */ 165);
const Product_1 = __webpack_require__(/*! ../Product */ 492);
function productPlaceholder(tpe) {
if (tpe === IndustryData_1.Industries.Food) {
return "Restaurant Name";
}
else if (tpe === IndustryData_1.Industries.Healthcare) {
return "Hospital Name";
}
else if (tpe === IndustryData_1.Industries.RealEstate) {
return "Property Name";
}
return "Product Name";
}
// Create a popup that lets the player create a product for their current industry
function MakeProductPopup(props) {
const allCities = Object.keys(props.division.offices)
.filter((cityName) => props.division.offices[cityName] !== 0);
const [city, setCity] = react_1.useState(allCities.length > 0 ? allCities[0] : '');
const [name, setName] = react_1.useState('');
const [design, setDesign] = react_1.useState(null);
const [marketing, setMarketing] = react_1.useState(null);
if (props.division.hasMaximumNumberProducts())
return (react_1.default.createElement(react_1.default.Fragment, null));
function makeProduct() {
let designInvest = design;
let marketingInvest = marketing;
if (designInvest == null || designInvest < 0) {
designInvest = 0;
}
if (marketingInvest == null || marketingInvest < 0) {
marketingInvest = 0;
}
if (name == null || name === "") {
DialogBox_1.dialogBoxCreate("You must specify a name for your product!");
}
else if (isNaN(designInvest)) {
DialogBox_1.dialogBoxCreate("Invalid value for design investment");
}
else if (isNaN(marketingInvest)) {
DialogBox_1.dialogBoxCreate("Invalid value for marketing investment");
}
else if (props.corp.funds.lt(designInvest + marketingInvest)) {
DialogBox_1.dialogBoxCreate("You don't have enough company funds to make this large of an investment");
}
else {
const product = new Product_1.Product({
name: name.replace(/[<>]/g, ''),
createCity: city,
designCost: designInvest,
advCost: marketingInvest,
});
if (props.division.products[product.name] instanceof Product_1.Product) {
DialogBox_1.dialogBoxCreate(`You already have a product with this name!`);
return;
}
props.corp.funds = props.corp.funds.minus(designInvest + marketingInvest);
props.division.products[product.name] = product;
createPopup_1.removePopup(props.popupId);
}
}
function onCityChange(event) {
setCity(event.target.value);
}
function onProductNameChange(event) {
setName(event.target.value);
}
function onDesignChange(event) {
if (event.target.value === "")
setDesign(null);
else
setDesign(parseFloat(event.target.value));
}
function onMarketingChange(event) {
if (event.target.value === "")
setMarketing(null);
else
setMarketing(parseFloat(event.target.value));
}
function onKeyDown(event) {
if (event.keyCode === 13)
makeProduct();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", { dangerouslySetInnerHTML: { __html: props.popupText } }),
react_1.default.createElement("select", { className: "dropdown", style: { margin: "5px" }, onChange: onCityChange, defaultValue: city }, allCities.map((cityName) => react_1.default.createElement("option", { key: cityName, value: cityName }, cityName))),
react_1.default.createElement("input", { onChange: onProductNameChange, className: "text-input", style: { margin: "5px" }, placeholder: productPlaceholder(props.division.type) }),
react_1.default.createElement("br", null),
react_1.default.createElement("input", { onChange: onDesignChange, autoFocus: true, type: "number", className: "text-input", style: { margin: "5px" }, placeholder: "Design investment" }),
react_1.default.createElement("input", { onChange: onMarketingChange, onKeyDown: onKeyDown, type: "number", className: "text-input", style: { margin: "5px" }, placeholder: "Marketing investment" }),
react_1.default.createElement("button", { className: "std-button", onClick: makeProduct }, "Develop Product")));
}
exports.MakeProductPopup = MakeProductPopup;
/***/ }),
/* 1112 */
/*!*************************************************!*\
!*** ./src/Corporation/ui/IndustryOverview.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndustryOverview = void 0;
// React Component for displaying an Industry's overview information
// (top-left panel in the Industry UI)
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const OfficeSpace_1 = __webpack_require__(/*! ../OfficeSpace */ 223);
const IndustryData_1 = __webpack_require__(/*! ../IndustryData */ 165);
const IndustryUpgrades_1 = __webpack_require__(/*! ../IndustryUpgrades */ 692);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createProgressBarText_1 = __webpack_require__(/*! ../../../utils/helpers/createProgressBarText */ 189);
const MakeProductPopup_1 = __webpack_require__(/*! ./MakeProductPopup */ 1111);
const ResearchPopup_1 = __webpack_require__(/*! ./ResearchPopup */ 1110);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function IndustryOverview(props) {
function renderMakeProductButton() {
const division = props.routing.currentDivision; // Validated inside render()
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
let createProductButtonText = "";
let createProductPopupText = "";
switch (division.type) {
case IndustryData_1.Industries.Food:
createProductButtonText = "Build Restaurant";
createProductPopupText = "Build and manage a new restaurant!";
break;
case IndustryData_1.Industries.Tobacco:
createProductButtonText = "Create Product";
createProductPopupText = "Create a new tobacco product!";
break;
case IndustryData_1.Industries.Pharmaceutical:
createProductButtonText = "Create Drug";
createProductPopupText = "Design and develop a new pharmaceutical drug!";
break;
case IndustryData_1.Industries.Computer:
case "Computer":
createProductButtonText = "Create Product";
createProductPopupText = "Design and manufacture a new computer hardware product!";
break;
case IndustryData_1.Industries.Robotics:
createProductButtonText = "Design Robot";
createProductPopupText = "Design and create a new robot or robotic system!";
break;
case IndustryData_1.Industries.Software:
createProductButtonText = "Develop Software";
createProductPopupText = "Develop a new piece of software!";
break;
case IndustryData_1.Industries.Healthcare:
createProductButtonText = "Build Hospital";
createProductPopupText = "Build and manage a new hospital!";
break;
case IndustryData_1.Industries.RealEstate:
createProductButtonText = "Develop Property";
createProductPopupText = "Develop a new piece of real estate property!";
break;
default:
createProductButtonText = "Create Product";
createProductPopupText = "Create a new product!";
return (react_1.default.createElement(react_1.default.Fragment, null));
}
createProductPopupText += "
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.
" +
"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.";
const hasMaxProducts = division.hasMaximumNumberProducts();
const className = hasMaxProducts ? "a-link-button-inactive tooltip" : "std-button";
const buttonStyle = {
margin: "6px",
display: "inline-block",
};
function openMakeProductPopup() {
if (division === null)
return;
const popupId = "cmpy-mgmt-create-product-popup";
createPopup_1.createPopup(popupId, MakeProductPopup_1.MakeProductPopup, {
popupText: createProductPopupText,
division: division,
corp: props.corp,
popupId: popupId,
});
}
return (react_1.default.createElement("button", { className: className, onClick: openMakeProductPopup, style: buttonStyle },
createProductButtonText,
hasMaxProducts &&
react_1.default.createElement("span", { className: "tooltiptext" },
"You have reached the maximum number of products: ",
division.getMaximumNumberProducts())));
}
function renderText() {
const corp = props.corp;
const division = props.routing.currentDivision; // Validated inside render()
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
const vechain = (corp.unlockUpgrades[4] === 1);
const profit = division.lastCycleRevenue.minus(division.lastCycleExpenses).toNumber();
const genInfo = `Industry: ${division.type} (Corp Funds: ${numeralFormat_1.numeralWrapper.formatMoney(corp.funds.toNumber())})`;
const awareness = `Awareness: ${numeralFormat_1.numeralWrapper.format(division.awareness, "0.000")}`;
const popularity = `Popularity: ${numeralFormat_1.numeralWrapper.format(division.popularity, "0.000")}`;
let advertisingInfo = false;
const advertisingFactors = division.getAdvertisingFactors();
const awarenessFac = advertisingFactors[1];
const popularityFac = advertisingFactors[2];
const ratioFac = advertisingFactors[3];
const totalAdvertisingFac = advertisingFactors[0];
if (vechain) {
advertisingInfo = true;
}
const revenue = `Revenue: ${numeralFormat_1.numeralWrapper.formatMoney(division.lastCycleRevenue.toNumber())} / s`;
const expenses = `Expenses: ${numeralFormat_1.numeralWrapper.formatMoney(division.lastCycleExpenses.toNumber())} /s`;
const profitStr = `Profit: ${numeralFormat_1.numeralWrapper.formatMoney(profit)} / s`;
function productionMultHelpTipOnClick() {
if (division === null)
return;
// Wrapper for createProgressBarText()
// Converts the industry's "effectiveness factors"
// into a graphic (string) depicting how high that effectiveness is
function convertEffectFacToGraphic(fac) {
return createProgressBarText_1.createProgressBarText({
progress: fac,
totalTicks: 20,
});
}
DialogBox_1.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.
" +
"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.
" +
"Below are approximations for how effective each material is at boosting " +
"this industry's production multiplier (Bigger bars = more effective):
" +
`Hardware: ${convertEffectFacToGraphic(division.hwFac)} ` +
`Robots: ${convertEffectFacToGraphic(division.robFac)} ` +
`AI Cores: ${convertEffectFacToGraphic(division.aiFac)} ` +
`Real Estate: ${convertEffectFacToGraphic(division.reFac)}`);
}
function openResearchPopup() {
if (division === null)
return;
const popupId = "corporation-research-popup-box";
createPopup_1.createPopup(popupId, ResearchPopup_1.ResearchPopup, {
industry: division,
popupId: popupId,
});
}
return (react_1.default.createElement("div", null,
genInfo,
react_1.default.createElement("br", null),
" ",
react_1.default.createElement("br", null),
awareness,
" ",
react_1.default.createElement("br", null),
popularity,
" ",
react_1.default.createElement("br", null),
(advertisingInfo !== false) &&
react_1.default.createElement("p", { className: "tooltip" },
"Advertising Multiplier: x",
numeralFormat_1.numeralWrapper.format(totalAdvertisingFac, "0.000"),
react_1.default.createElement("span", { className: "tooltiptext cmpy-mgmt-advertising-info" },
"Total multiplier for this industrys sales due to its awareness and popularity",
react_1.default.createElement("br", null),
"Awareness Bonus: x",
numeralFormat_1.numeralWrapper.format(Math.pow(awarenessFac, 0.85), "0.000"),
react_1.default.createElement("br", null),
"Popularity Bonus: x",
numeralFormat_1.numeralWrapper.format(Math.pow(popularityFac, 0.85), "0.000"),
react_1.default.createElement("br", null),
"Ratio Multiplier: x",
numeralFormat_1.numeralWrapper.format(Math.pow(ratioFac, 0.85), "0.000"))),
advertisingInfo,
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
revenue,
" ",
react_1.default.createElement("br", null),
expenses,
" ",
react_1.default.createElement("br", null),
profitStr,
react_1.default.createElement("br", null),
" ",
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Production Multiplier: ",
numeralFormat_1.numeralWrapper.format(division.prodMult, "0.00"),
react_1.default.createElement("span", { className: "tooltiptext" }, "Production gain from owning production-boosting materials such as hardware, Robots, AI Cores, and Real Estate")),
react_1.default.createElement("div", { className: "help-tip", onClick: productionMultHelpTipOnClick }, "?"),
react_1.default.createElement("br", null),
" ",
react_1.default.createElement("br", null),
react_1.default.createElement("p", { className: "tooltip" },
"Scientific Research: ",
numeralFormat_1.numeralWrapper.format(division.sciResearch.qty, "0.000a"),
react_1.default.createElement("span", { className: "tooltiptext" }, "Scientific Research increases the quality of the materials and products that you produce.")),
react_1.default.createElement("button", { className: "help-tip", onClick: openResearchPopup }, "Research")));
}
function renderUpgrades() {
const corp = props.corp;
const division = props.routing.currentDivision; // Validated inside render()
if (division === null)
return ([react_1.default.createElement(react_1.default.Fragment, null)]);
const office = division.offices[props.currentCity];
if (!(office instanceof OfficeSpace_1.OfficeSpace)) {
throw new Error(`Current City (${props.currentCity}) for UI does not have an OfficeSpace object`);
}
const upgrades = [];
for (const index in IndustryUpgrades_1.IndustryUpgrades) {
const upgrade = IndustryUpgrades_1.IndustryUpgrades[index];
// AutoBrew research disables the Coffee upgrade
if (division.hasResearch("AutoBrew") && upgrade[4] === "Coffee") {
continue;
}
const i = upgrade[0];
const baseCost = upgrade[1];
const priceMult = upgrade[2];
let 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;
}
function onClick() {
if (division === null)
return;
if (corp.funds.lt(cost)) {
DialogBox_1.dialogBoxCreate("Insufficient funds");
}
else {
corp.funds = corp.funds.minus(cost);
division.upgrade(upgrade, {
corporation: corp,
office: office,
});
// corp.displayDivisionContent(division, city);
corp.rerender(props.player);
}
}
upgrades.push(renderUpgrade({
onClick: onClick,
text: `${upgrade[4]} - ${numeralFormat_1.numeralWrapper.formatMoney(cost)}`,
tooltip: upgrade[5],
}));
}
return upgrades;
}
function renderUpgrade(props) {
return (react_1.default.createElement("div", { className: "cmpy-mgmt-upgrade-div tooltip", onClick: props.onClick, key: props.text },
props.text,
props.tooltip != null &&
react_1.default.createElement("span", { className: "tooltiptext" }, props.tooltip)));
}
const division = props.routing.currentDivision;
if (division == null) {
throw new Error(`Routing does not hold reference to the current Industry`);
}
const makeProductButton = renderMakeProductButton();
return (react_1.default.createElement("div", { className: "cmpy-mgmt-industry-overview-panel" },
renderText(),
react_1.default.createElement("br", null),
react_1.default.createElement("u", { className: "industry-purchases-and-upgrades-header" }, "Purchases & Upgrades"),
react_1.default.createElement("br", null),
renderUpgrades(),
" ",
react_1.default.createElement("br", null),
division.makesProducts &&
makeProductButton));
}
exports.IndustryOverview = IndustryOverview;
/***/ }),
/* 1113 */
/*!************************************************!*\
!*** ./src/Corporation/ui/ThrowPartyPopup.tsx ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ThrowPartyPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
function ThrowPartyPopup(props) {
const [cost, setCost] = react_1.useState(null);
function changeCost(event) {
setCost(parseFloat(event.target.value));
}
function throwParty() {
if (cost === null || isNaN(cost) || cost < 0) {
DialogBox_1.dialogBoxCreate("Invalid value entered");
}
else {
const totalCost = cost * props.office.employees.length;
if (props.corp.funds.lt(totalCost)) {
DialogBox_1.dialogBoxCreate("You don't have enough company funds to throw a party!");
}
else {
props.corp.funds = props.corp.funds.minus(totalCost);
let mult;
for (let fooit = 0; fooit < props.office.employees.length; ++fooit) {
mult = props.office.employees[fooit].throwParty(cost);
}
DialogBox_1.dialogBoxCreate("You threw a party for the office! The morale and happiness " +
"of each employee increased by " + numeralFormat_1.numeralWrapper.formatPercentage((mult - 1)));
createPopup_1.removePopup(props.popupId);
}
}
}
function EffectText(props) {
let cost = props.cost;
if (cost !== null && (isNaN(cost) || cost < 0))
return react_1.default.createElement("p", null, "Invalid value entered!");
if (cost === null)
cost = 0;
return react_1.default.createElement("p", null,
"Throwing this party will cost a total of ",
numeralFormat_1.numeralWrapper.formatMoney(cost * props.office.employees.length));
}
function onKeyDown(event) {
if (event.keyCode === 13)
throwParty();
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "Enter the amount of money you would like to spend PER EMPLOYEE on this office party"),
react_1.default.createElement(EffectText, { cost: cost, office: props.office }),
react_1.default.createElement("input", { autoFocus: true, className: "text-input", type: "number", style: { margin: "5px" }, placeholder: "$ / employee", onChange: changeCost, onKeyDown: onKeyDown }),
react_1.default.createElement("button", { className: "std-button", onClick: throwParty }, "Throw Party")));
}
exports.ThrowPartyPopup = ThrowPartyPopup;
/***/ }),
/* 1114 */
/*!*******************************************************!*\
!*** ./src/Corporation/ui/UpgradeOfficeSizePopup.tsx ***!
\*******************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpgradeOfficeSizePopup = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 107);
function UpgradeOfficeSizePopup(props) {
const initialPriceMult = Math.round(props.office.size / Constants_1.CorporationConstants.OfficeInitialSize);
const costMultiplier = 1.09;
const upgradeCost = Constants_1.CorporationConstants.OfficeInitialCost * Math.pow(costMultiplier, initialPriceMult);
// Calculate cost to upgrade size by 15 employees
let mult = 0;
for (let i = 0; i < 5; ++i) {
mult += (Math.pow(costMultiplier, initialPriceMult + i));
}
const upgradeCost15 = Constants_1.CorporationConstants.OfficeInitialCost * mult;
//Calculate max upgrade size and cost
const maxMult = (props.corp.funds.dividedBy(Constants_1.CorporationConstants.OfficeInitialCost)).toNumber();
let maxNum = 1;
mult = Math.pow(costMultiplier, initialPriceMult);
while (maxNum < 50) { //Hard cap of 50x (extra 150 employees)
if (mult >= maxMult)
break;
const multIncrease = Math.pow(costMultiplier, initialPriceMult + maxNum);
if (mult + multIncrease > maxMult) {
break;
}
else {
mult += multIncrease;
}
++maxNum;
}
const upgradeCostMax = Constants_1.CorporationConstants.OfficeInitialCost * mult;
function upgradeSize(cost, size) {
if (props.corp.funds.lt(cost)) {
DialogBox_1.dialogBoxCreate("You don't have enough company funds to purchase this upgrade!");
}
else {
props.office.size += size;
props.corp.funds = props.corp.funds.minus(cost);
DialogBox_1.dialogBoxCreate("Office space increased! It can now hold " + props.office.size + " employees");
props.corp.rerender(props.player);
}
createPopup_1.removePopup(props.popupId);
}
function UpgradeSizeButton(props) {
return (react_1.default.createElement("button", { className: "tooltip " + (props.corp.funds.lt(props.cost) ? "a-link-button-inactive" : "a-link-button"), style: { display: "inline-block", margin: "4px" }, onClick: () => upgradeSize(props.cost, props.size) },
"by ",
props.size,
react_1.default.createElement("span", { className: "tooltiptext" }, numeralFormat_1.numeralWrapper.formatMoney(props.cost))));
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "Increase the size of your office space to fit additional employees!"),
react_1.default.createElement("p", null, "Upgrade size: "),
react_1.default.createElement(UpgradeSizeButton, { corp: props.corp, cost: upgradeCost, size: Constants_1.CorporationConstants.OfficeInitialSize }),
react_1.default.createElement(UpgradeSizeButton, { corp: props.corp, cost: upgradeCost15, size: Constants_1.CorporationConstants.OfficeInitialSize * 5 }),
react_1.default.createElement(UpgradeSizeButton, { corp: props.corp, cost: upgradeCostMax, size: maxNum * Constants_1.CorporationConstants.OfficeInitialSize })));
}
exports.UpgradeOfficeSizePopup = UpgradeOfficeSizePopup;
/***/ }),
/* 1115 */
/*!***********************************************!*\
!*** ./src/Corporation/ui/IndustryOffice.tsx ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndustryOffice = void 0;
// React Component for displaying an Industry's OfficeSpace information
// (bottom-left panel in the Industry UI)
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const OfficeSpace_1 = __webpack_require__(/*! ../OfficeSpace */ 223);
const EmployeePositions_1 = __webpack_require__(/*! ../EmployeePositions */ 282);
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const getSelectData_1 = __webpack_require__(/*! ../../../utils/uiHelpers/getSelectData */ 491);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const UpgradeOfficeSizePopup_1 = __webpack_require__(/*! ./UpgradeOfficeSizePopup */ 1114);
const ThrowPartyPopup_1 = __webpack_require__(/*! ./ThrowPartyPopup */ 1113);
function IndustryOffice(props) {
const [employeeManualAssignMode, setEmployeeManualAssignMode] = react_1.useState(false);
const [city, setCity] = react_1.useState("");
const [divisionName, setDivisionName] = react_1.useState("");
const [employee, setEmployee] = react_1.useState(null);
const [numEmployees, setNumEmployees] = react_1.useState(0);
const [numOperations, setNumOperations] = react_1.useState(0);
const [numEngineers, setNumEngineers] = react_1.useState(0);
const [numBusiness, setNumBusiness] = react_1.useState(0);
const [numManagement, setNumManagement] = react_1.useState(0);
const [numResearch, setNumResearch] = react_1.useState(0);
const [numUnassigned, setNumUnassigned] = react_1.useState(0);
const [numTraining, setNumTraining] = react_1.useState(0);
function resetEmployeeCount() {
setNumEmployees(0);
setNumOperations(0);
setNumEngineers(0);
setNumBusiness(0);
setNumManagement(0);
setNumResearch(0);
setNumUnassigned(0);
setNumTraining(0);
}
function updateEmployeeCount() {
const division = props.routing.currentDivision;
if (division == null) {
throw new Error(`Routing does not hold reference to the current Industry`);
}
const office = division.offices[props.currentCity];
if (!(office instanceof OfficeSpace_1.OfficeSpace)) {
throw new Error(`Current City (${props.currentCity}) for UI does not have an OfficeSpace object`);
}
// If we're in a new city, we have to reset the state
if (division.name !== divisionName || props.currentCity !== city) {
resetEmployeeCount();
setDivisionName(division.name);
setCity(props.currentCity);
}
// Calculate how many NEW employees we need to account for
const currentNumEmployees = office.employees.length;
let newOperations = numOperations;
let newEngineers = numEngineers;
let newBusiness = numBusiness;
let newManagement = numManagement;
let newResearch = numResearch;
let newUnassigned = numUnassigned;
let newTraining = numTraining;
// Record the number of employees in each position, for NEW employees only
for (let i = numEmployees; i < office.employees.length; ++i) {
switch (office.employees[i].pos) {
case EmployeePositions_1.EmployeePositions.Operations:
newOperations++;
break;
case EmployeePositions_1.EmployeePositions.Engineer:
newEngineers++;
break;
case EmployeePositions_1.EmployeePositions.Business:
newBusiness++;
break;
case EmployeePositions_1.EmployeePositions.Management:
newManagement++;
break;
case EmployeePositions_1.EmployeePositions.RandD:
newResearch++;
break;
case EmployeePositions_1.EmployeePositions.Unassigned:
newUnassigned++;
break;
case EmployeePositions_1.EmployeePositions.Training:
newTraining++;
break;
default:
console.error("Unrecognized employee position: " + office.employees[i].pos);
break;
}
}
if (newOperations !== numOperations)
setNumOperations(newOperations);
if (newEngineers !== numEngineers)
setNumEngineers(newEngineers);
if (newBusiness !== numBusiness)
setNumBusiness(newBusiness);
if (newManagement !== numManagement)
setNumManagement(newManagement);
if (newResearch !== numResearch)
setNumResearch(newResearch);
if (newUnassigned !== numUnassigned)
setNumUnassigned(newUnassigned);
if (newTraining !== numTraining)
setNumTraining(newTraining);
if (currentNumEmployees !== numEmployees)
setNumEmployees(currentNumEmployees);
}
updateEmployeeCount();
// Renders the "Employee Management" section of the Office UI
function renderEmployeeManagement() {
updateEmployeeCount();
if (employeeManualAssignMode) {
return renderManualEmployeeManagement();
}
else {
return renderAutomaticEmployeeManagement();
}
}
function renderAutomaticEmployeeManagement() {
const division = props.routing.currentDivision; // Validated in constructor
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
const office = division.offices[props.currentCity]; // Validated in constructor
const vechain = (props.corp.unlockUpgrades[4] === 1); // Has Vechain upgrade
function switchModeOnClick() {
setEmployeeManualAssignMode(true);
props.corp.rerender(props.player);
}
// Calculate average morale, happiness, and energy. Also salary
// TODO is this efficient?
let totalMorale = 0, totalHappiness = 0, totalEnergy = 0, totalSalary = 0;
for (let i = 0; i < office.employees.length; ++i) {
totalMorale += office.employees[i].mor;
totalHappiness += office.employees[i].hap;
totalEnergy += office.employees[i].ene;
totalSalary += office.employees[i].sal;
}
let avgMorale = 0, avgHappiness = 0, avgEnergy = 0;
if (office.employees.length > 0) {
avgMorale = totalMorale / office.employees.length;
avgHappiness = totalHappiness / office.employees.length;
avgEnergy = totalEnergy / office.employees.length;
}
// Helper functions for (re-)assigning employees to different positions
function assignEmployee(to) {
if (numUnassigned <= 0) {
console.warn("Cannot assign employee. No unassigned employees available");
return;
}
switch (to) {
case EmployeePositions_1.EmployeePositions.Operations:
setNumOperations(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.Engineer:
setNumEngineers(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.Business:
setNumBusiness(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.Management:
setNumManagement(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.RandD:
setNumResearch(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.Unassigned:
setNumUnassigned(n => n + 1);
break;
case EmployeePositions_1.EmployeePositions.Training:
setNumTraining(n => n + 1);
break;
default:
console.error("Unrecognized employee position: " + to);
break;
}
setNumUnassigned(n => n - 1);
office.assignEmployeeToJob(to);
office.calculateEmployeeProductivity({ corporation: props.corp, industry: division });
props.corp.rerender(props.player);
}
function unassignEmployee(from) {
function logWarning(pos) {
console.warn(`Cannot unassign from ${pos} because there is nobody assigned to that position`);
}
switch (from) {
case EmployeePositions_1.EmployeePositions.Operations:
if (numOperations <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumOperations(n => n - 1);
break;
case EmployeePositions_1.EmployeePositions.Engineer:
if (numEngineers <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumEngineers(n => n - 1);
break;
case EmployeePositions_1.EmployeePositions.Business:
if (numBusiness <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumBusiness(n => n - 1);
break;
case EmployeePositions_1.EmployeePositions.Management:
if (numManagement <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumManagement(n => n - 1);
break;
case EmployeePositions_1.EmployeePositions.RandD:
if (numResearch <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumResearch(n => n - 1);
break;
case EmployeePositions_1.EmployeePositions.Unassigned:
console.warn(`Tried to unassign from the Unassigned position`);
break;
case EmployeePositions_1.EmployeePositions.Training:
if (numTraining <= 0) {
return logWarning(EmployeePositions_1.EmployeePositions.Operations);
}
setNumTraining(n => n - 1);
break;
default:
console.error("Unrecognized employee position: " + from);
break;
}
setNumUnassigned(n => n + 1);
office.unassignEmployeeFromJob(from);
office.calculateEmployeeProductivity({ corporation: props.corp, industry: division });
props.corp.rerender(props.player);
}
const positionHeaderStyle = {
fontSize: "15px",
margin: "5px 0px 5px 0px",
width: "50%",
};
const assignButtonClass = numUnassigned > 0 ? "std-button" : "a-link-button-inactive";
function operationAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.Operations);
props.corp.rerender(props.player);
}
function operationUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.Operations);
props.corp.rerender(props.player);
}
const operationUnassignButtonClass = numOperations > 0 ? "std-button" : "a-link-button-inactive";
function engineerAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.Engineer);
props.corp.rerender(props.player);
}
function engineerUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.Engineer);
props.corp.rerender(props.player);
}
const engineerUnassignButtonClass = numEngineers > 0 ? "std-button" : "a-link-button-inactive";
function businessAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.Business);
props.corp.rerender(props.player);
}
function businessUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.Business);
props.corp.rerender(props.player);
}
const businessUnassignButtonClass = numBusiness > 0 ? "std-button" : "a-link-button-inactive";
function managementAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.Management);
props.corp.rerender(props.player);
}
function managementUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.Management);
props.corp.rerender(props.player);
}
const managementUnassignButtonClass = numManagement > 0 ? "std-button" : "a-link-button-inactive";
function rndAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.RandD);
props.corp.rerender(props.player);
}
function rndUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.RandD);
props.corp.rerender(props.player);
}
const rndUnassignButtonClass = numResearch > 0 ? "std-button" : "a-link-button-inactive";
function trainingAssignButtonOnClick() {
assignEmployee(EmployeePositions_1.EmployeePositions.Training);
props.corp.rerender(props.player);
}
function trainingUnassignButtonOnClick() {
unassignEmployee(EmployeePositions_1.EmployeePositions.Training);
props.corp.rerender(props.player);
}
const trainingUnassignButtonClass = numTraining > 0 ? "std-button" : "a-link-button-inactive";
return (react_1.default.createElement("div", null,
react_1.default.createElement("button", { className: "std-button tooltip", onClick: switchModeOnClick },
"Switch to Manual Mode",
react_1.default.createElement("span", { className: "tooltiptext" }, "Switch to Manual Assignment Mode, which allows you to specify which employees should get which jobs")),
react_1.default.createElement("p", null,
react_1.default.createElement("strong", null,
"Unassigned Employees: ",
numUnassigned)),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null,
"Avg Employee Morale: ",
numeralFormat_1.numeralWrapper.format(avgMorale, "0.000")),
react_1.default.createElement("p", null,
"Avg Employee Happiness: ",
numeralFormat_1.numeralWrapper.format(avgHappiness, "0.000")),
react_1.default.createElement("p", null,
"Avg Employee Energy: ",
numeralFormat_1.numeralWrapper.format(avgEnergy, "0.000")),
react_1.default.createElement("p", null,
"Total Employee Salary: ",
numeralFormat_1.numeralWrapper.formatMoney(totalSalary)),
vechain &&
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Material Production: ",
numeralFormat_1.numeralWrapper.format(division.getOfficeProductivity(office), "0.000"),
react_1.default.createElement("span", { className: "tooltiptext" }, "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")),
vechain && react_1.default.createElement("br", null),
vechain &&
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Product Production: ",
numeralFormat_1.numeralWrapper.format(division.getOfficeProductivity(office, { forProduct: true }), "0.000"),
react_1.default.createElement("span", { className: "tooltiptext" }, "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")),
vechain && react_1.default.createElement("br", null),
vechain &&
react_1.default.createElement("p", { className: "tooltip", style: { display: "inline-block" } },
"Business Multiplier: x",
numeralFormat_1.numeralWrapper.format(division.getBusinessFactor(office), "0.000"),
react_1.default.createElement("span", { className: "tooltiptext" }, "The effect this office's 'Business' employees has on boosting sales")),
vechain && react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.Operations,
" (",
numOperations,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Manages supply chain operations. Improves the amount of Materials and Products you produce.")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: operationAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: operationUnassignButtonClass, onClick: operationUnassignButtonOnClick }, "-"),
react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.Engineer,
" (",
numEngineers,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Develops and maintains products and production systems. Increases the quality of everything you produce. Also increases the amount you produce (not as much as Operations, however)")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: engineerAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: engineerUnassignButtonClass, onClick: engineerUnassignButtonOnClick }, "-"),
react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.Business,
" (",
numBusiness,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Handles sales and finances. Improves the amount of Materials and Products you can sell.")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: businessAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: businessUnassignButtonClass, onClick: businessUnassignButtonOnClick }, "-"),
react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.Management,
" (",
numManagement,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Leads and oversees employees and office operations. Improves the effectiveness of Engineer and Operations employees")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: managementAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: managementUnassignButtonClass, onClick: managementUnassignButtonOnClick }, "-"),
react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.RandD,
" (",
numResearch,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Research new innovative ways to improve the company. Generates Scientific Research")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: rndAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: rndUnassignButtonClass, onClick: rndUnassignButtonOnClick }, "-"),
react_1.default.createElement("br", null),
react_1.default.createElement("h2", { className: "tooltip", style: positionHeaderStyle },
EmployeePositions_1.EmployeePositions.Training,
" (",
numTraining,
")",
react_1.default.createElement("span", { className: "tooltiptext" }, "Set employee to training, which will increase some of their stats. Employees in training do not affect any company operations.")),
react_1.default.createElement("button", { className: assignButtonClass, onClick: trainingAssignButtonOnClick }, "+"),
react_1.default.createElement("button", { className: trainingUnassignButtonClass, onClick: trainingUnassignButtonOnClick }, "-")));
}
function renderManualEmployeeManagement() {
const corp = props.corp;
const division = props.routing.currentDivision; // Validated in constructor
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
const office = division.offices[props.currentCity]; // Validated in constructor
function switchModeOnClick() {
setEmployeeManualAssignMode(false);
props.corp.rerender(props.player);
}
const employeeInfoDivStyle = {
color: "white",
margin: "4px",
padding: "4px",
};
// Employee Selector
const employees = [];
for (let i = 0; i < office.employees.length; ++i) {
employees.push(react_1.default.createElement("option", { key: office.employees[i].name }, office.employees[i].name));
}
function employeeSelectorOnChange(e) {
const name = getSelectData_1.getSelectText(e.target);
for (let i = 0; i < office.employees.length; ++i) {
if (name === office.employees[i].name) {
setEmployee(office.employees[i]);
break;
}
}
corp.rerender(props.player);
}
// Employee Positions Selector
const emp = employee;
let employeePositionSelectorInitialValue = "";
const employeePositions = [];
const positionNames = Object.values(EmployeePositions_1.EmployeePositions);
for (let i = 0; i < positionNames.length; ++i) {
employeePositions.push(react_1.default.createElement("option", { key: positionNames[i], value: positionNames[i] }, positionNames[i]));
if (emp != null && emp.pos === positionNames[i]) {
employeePositionSelectorInitialValue = positionNames[i];
}
}
function employeePositionSelectorOnChange(e) {
if (employee === null)
return;
const pos = getSelectData_1.getSelectText(e.target);
employee.pos = pos;
resetEmployeeCount();
corp.rerender(props.player);
}
// Numeraljs formatter
const nf = "0.000";
// Employee stats (after applying multipliers)
const effCre = emp ? emp.cre * corp.getEmployeeCreMultiplier() * division.getEmployeeCreMultiplier() : 0;
const effCha = emp ? emp.cha * corp.getEmployeeChaMultiplier() * division.getEmployeeChaMultiplier() : 0;
const effInt = emp ? emp.int * corp.getEmployeeIntMultiplier() * division.getEmployeeIntMultiplier() : 0;
const effEff = emp ? emp.eff * corp.getEmployeeEffMultiplier() * division.getEmployeeEffMultiplier() : 0;
return (react_1.default.createElement("div", null,
react_1.default.createElement("button", { className: "std-button tooltip", onClick: switchModeOnClick },
"Switch to Auto Mode",
react_1.default.createElement("span", { className: "tooltiptext" }, "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")),
react_1.default.createElement("div", { style: employeeInfoDivStyle },
react_1.default.createElement("select", { onChange: employeeSelectorOnChange }, employees),
employee != null &&
react_1.default.createElement("p", null,
"Morale: ",
numeralFormat_1.numeralWrapper.format(employee.mor, nf),
react_1.default.createElement("br", null),
"Happiness: ",
numeralFormat_1.numeralWrapper.format(employee.hap, nf),
react_1.default.createElement("br", null),
"Energy: ",
numeralFormat_1.numeralWrapper.format(employee.ene, nf),
react_1.default.createElement("br", null),
"Intelligence: ",
numeralFormat_1.numeralWrapper.format(effInt, nf),
react_1.default.createElement("br", null),
"Charisma: ",
numeralFormat_1.numeralWrapper.format(effCha, nf),
react_1.default.createElement("br", null),
"Experience: ",
numeralFormat_1.numeralWrapper.format(employee.exp, nf),
react_1.default.createElement("br", null),
"Creativity: ",
numeralFormat_1.numeralWrapper.format(effCre, nf),
react_1.default.createElement("br", null),
"Efficiency: ",
numeralFormat_1.numeralWrapper.format(effEff, nf),
react_1.default.createElement("br", null),
"Salary: ",
numeralFormat_1.numeralWrapper.formatMoney(employee.sal)),
employee != null &&
react_1.default.createElement("select", { onChange: employeePositionSelectorOnChange, value: employeePositionSelectorInitialValue }, employeePositions))));
}
const corp = props.corp;
const division = props.routing.currentDivision; // Validated in constructor
if (division === null)
return (react_1.default.createElement(react_1.default.Fragment, null));
const office = division.offices[props.currentCity]; // Validated in constructor
const buttonStyle = {
fontSize: "13px",
};
// Hire Employee button
let hireEmployeeButtonClass = "tooltip";
if (office.atCapacity()) {
hireEmployeeButtonClass += " a-link-button-inactive";
}
else {
hireEmployeeButtonClass += " std-button";
if (office.employees.length === 0) {
hireEmployeeButtonClass += " flashing-button";
}
}
function hireEmployeeButtonOnClick() {
office.findEmployees(props.player, { corporation: corp, industry: division });
}
// Autohire employee button
let autohireEmployeeButtonClass = "tooltip";
if (office.atCapacity()) {
autohireEmployeeButtonClass += " a-link-button-inactive";
}
else {
autohireEmployeeButtonClass += " std-button";
}
function autohireEmployeeButtonOnClick() {
if (office.atCapacity())
return;
office.hireRandomEmployee();
props.corp.rerender(props.player);
}
function openUpgradeOfficeSizePopup() {
const popupId = "cmpy-mgmt-upgrade-office-size-popup";
createPopup_1.createPopup(popupId, UpgradeOfficeSizePopup_1.UpgradeOfficeSizePopup, {
office: office,
corp: props.corp,
popupId: popupId,
player: props.player,
});
}
function openThrowPartyPopup() {
const popupId = "cmpy-mgmt-throw-office-party-popup";
createPopup_1.createPopup(popupId, ThrowPartyPopup_1.ThrowPartyPopup, {
office: office,
corp: props.corp,
popupId: popupId,
});
}
return (react_1.default.createElement("div", { className: "cmpy-mgmt-employee-panel" },
react_1.default.createElement("h1", { style: { margin: "4px 0px 5px 0px" } }, "Office Space"),
react_1.default.createElement("p", null,
"Size: ",
office.employees.length,
" / ",
office.size,
" employees"),
react_1.default.createElement("button", { className: hireEmployeeButtonClass, onClick: hireEmployeeButtonOnClick, style: buttonStyle },
"Hire Employee",
office.employees.length === 0 &&
react_1.default.createElement("span", { className: "tooltiptext" }, "You'll need to hire some employees to get your operations started! It's recommended to have at least one employee in every position")),
react_1.default.createElement("button", { className: autohireEmployeeButtonClass, onClick: autohireEmployeeButtonOnClick, style: buttonStyle },
"Autohire Employee",
react_1.default.createElement("span", { className: "tooltiptext" }, "Automatically hires an employee and gives him/her a random name")),
react_1.default.createElement("br", null),
react_1.default.createElement("button", { className: "std-button tooltip", onClick: openUpgradeOfficeSizePopup, style: buttonStyle },
"Upgrade size",
react_1.default.createElement("span", { className: "tooltiptext" }, "Upgrade the office's size so that it can hold more employees!")),
!division.hasResearch("AutoPartyManager") &&
react_1.default.createElement("button", { className: "std-button tooltip", onClick: openThrowPartyPopup, style: buttonStyle },
"Throw Party",
react_1.default.createElement("span", { className: "tooltiptext" }, "\"Throw an office party to increase your employee's morale and happiness\"")),
react_1.default.createElement("br", null),
renderEmployeeManagement()));
}
exports.IndustryOffice = IndustryOffice;
/***/ }),
/* 1116 */
/*!*****************************************!*\
!*** ./src/Corporation/ui/Industry.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Industry = void 0;
// React Component for managing the Corporation's Industry UI
// This Industry component does NOT include the city tabs at the top
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const IndustryOffice_1 = __webpack_require__(/*! ./IndustryOffice */ 1115);
const IndustryOverview_1 = __webpack_require__(/*! ./IndustryOverview */ 1112);
const IndustryWarehouse_1 = __webpack_require__(/*! ./IndustryWarehouse */ 1108);
function Industry(props) {
return (react_1.default.createElement("div", null,
react_1.default.createElement("div", { className: "cmpy-mgmt-industry-left-panel" },
react_1.default.createElement(IndustryOverview_1.IndustryOverview, { player: props.player, routing: props.routing, corp: props.corp, currentCity: props.currentCity }),
react_1.default.createElement(IndustryOffice_1.IndustryOffice, { player: props.player, routing: props.routing, corp: props.corp, currentCity: props.currentCity })),
react_1.default.createElement("div", { className: "cmpy-mgmt-industry-right-panel" },
react_1.default.createElement(IndustryWarehouse_1.IndustryWarehouse, { player: props.player, corp: props.corp, routing: props.routing, currentCity: props.currentCity }))));
}
exports.Industry = Industry;
/***/ }),
/* 1117 */
/*!***************************************************!*\
!*** ./src/Corporation/ui/ExpandNewCityPopup.tsx ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpandNewCityPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const numeralFormat_1 = __webpack_require__(/*! ../../ui/numeralFormat */ 7);
const Constants_1 = __webpack_require__(/*! ../data/Constants */ 107);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const OfficeSpace_1 = __webpack_require__(/*! ../OfficeSpace */ 223);
function ExpandNewCityPopup(props) {
const dropdown = react_1.useRef(null);
function expand() {
if (dropdown.current === null)
return;
const city = dropdown.current.value;
if (props.corp.funds.lt(Constants_1.CorporationConstants.OfficeInitialCost)) {
DialogBox_1.dialogBoxCreate("You don't have enough company funds to open a new office!");
}
else {
props.corp.funds = props.corp.funds.minus(Constants_1.CorporationConstants.OfficeInitialCost);
DialogBox_1.dialogBoxCreate(`Opened a new office in ${city}!`);
props.division.offices[city] = new OfficeSpace_1.OfficeSpace({
loc: city,
size: Constants_1.CorporationConstants.OfficeInitialSize,
});
}
props.cityStateSetter(city);
createPopup_1.removePopup(props.popupId);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null,
"Would you like to expand into a new city by opening an office? This would cost ",
numeralFormat_1.numeralWrapper.format(Constants_1.CorporationConstants.OfficeInitialCost, '$0.000a')),
react_1.default.createElement("select", { ref: dropdown, className: "dropdown", style: { margin: "5px" } }, Object.keys(props.division.offices)
.filter((cityName) => props.division.offices[cityName] === 0)
.map((cityName) => react_1.default.createElement("option", { key: cityName, value: cityName }, cityName))),
react_1.default.createElement("button", { className: "std-button", style: { display: "inline-block" }, onClick: expand }, "Confirm")));
}
exports.ExpandNewCityPopup = ExpandNewCityPopup;
/***/ }),
/* 1118 */
/*!****************************************!*\
!*** ./src/Corporation/ui/CityTab.tsx ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CityTab = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
function CityTab(props) {
let className = "cmpy-mgmt-city-tab";
if (props.current) {
className += " current";
}
return (react_1.default.createElement("button", { className: className, onClick: props.onClick }, props.name));
}
exports.CityTab = CityTab;
/***/ }),
/* 1119 */
/*!*****************************************!*\
!*** ./src/Corporation/ui/CityTabs.tsx ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CityTabs = void 0;
// React Components for the Corporation UI's City navigation tabs
// These allow player to navigate between different cities for each industry
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const CityTab_1 = __webpack_require__(/*! ./CityTab */ 1118);
const ExpandNewCityPopup_1 = __webpack_require__(/*! ./ExpandNewCityPopup */ 1117);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function CityTabs(props) {
const division = props.routing.currentDivision;
function openExpandNewCityModal() {
const popupId = "cmpy-mgmt-expand-city-popup";
createPopup_1.createPopup(popupId, ExpandNewCityPopup_1.ExpandNewCityPopup, {
popupId: popupId,
corp: props.corp,
division: division,
cityStateSetter: props.cityStateSetter,
});
}
return react_1.default.createElement(react_1.default.Fragment, null,
Object.keys(props.onClicks).map((cityName) => react_1.default.createElement(CityTab_1.CityTab, { current: props.city === cityName, key: cityName, name: cityName, onClick: props.onClicks[cityName] })),
react_1.default.createElement(CityTab_1.CityTab, { current: false, key: "Expand into new City", name: "Expand into new City", onClick: openExpandNewCityModal }));
}
exports.CityTabs = CityTabs;
/***/ }),
/* 1120 */
/*!******************************************!*\
!*** ./src/Corporation/ui/MainPanel.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MainPanel = void 0;
// React Component for the element that contains the actual info/data
// for the Corporation UI. This panel lies below the header tabs and will
// be filled with whatever is needed based on the routing/navigation
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const CityTabs_1 = __webpack_require__(/*! ./CityTabs */ 1119);
const Industry_1 = __webpack_require__(/*! ./Industry */ 1116);
const Overview_1 = __webpack_require__(/*! ./Overview */ 1099);
const OfficeSpace_1 = __webpack_require__(/*! ../OfficeSpace */ 223);
const CityNames_1 = __webpack_require__(/*! ../../Locations/data/CityNames */ 42);
function MainPanel(props) {
const [division, setDivision] = react_1.useState("");
const [city, setCity] = react_1.useState(CityNames_1.CityName.Sector12);
// We can pass this setter to child components
function changeCityState(newCity) {
if (Object.values(CityNames_1.CityName).includes(newCity)) {
setCity(newCity);
}
else {
console.error(`Tried to change MainPanel's city state to an invalid city: ${newCity}`);
}
}
function renderOverviewPage() {
return (react_1.default.createElement("div", { id: "cmpy-mgmt-panel" },
react_1.default.createElement(Overview_1.Overview, Object.assign({}, props))));
}
function renderDivisionPage() {
// Note: Division is the same thing as Industry...I wasn't consistent with naming
const division = props.routing.currentDivision;
if (division == null) {
throw new Error(`Routing does not hold reference to the current Industry`);
}
// City tabs
const onClicks = {};
for (const cityName in division.offices) {
if (division.offices[cityName] instanceof OfficeSpace_1.OfficeSpace) {
onClicks[cityName] = () => {
setCity(cityName);
props.corp.rerender(props.player);
};
}
}
const cityTabs = (react_1.default.createElement(CityTabs_1.CityTabs, Object.assign({}, props, { corp: props.corp, city: city, onClicks: onClicks, cityStateSetter: changeCityState })));
return (react_1.default.createElement("div", { id: "cmpy-mgmt-panel" },
cityTabs,
react_1.default.createElement(Industry_1.Industry, Object.assign({}, props, { currentCity: city }))));
}
if (props.routing.isOnOverviewPage()) {
// Corporation overview Content
return renderOverviewPage();
}
else {
// Division content
// First, check if we're at a new division. If so, we need to reset the city to Sector-12
// Otherwise, just switch the 'city' state
const currentDivision = props.routing.current();
if (currentDivision !== division) {
setDivision(currentDivision);
setCity(CityNames_1.CityName.Sector12);
}
return renderDivisionPage();
}
}
exports.MainPanel = MainPanel;
/***/ }),
/* 1121 */
/*!****************************************!*\
!*** ./src/Locations/createCityMap.ts ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCityMap = void 0;
/**
* Utility function that creates a "city map", which is an object where
* each city is a key (property).
*
* This map uses the official name of the city, NOT its key in the 'Cities' object
*/
const Cities_1 = __webpack_require__(/*! ./Cities */ 192);
function createCityMap(initValue) {
const map = {};
const cities = Object.keys(Cities_1.Cities);
for (let i = 0; i < cities.length; ++i) {
map[cities[i]] = initValue;
}
return map;
}
exports.createCityMap = createCityMap;
/***/ }),
/* 1122 */
/*!*************************************************!*\
!*** ./src/Corporation/ProductRatingWeights.ts ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProductRatingWeights = void 0;
const IndustryData_1 = __webpack_require__(/*! ./IndustryData */ 165);
exports.ProductRatingWeights = {
[IndustryData_1.Industries.Food]: {
Quality: 0.7,
Durability: 0.1,
Aesthetics: 0.2,
},
[IndustryData_1.Industries.Tobacco]: {
Quality: 0.4,
Durability: 0.2,
Reliability: 0.2,
Aesthetics: 0.2,
},
[IndustryData_1.Industries.Pharmaceutical]: {
Quality: 0.2,
Performance: 0.2,
Durability: 0.1,
Reliability: 0.3,
Features: 0.2,
},
[IndustryData_1.Industries.Computer]: {
Quality: 0.15,
Performance: 0.25,
Durability: 0.25,
Reliability: 0.2,
Aesthetics: 0.05,
Features: 0.1,
},
"Computer": {
Quality: 0.15,
Performance: 0.25,
Durability: 0.25,
Reliability: 0.2,
Aesthetics: 0.05,
Features: 0.1,
},
[IndustryData_1.Industries.Robotics]: {
Quality: 0.1,
Performance: 0.2,
Durability: 0.2,
Reliability: 0.2,
Aesthetics: 0.1,
Features: 0.2,
},
[IndustryData_1.Industries.Software]: {
Quality: 0.2,
Performance: 0.2,
Reliability: 0.2,
Durability: 0.2,
Features: 0.2,
},
[IndustryData_1.Industries.Healthcare]: {
Quality: 0.4,
Performance: 0.1,
Durability: 0.1,
Reliability: 0.3,
Features: 0.1,
},
[IndustryData_1.Industries.RealEstate]: {
Quality: 0.2,
Durability: 0.25,
Reliability: 0.1,
Aesthetics: 0.35,
Features: 0.1,
},
};
/***/ }),
/* 1123 */
/*!*************************************!*\
!*** ./src/Corporation/Employee.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Employee = void 0;
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 107);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const createElement_1 = __webpack_require__(/*! ../../utils/uiHelpers/createElement */ 51);
const EmployeePositions_1 = __webpack_require__(/*! ./EmployeePositions */ 282);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 23);
class Employee {
constructor(params = {}) {
this.pro = 0;
this.cyclesUntilRaise = Constants_1.CorporationConstants.CyclesPerEmployeeRaise;
this.name = params.name ? params.name : "Bobby";
//Morale, happiness, and energy are 0-100
this.mor = params.morale ? params.morale : getRandomInt_1.getRandomInt(50, 100);
this.hap = params.happiness ? params.happiness : getRandomInt_1.getRandomInt(50, 100);
this.ene = params.energy ? params.energy : getRandomInt_1.getRandomInt(50, 100);
this.int = params.intelligence ? params.intelligence : getRandomInt_1.getRandomInt(10, 50);
this.cha = params.charisma ? params.charisma : getRandomInt_1.getRandomInt(10, 50);
this.exp = params.experience ? params.experience : getRandomInt_1.getRandomInt(10, 50);
this.cre = params.creativity ? params.creativity : getRandomInt_1.getRandomInt(10, 50);
this.eff = params.efficiency ? params.efficiency : getRandomInt_1.getRandomInt(10, 50);
this.sal = params.salary ? params.salary : getRandomInt_1.getRandomInt(0.1, 5);
this.loc = params.loc ? params.loc : "";
this.pos = EmployeePositions_1.EmployeePositions.Unassigned;
}
//Returns the amount the employee needs to be paid
process(marketCycles = 1, office) {
const gain = 0.003 * marketCycles, det = gain * Math.random();
this.exp += gain;
// Employee salaries slowly go up over time
this.cyclesUntilRaise -= marketCycles;
if (this.cyclesUntilRaise <= 0) {
this.sal += Constants_1.CorporationConstants.EmployeeRaiseAmount;
this.cyclesUntilRaise += Constants_1.CorporationConstants.CyclesPerEmployeeRaise;
}
//Training
const trainingEff = gain * Math.random();
if (this.pos === EmployeePositions_1.EmployeePositions.Training) {
//To increase creativity and intelligence special upgrades are needed
this.cha += trainingEff;
this.exp += trainingEff;
this.eff += trainingEff;
}
this.ene -= det;
this.hap -= det;
if (this.ene < office.minEne) {
this.ene = office.minEne;
}
if (this.hap < office.minHap) {
this.hap = office.minHap;
}
const salary = this.sal * marketCycles * Constants_1.CorporationConstants.SecsPerMarketCycle;
return salary;
}
calculateProductivity(corporation, industry) {
const effCre = this.cre * corporation.getEmployeeCreMultiplier() * industry.getEmployeeCreMultiplier(), effCha = this.cha * corporation.getEmployeeChaMultiplier() * industry.getEmployeeChaMultiplier(), effInt = this.int * corporation.getEmployeeIntMultiplier() * industry.getEmployeeIntMultiplier(), effEff = this.eff * corporation.getEmployeeEffMultiplier() * industry.getEmployeeEffMultiplier();
const prodBase = this.mor * this.hap * this.ene * 1e-6;
let prodMult = 0;
switch (this.pos) {
//Calculate productivity based on position. This is multipled by prodBase
//to get final value
case EmployeePositions_1.EmployeePositions.Operations:
prodMult = (0.6 * effInt) + (0.1 * effCha) + (this.exp) +
(0.5 * effCre) + (effEff);
break;
case EmployeePositions_1.EmployeePositions.Engineer:
prodMult = (effInt) + (0.1 * effCha) + (1.5 * this.exp) +
(effEff);
break;
case EmployeePositions_1.EmployeePositions.Business:
prodMult = (0.4 * effInt) + (effCha) + (0.5 * this.exp);
break;
case EmployeePositions_1.EmployeePositions.Management:
prodMult = (2 * effCha) + (this.exp) + (0.2 * effCre) +
(0.7 * effEff);
break;
case EmployeePositions_1.EmployeePositions.RandD:
prodMult = (1.5 * effInt) + (0.8 * this.exp) + (effCre) +
(0.5 * effEff);
break;
case EmployeePositions_1.EmployeePositions.Unassigned:
case EmployeePositions_1.EmployeePositions.Training:
prodMult = 0;
break;
default:
console.error(`Invalid employee position: ${this.pos}`);
break;
}
return prodBase * prodMult;
}
//Process benefits from having an office party thrown
throwParty(money) {
const 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
createUI(panel, corporation, industry) {
const effCre = this.cre * corporation.getEmployeeCreMultiplier() * industry.getEmployeeCreMultiplier(), effCha = this.cha * corporation.getEmployeeChaMultiplier() * industry.getEmployeeChaMultiplier(), effInt = this.int * corporation.getEmployeeIntMultiplier() * industry.getEmployeeIntMultiplier(), effEff = this.eff * corporation.getEmployeeEffMultiplier() * industry.getEmployeeEffMultiplier();
panel.style.color = "white";
panel.appendChild(createElement_1.createElement("p", {
id: "cmpy-mgmt-employee-" + this.name + "-panel-text",
innerHTML: "Morale: " + StringHelperFunctions_1.formatNumber(this.mor, 3) + " " +
"Happiness: " + StringHelperFunctions_1.formatNumber(this.hap, 3) + " " +
"Energy: " + StringHelperFunctions_1.formatNumber(this.ene, 3) + " " +
"Intelligence: " + StringHelperFunctions_1.formatNumber(effInt, 3) + " " +
"Charisma: " + StringHelperFunctions_1.formatNumber(effCha, 3) + " " +
"Experience: " + StringHelperFunctions_1.formatNumber(this.exp, 3) + " " +
"Creativity: " + StringHelperFunctions_1.formatNumber(effCre, 3) + " " +
"Efficiency: " + StringHelperFunctions_1.formatNumber(effEff, 3) + " " +
"Salary: " + numeralFormat_1.numeralWrapper.format(this.sal, "$0.000a") + "/ s ",
}));
//Selector for employee position
const selector = createElement_1.createElement("select", {});
for (const key in EmployeePositions_1.EmployeePositions) {
if (EmployeePositions_1.EmployeePositions.hasOwnProperty(key)) {
selector.add(createElement_1.createElement("option", {
text: EmployeePositions_1.EmployeePositions[key],
value: EmployeePositions_1.EmployeePositions[key],
}));
}
}
selector.addEventListener("change", () => {
this.pos = selector.options[selector.selectedIndex].value;
});
//Set initial value of selector
for (let i = 0; i < selector.length; ++i) {
if (selector.options[i].value === this.pos) {
selector.selectedIndex = i;
break;
}
}
panel.appendChild(selector);
}
toJSON() {
return JSONReviver_1.Generic_toJSON("Employee", this);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Employee, value.data);
}
}
exports.Employee = Employee;
JSONReviver_1.Reviver.constructors.Employee = Employee;
/***/ }),
/* 1124 */
/*!*************************************************!*\
!*** ./src/utils/calculateEffectWithFactors.ts ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EffectWithFactors = exports.calculateEffectWithFactors = void 0;
/**
* This is a component that implements a mathematical formula used commonly throughout the
* game. This formula is (typically) used to calculate the effect that various statistics
* have on a game mechanic. It looks something like:
*
* (stat ^ exponential factor) + (stat / linear factor)
*
* where the exponential factor is a number between 0 and 1 and the linear factor
* is typically a relatively larger number.
*
* This formula ensures that the effects of the statistic that is being processed
* has diminishing returns, but never loses its effectiveness as you continue
* to raise it.
*
* There are two implementations of this component. One is simply a function that
* can be called with the stat and the exponential/linear factors. The other is a
* class where the exponential and linear factors are defined upon construction.
*/
function calculateEffectWithFactors(n, expFac, linearFac) {
if (expFac <= 0 || expFac >= 1) {
console.warn(`Exponential factor is ${expFac}. This is not an intended value for it`);
}
if (linearFac < 1) {
console.warn(`Linear factor is ${linearFac}. This is not an intended value for it`);
}
return (Math.pow(n, expFac)) + (n / linearFac);
}
exports.calculateEffectWithFactors = calculateEffectWithFactors;
class EffectWithFactors {
constructor(expFac, linearFac) {
this.expFac = expFac;
this.linearFac = linearFac;
}
calculate(n) {
return calculateEffectWithFactors(n, this.expFac, this.linearFac);
}
}
exports.EffectWithFactors = EffectWithFactors;
/***/ }),
/* 1125 */
/*!*************************************!*\
!*** ./src/Corporation/Industry.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Industry = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
const CityNames_1 = __webpack_require__(/*! ../Locations/data/CityNames */ 42);
const decimal_js_1 = __importDefault(__webpack_require__(/*! decimal.js */ 65));
const IndustryData_1 = __webpack_require__(/*! ./IndustryData */ 165);
const Constants_1 = __webpack_require__(/*! ./data/Constants */ 107);
const EmployeePositions_1 = __webpack_require__(/*! ./EmployeePositions */ 282);
const Material_1 = __webpack_require__(/*! ./Material */ 494);
const getRandomInt_1 = __webpack_require__(/*! ../../utils/helpers/getRandomInt */ 45);
const calculateEffectWithFactors_1 = __webpack_require__(/*! ../utils/calculateEffectWithFactors */ 1124);
const OfficeSpace_1 = __webpack_require__(/*! ./OfficeSpace */ 223);
const Product_1 = __webpack_require__(/*! ./Product */ 492);
const DialogBox_1 = __webpack_require__(/*! ../../utils/DialogBox */ 13);
const isString_1 = __webpack_require__(/*! ../../utils/helpers/isString */ 72);
const MaterialSizes_1 = __webpack_require__(/*! ./MaterialSizes */ 400);
const Warehouse_1 = __webpack_require__(/*! ./Warehouse */ 495);
const IndustryUpgrades_1 = __webpack_require__(/*! ./IndustryUpgrades */ 692);
const StringHelperFunctions_1 = __webpack_require__(/*! ../../utils/StringHelperFunctions */ 23);
class Industry {
constructor(params = {}) {
this.name = "";
this.type = IndustryData_1.Industries.Agriculture;
this.sciResearch = new Material_1.Material({ name: "Scientific Research" });
this.researched = {};
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
//Upgrades
this.upgrades = [];
this.state = "START";
this.newInd = true;
//Maps locations to offices. 0 if no office at that location
this.offices = {
[CityNames_1.CityName.Aevum]: 0,
[CityNames_1.CityName.Chongqing]: 0,
[CityNames_1.CityName.Sector12]: new OfficeSpace_1.OfficeSpace({
loc: CityNames_1.CityName.Sector12,
size: Constants_1.CorporationConstants.OfficeInitialSize,
}),
[CityNames_1.CityName.NewTokyo]: 0,
[CityNames_1.CityName.Ishima]: 0,
[CityNames_1.CityName.Volhaven]: 0,
};
this.name = params.name ? params.name : '';
this.type = params.type ? params.type : IndustryData_1.Industries.Agriculture;
//Financials
this.lastCycleRevenue = new decimal_js_1.default(0);
this.lastCycleExpenses = new decimal_js_1.default(0);
this.thisCycleRevenue = new decimal_js_1.default(0);
this.thisCycleExpenses = new decimal_js_1.default(0);
//Upgrades
const numUpgrades = Object.keys(IndustryUpgrades_1.IndustryUpgrades).length;
this.upgrades = Array(numUpgrades).fill(0);
this.warehouses = {
[CityNames_1.CityName.Aevum]: 0,
[CityNames_1.CityName.Chongqing]: 0,
[CityNames_1.CityName.Sector12]: new Warehouse_1.Warehouse({
corp: params.corp,
industry: this,
loc: CityNames_1.CityName.Sector12,
size: Constants_1.CorporationConstants.WarehouseInitialSize,
}),
[CityNames_1.CityName.NewTokyo]: 0,
[CityNames_1.CityName.Ishima]: 0,
[CityNames_1.CityName.Volhaven]: 0,
};
this.init();
}
init() {
//Set the unique properties of an industry (how much its affected by real estate/scientific research, etc.)
const startingCost = IndustryData_1.IndustryStartingCosts[this.type];
if (startingCost === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.startingCost = startingCost;
switch (this.type) {
case IndustryData_1.Industries.Energy:
this.reFac = 0.65;
this.sciFac = 0.7;
this.robFac = 0.05;
this.aiFac = 0.3;
this.advFac = 0.08;
this.reqMats = {
"Hardware": 0.1,
"Metal": 0.2,
};
this.prodMats = ["Energy"];
break;
case IndustryData_1.Industries.Utilities:
case "Utilities":
this.reFac = 0.5;
this.sciFac = 0.6;
this.robFac = 0.4;
this.aiFac = 0.4;
this.advFac = 0.08;
this.reqMats = {
"Hardware": 0.1,
"Metal": 0.1,
};
this.prodMats = ["Water"];
break;
case IndustryData_1.Industries.Agriculture:
this.reFac = 0.72;
this.sciFac = 0.5;
this.hwFac = 0.2;
this.robFac = 0.3;
this.aiFac = 0.3;
this.advFac = 0.04;
this.reqMats = {
"Water": 0.5,
"Energy": 0.5,
};
this.prodMats = ["Plants", "Food"];
break;
case IndustryData_1.Industries.Fishing:
this.reFac = 0.15;
this.sciFac = 0.35;
this.hwFac = 0.35;
this.robFac = 0.5;
this.aiFac = 0.2;
this.advFac = 0.08;
this.reqMats = {
"Energy": 0.5,
};
this.prodMats = ["Food"];
break;
case IndustryData_1.Industries.Mining:
this.reFac = 0.3;
this.sciFac = 0.26;
this.hwFac = 0.4;
this.robFac = 0.45;
this.aiFac = 0.45;
this.advFac = 0.06;
this.reqMats = {
"Energy": 0.8,
};
this.prodMats = ["Metal"];
break;
case IndustryData_1.Industries.Food:
//reFac is unique for this bc it diminishes greatly per city. Handle this separately in code?
this.sciFac = 0.12;
this.hwFac = 0.15;
this.robFac = 0.3;
this.aiFac = 0.25;
this.advFac = 0.25;
this.reFac = 0.05;
this.reqMats = {
"Food": 0.5,
"Water": 0.5,
"Energy": 0.2,
};
this.makesProducts = true;
break;
case IndustryData_1.Industries.Tobacco:
this.reFac = 0.15;
this.sciFac = 0.75;
this.hwFac = 0.15;
this.robFac = 0.2;
this.aiFac = 0.15;
this.advFac = 0.2;
this.reqMats = {
"Plants": 1,
"Water": 0.2,
};
this.makesProducts = true;
break;
case IndustryData_1.Industries.Chemical:
this.reFac = 0.25;
this.sciFac = 0.75;
this.hwFac = 0.2;
this.robFac = 0.25;
this.aiFac = 0.2;
this.advFac = 0.07;
this.reqMats = {
"Plants": 1,
"Energy": 0.5,
"Water": 0.5,
};
this.prodMats = ["Chemicals"];
break;
case IndustryData_1.Industries.Pharmaceutical:
this.reFac = 0.05;
this.sciFac = 0.8;
this.hwFac = 0.15;
this.robFac = 0.25;
this.aiFac = 0.2;
this.advFac = 0.16;
this.reqMats = {
"Chemicals": 2,
"Energy": 1,
"Water": 0.5,
};
this.prodMats = ["Drugs"];
this.makesProducts = true;
break;
case IndustryData_1.Industries.Computer:
case "Computer":
this.reFac = 0.2;
this.sciFac = 0.62;
this.robFac = 0.36;
this.aiFac = 0.19;
this.advFac = 0.17;
this.reqMats = {
"Metal": 2,
"Energy": 1,
};
this.prodMats = ["Hardware"];
this.makesProducts = true;
break;
case IndustryData_1.Industries.Robotics:
this.reFac = 0.32;
this.sciFac = 0.65;
this.aiFac = 0.36;
this.advFac = 0.18;
this.hwFac = 0.19;
this.reqMats = {
"Hardware": 5,
"Energy": 3,
};
this.prodMats = ["Robots"];
this.makesProducts = true;
break;
case IndustryData_1.Industries.Software:
this.sciFac = 0.62;
this.advFac = 0.16;
this.hwFac = 0.25;
this.reFac = 0.15;
this.aiFac = 0.18;
this.robFac = 0.05;
this.reqMats = {
"Hardware": 0.5,
"Energy": 0.5,
};
this.prodMats = ["AICores"];
this.makesProducts = true;
break;
case IndustryData_1.Industries.Healthcare:
this.reFac = 0.1;
this.sciFac = 0.75;
this.advFac = 0.11;
this.hwFac = 0.1;
this.robFac = 0.1;
this.aiFac = 0.1;
this.reqMats = {
"Robots": 10,
"AICores": 5,
"Energy": 5,
"Water": 5,
};
this.makesProducts = true;
break;
case IndustryData_1.Industries.RealEstate:
this.robFac = 0.6;
this.aiFac = 0.6;
this.advFac = 0.25;
this.sciFac = 0.05;
this.hwFac = 0.05;
this.reqMats = {
"Metal": 5,
"Energy": 5,
"Water": 2,
"Hardware": 4,
};
this.prodMats = ["RealEstate"];
this.makesProducts = true;
break;
default:
console.error(`Invalid Industry Type passed into Industry.init(): ${this.type}`);
return;
}
}
getProductDescriptionText() {
if (!this.makesProducts)
return '';
switch (this.type) {
case IndustryData_1.Industries.Food:
return "create and manage restaurants";
case IndustryData_1.Industries.Tobacco:
return "create tobacco and tobacco-related products";
case IndustryData_1.Industries.Pharmaceutical:
return "develop new pharmaceutical drugs";
case IndustryData_1.Industries.Computer:
case "Computer":
return "create new computer hardware and networking infrastructures";
case IndustryData_1.Industries.Robotics:
return "build specialized robots and robot-related products";
case IndustryData_1.Industries.Software:
return "develop computer software";
case IndustryData_1.Industries.Healthcare:
return "build and manage hospitals";
case IndustryData_1.Industries.RealEstate:
return "develop and manage real estate properties";
default:
console.error("Invalid industry type in Industry.getProductDescriptionText");
return "";
}
}
getMaximumNumberProducts() {
if (!this.makesProducts)
return 0;
// Calculate additional number of allowed Products from Research/Upgrades
let additional = 0;
if (this.hasResearch("uPgrade: Capacity.I"))
++additional;
if (this.hasResearch("uPgrade: Capacity.II"))
++additional;
return Constants_1.CorporationConstants.BaseMaxProducts + additional;
}
hasMaximumNumberProducts() {
return (Object.keys(this.products).length >= this.getMaximumNumberProducts());
}
//Calculates the values that factor into the production and properties of
//materials/products (such as quality, etc.)
calculateProductionFactors() {
let multSum = 0;
for (let i = 0; i < Constants_1.CorporationConstants.Cities.length; ++i) {
const city = Constants_1.CorporationConstants.Cities[i];
const warehouse = this.warehouses[city];
if (!(warehouse instanceof Warehouse_1.Warehouse)) {
continue;
}
const materials = warehouse.materials;
const 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;
}
updateWarehouseSizeUsed(warehouse) {
warehouse.updateMaterialSizeUsed();
for (const prodName in this.products) {
if (this.products.hasOwnProperty(prodName)) {
const prod = this.products[prodName];
warehouse.sizeUsed += (prod.data[warehouse.loc][0] * prod.siz);
if (prod.data[warehouse.loc][0] > 0) {
warehouse.breakdown += (prodName + ": " + StringHelperFunctions_1.formatNumber(prod.data[warehouse.loc][0] * prod.siz, 0) + " ");
}
}
}
}
process(marketCycles = 1, state, corporation) {
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.error("NaN in Corporation's computed revenue/expenses");
DialogBox_1.dialogBoxCreate("Something went wrong when compting Corporation's revenue/expenses. This is a bug. Please report to game developer");
this.thisCycleRevenue = new decimal_js_1.default(0);
this.thisCycleExpenses = new decimal_js_1.default(0);
}
this.lastCycleRevenue = this.thisCycleRevenue.dividedBy(marketCycles * Constants_1.CorporationConstants.SecsPerMarketCycle);
this.lastCycleExpenses = this.thisCycleExpenses.dividedBy(marketCycles * Constants_1.CorporationConstants.SecsPerMarketCycle);
this.thisCycleRevenue = new decimal_js_1.default(0);
this.thisCycleExpenses = new decimal_js_1.default(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)
let employeeSalary = 0;
for (const officeLoc in this.offices) {
if (this.offices[officeLoc] instanceof OfficeSpace_1.OfficeSpace) {
employeeSalary += this.offices[officeLoc].process(marketCycles, { industry: this, corporation: corporation });
}
}
this.thisCycleExpenses = this.thisCycleExpenses.plus(employeeSalary);
// Process change in demand/competition of materials/products
this.processMaterialMarket();
this.processProductMarket(marketCycles);
// Process loss of popularity
this.popularity -= (marketCycles * .0001);
this.popularity = Math.max(0, this.popularity);
// Process Dreamsense gains
const popularityGain = corporation.getDreamSenseGain(), awarenessGain = popularityGain * 4;
if (popularityGain > 0) {
this.popularity += (popularityGain * marketCycles);
this.awareness += (awarenessGain * marketCycles);
}
return;
}
// Process production, purchase, and import/export of materials
let res = this.processMaterials(marketCycles, corporation);
if (Array.isArray(res)) {
this.thisCycleRevenue = this.thisCycleRevenue.plus(res[0]);
this.thisCycleExpenses = this.thisCycleExpenses.plus(res[1]);
}
// Process creation, production & sale of products
res = this.processProducts(marketCycles, corporation);
if (Array.isArray(res)) {
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
processMaterialMarket() {
//References to prodMats and reqMats
const reqMats = this.reqMats, prodMats = this.prodMats;
//Only 'process the market' for materials that this industry deals with
for (let i = 0; i < Constants_1.CorporationConstants.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[Constants_1.CorporationConstants.Cities[i]] instanceof Warehouse_1.Warehouse) {
const wh = this.warehouses[Constants_1.CorporationConstants.Cities[i]];
for (const name in reqMats) {
if (reqMats.hasOwnProperty(name)) {
wh.materials[name].processMarket();
}
}
//Produced materials are stored in an array
for (let 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
processProductMarket(marketCycles = 1) {
// Demand gradually decreases, and competition gradually increases
for (const name in this.products) {
if (this.products.hasOwnProperty(name)) {
const product = this.products[name];
let change = getRandomInt_1.getRandomInt(0, 3) * 0.0004;
if (change === 0)
continue;
if (this.type === IndustryData_1.Industries.Pharmaceutical || this.type === IndustryData_1.Industries.Software ||
this.type === IndustryData_1.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
processMaterials(marketCycles = 1, corporation) {
let revenue = 0, expenses = 0;
this.calculateProductionFactors();
//At the start of the export state, set the imports of everything to 0
if (this.state === "EXPORT") {
for (let i = 0; i < Constants_1.CorporationConstants.Cities.length; ++i) {
const city = Constants_1.CorporationConstants.Cities[i];
if (!(this.warehouses[city] instanceof Warehouse_1.Warehouse)) {
continue;
}
const warehouse = this.warehouses[city];
for (const matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
const mat = warehouse.materials[matName];
mat.imp = 0;
}
}
}
}
for (let i = 0; i < Constants_1.CorporationConstants.Cities.length; ++i) {
const city = Constants_1.CorporationConstants.Cities[i], office = this.offices[city];
if (this.warehouses[city] instanceof Warehouse_1.Warehouse) {
const warehouse = this.warehouses[city];
switch (this.state) {
case "PURCHASE":
/* Process purchase of materials */
for (const matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
(function (matName, ind) {
const mat = warehouse.materials[matName];
let 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 * Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles;
}
else {
buyAmt = (mat.buy * Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
}
if (matName == "RealEstate") {
maxAmt = buyAmt;
}
else {
maxAmt = Math.floor((warehouse.size - warehouse.sizeUsed) / MaterialSizes_1.MaterialSizes[matName]);
}
buyAmt = Math.min(buyAmt, maxAmt);
if (buyAmt > 0) {
mat.qty += buyAmt;
expenses += (buyAmt * mat.bCost);
}
})(matName, this);
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) {
const mat = warehouse.materials[this.prodMats[0]];
//Calculate the maximum production of this material based
//on the office's productivity
const maxProd = this.getOfficeProductivity(office)
* this.prodMult // Multiplier from materials
* corporation.getProductionMultiplier()
* this.getProductionMultiplier(); // Multiplier from Research
let prod;
if (mat.prdman[0]) {
//Production is manually limited
prod = Math.min(maxProd, mat.prdman[1]);
}
else {
prod = maxProd;
}
prod *= (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles); //Convert production from per second to per market cycle
// Calculate net change in warehouse storage making the produced materials will cost
let totalMatSize = 0;
for (let tmp = 0; tmp < this.prodMats.length; ++tmp) {
totalMatSize += (MaterialSizes_1.MaterialSizes[this.prodMats[tmp]]);
}
for (const reqMatName in this.reqMats) {
const normQty = this.reqMats[reqMatName];
totalMatSize -= (MaterialSizes_1.MaterialSizes[reqMatName] * normQty);
}
// If not enough space in warehouse, limit the amount of produced materials
if (totalMatSize > 0) {
const 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 / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles));
// Make sure we have enough resource to make our materials
let producableFrac = 1;
for (const reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
const req = this.reqMats[reqMatName] * prod;
if (warehouse.materials[reqMatName].qty < req) {
producableFrac = Math.min(producableFrac, warehouse.materials[reqMatName].qty / req);
}
}
}
if (producableFrac <= 0) {
producableFrac = 0;
prod = 0;
}
// Make our materials if they are producable
if (producableFrac > 0 && prod > 0) {
for (const reqMatName in this.reqMats) {
const reqMatQtyNeeded = (this.reqMats[reqMatName] * prod * producableFrac);
warehouse.materials[reqMatName].qty -= reqMatQtyNeeded;
warehouse.materials[reqMatName].prd = 0;
warehouse.materials[reqMatName].prd -= reqMatQtyNeeded / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
}
for (let j = 0; j < this.prodMats.length; ++j) {
warehouse.materials[this.prodMats[j]].qty += (prod * producableFrac);
warehouse.materials[this.prodMats[j]].qlt =
(office.employeeProd[EmployeePositions_1.EmployeePositions.Engineer] / 90 +
Math.pow(this.sciResearch.qty, this.sciFac) +
Math.pow(warehouse.materials["AICores"].qty, this.aiFac) / 10e3);
}
}
else {
for (const reqMatName in this.reqMats) {
if (this.reqMats.hasOwnProperty(reqMatName)) {
warehouse.materials[reqMatName].prd = 0;
}
}
}
//Per second
const fooProd = prod * producableFrac / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
for (let fooI = 0; fooI < this.prodMats.length; ++fooI) {
warehouse.materials[this.prodMats[fooI]].prd = fooProd;
}
}
else {
//If this doesn't produce any materials, then it only creates
//Products. Creating products will consume materials. The
//Production of all consumed materials must be set to 0
for (const reqMatName in this.reqMats) {
warehouse.materials[reqMatName].prd = 0;
}
}
break;
case "SALE":
/* Process sale of materials */
for (const matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
const mat = warehouse.materials[matName];
if (mat.sCost < 0 || mat.sllman[0] === false) {
mat.sll = 0;
continue;
}
// Sale multipliers
const businessFactor = this.getBusinessFactor(office); //Business employee productivity
const advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
const marketFactor = this.getMarketFactor(mat); //Competition + demand
// Determine the cost that the material will be sold at
const markupLimit = mat.getMarkupLimit();
let sCost;
if (mat.marketTa2) {
const prod = mat.prd;
// Reverse engineer the 'maxSell' formula
// 1. Set 'maxSell' = prod
// 2. Substitute formula for 'markup'
// 3. Solve for 'sCost'
const numerator = markupLimit;
const sqrtNumerator = prod;
const sqrtDenominator = ((mat.qlt + .001)
* marketFactor
* businessFactor
* corporation.getSalesMultiplier()
* advertisingFactor
* this.getSalesMultiplier());
const denominator = Math.sqrt(sqrtNumerator / sqrtDenominator);
let optimalPrice;
if (sqrtDenominator === 0 || denominator === 0) {
if (sqrtNumerator === 0) {
optimalPrice = 0; // No production
}
else {
optimalPrice = mat.bCost + markupLimit;
console.warn(`In Corporation, found illegal 0s when trying to calculate MarketTA2 sale cost`);
}
}
else {
optimalPrice = (numerator / denominator) + mat.bCost;
}
// We'll store this "Optimal Price" in a property so that we don't have
// to re-calculate it for the UI
mat.marketTa2Price = optimalPrice;
sCost = optimalPrice;
}
else if (mat.marketTa1) {
sCost = mat.bCost + markupLimit;
}
else if (isString_1.isString(mat.sCost)) {
sCost = mat.sCost.replace(/MP/g, mat.bCost);
sCost = eval(sCost);
}
else {
sCost = mat.sCost;
}
// Calculate how much of the material sells (per second)
let markup = 1;
if (sCost > mat.bCost) {
//Penalty if difference between sCost and bCost is greater than markup limit
if ((sCost - mat.bCost) > markupLimit) {
markup = Math.pow(markupLimit / (sCost - mat.bCost), 2);
}
}
else if (sCost < mat.bCost) {
if (sCost <= 0) {
markup = 1e12; //Sell everything, essentially discard
}
else {
//Lower prices than market increases sales
markup = mat.bCost / sCost;
}
}
const maxSell = (mat.qlt + .001)
* marketFactor
* markup
* businessFactor
* corporation.getSalesMultiplier()
* advertisingFactor
* this.getSalesMultiplier();
let sellAmt;
if (isString_1.isString(mat.sllman[1])) {
//Dynamically evaluated
let tmp = mat.sllman[1].replace(/MAX/g, maxSell);
tmp = tmp.replace(/PROD/g, mat.prd);
try {
sellAmt = eval(tmp);
}
catch (e) {
DialogBox_1.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 * Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
sellAmt = Math.min(mat.qty, sellAmt);
if (sellAmt < 0) {
console.warn(`sellAmt calculated to be negative for ${matName} in ${city}`);
mat.sll = 0;
continue;
}
if (sellAmt && sCost >= 0) {
mat.qty -= sellAmt;
revenue += (sellAmt * sCost);
mat.sll = sellAmt / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
}
else {
mat.sll = 0;
}
}
} //End processing of sale of materials
break;
case "EXPORT":
for (const matName in warehouse.materials) {
if (warehouse.materials.hasOwnProperty(matName)) {
const mat = warehouse.materials[matName];
mat.totalExp = 0; //Reset export
for (let expI = 0; expI < mat.exp.length; ++expI) {
const exp = mat.exp[expI];
let amt = exp.amt.replace(/MAX/g, mat.qty / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles));
try {
amt = eval(amt);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Calculating export for " + mat.name + " in " +
this.name + "'s " + city + " division failed with " +
"error: " + e);
continue;
}
if (isNaN(amt)) {
DialogBox_1.dialogBoxCreate("Error calculating export amount for " + mat.name + " in " +
this.name + "'s " + city + " division.");
continue;
}
amt = amt * Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles;
if (mat.qty < amt) {
amt = mat.qty;
}
if (amt === 0) {
break; //None left
}
for (let foo = 0; foo < corporation.divisions.length; ++foo) {
if (corporation.divisions[foo].name === exp.ind) {
const expIndustry = corporation.divisions[foo];
const expWarehouse = expIndustry.warehouses[exp.city];
if (!(expWarehouse instanceof Warehouse_1.Warehouse)) {
console.error(`Invalid export! ${expIndustry.name} ${exp.city}`);
break;
}
// Make sure theres enough space in warehouse
if (expWarehouse.sizeUsed >= expWarehouse.size) {
// Warehouse at capacity. Exporting doesnt
// affect revenue so just return 0's
return [0, 0];
}
else {
const maxAmt = Math.floor((expWarehouse.size - expWarehouse.sizeUsed) / MaterialSizes_1.MaterialSizes[matName]);
amt = Math.min(maxAmt, amt);
}
expWarehouse.materials[matName].imp += (amt / (Constants_1.CorporationConstants.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 /= (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
}
}
break;
case "START":
break;
default:
console.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_1.OfficeSpace) {
this.sciResearch.qty += (.004
* Math.pow(office.employeeProd[EmployeePositions_1.EmployeePositions.RandD], 0.5)
* corporation.getScientificResearchMultiplier()
* this.getScientificResearchMultiplier());
}
}
return [revenue, expenses];
}
//Process production & sale of this industry's FINISHED products (including all of their stats)
processProducts(marketCycles = 1, corporation) {
let revenue = 0;
const expenses = 0;
//Create products
if (this.state === "PRODUCTION") {
for (const prodName in this.products) {
const prod = this.products[prodName];
if (!prod.fin) {
const city = prod.createCity;
const office = this.offices[city];
// Designing/Creating a Product is based mostly off Engineers
const engrProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Engineer];
const mgmtProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Management];
const opProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Operations];
const total = engrProd + mgmtProd + opProd;
if (total <= 0) {
break;
}
// Management is a multiplier for the production from Engineers
const mgmtFactor = 1 + (mgmtProd / (1.2 * total));
const progress = (Math.pow(engrProd, 0.34) + Math.pow(opProd, 0.2)) * mgmtFactor;
prod.createProduct(marketCycles, progress);
if (prod.prog >= 100) {
prod.finishProduct(office.employeeProd, this);
}
break;
}
}
}
//Produce Products
for (const prodName in this.products) {
if (this.products.hasOwnProperty(prodName)) {
const prod = this.products[prodName];
if (prod instanceof Product_1.Product && prod.fin) {
revenue += this.processProduct(marketCycles, prod, corporation);
}
}
}
return [revenue, expenses];
}
//Processes FINISHED products
processProduct(marketCycles = 1, product, corporation) {
let totalProfit = 0;
for (let i = 0; i < Constants_1.CorporationConstants.Cities.length; ++i) {
const city = Constants_1.CorporationConstants.Cities[i], office = this.offices[city], warehouse = this.warehouses[city];
if (warehouse instanceof Warehouse_1.Warehouse) {
switch (this.state) {
case "PRODUCTION": {
//Calculate the maximum production of this material based
//on the office's productivity
const maxProd = this.getOfficeProductivity(office, { forProduct: true })
* corporation.getProductionMultiplier()
* this.prodMult // Multiplier from materials
* this.getProductionMultiplier() // Multiplier from research
* this.getProductProductionMultiplier(); // Multiplier from research
let prod;
//Account for whether production is manually limited
if (product.prdman[city][0]) {
prod = Math.min(maxProd, product.prdman[city][1]);
}
else {
prod = maxProd;
}
prod *= (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
//Calculate net change in warehouse storage making the Products will cost
let netStorageSize = product.siz;
for (const reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
const normQty = product.reqMats[reqMatName];
netStorageSize -= (MaterialSizes_1.MaterialSizes[reqMatName] * normQty);
}
}
//If there's not enough space in warehouse, limit the amount of Product
if (netStorageSize > 0) {
const maxAmt = Math.floor((warehouse.size - warehouse.sizeUsed) / netStorageSize);
prod = Math.min(maxAmt, prod);
}
warehouse.smartSupplyStore += (prod / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles));
//Make sure we have enough resources to make our Products
let producableFrac = 1;
for (const reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
const 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 (const reqMatName in product.reqMats) {
if (product.reqMats.hasOwnProperty(reqMatName)) {
const reqMatQtyNeeded = (product.reqMats[reqMatName] * prod * producableFrac);
warehouse.materials[reqMatName].qty -= reqMatQtyNeeded;
warehouse.materials[reqMatName].prd -= reqMatQtyNeeded / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
}
}
//Quantity
product.data[city][0] += (prod * producableFrac);
}
//Keep track of production Per second
product.data[city][1] = prod * producableFrac / (Constants_1.CorporationConstants.SecsPerMarketCycle * marketCycles);
break;
}
case "SALE": {
//Process sale of Products
product.pCost = 0; //Estimated production cost
for (const 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 *= Constants_1.CorporationConstants.ProductProductionCostRatio;
// Sale multipliers
const businessFactor = this.getBusinessFactor(office); //Business employee productivity
const advertisingFactor = this.getAdvertisingFactors()[0]; //Awareness + popularity
const marketFactor = this.getMarketFactor(product); //Competition + demand
// Calculate Sale Cost (sCost), which could be dynamically evaluated
const markupLimit = product.rat / product.mku;
let sCost;
if (product.marketTa2) {
const prod = product.data[city][1];
// Reverse engineer the 'maxSell' formula
// 1. Set 'maxSell' = prod
// 2. Substitute formula for 'markup'
// 3. Solve for 'sCost'roduct.pCost = sCost
const numerator = markupLimit;
const sqrtNumerator = prod;
const sqrtDenominator = (0.5
* Math.pow(product.rat, 0.65)
* marketFactor
* corporation.getSalesMultiplier()
* businessFactor
* advertisingFactor
* this.getSalesMultiplier());
const denominator = Math.sqrt(sqrtNumerator / sqrtDenominator);
let optimalPrice;
if (sqrtDenominator === 0 || denominator === 0) {
if (sqrtNumerator === 0) {
optimalPrice = 0; // No production
}
else {
optimalPrice = product.pCost + markupLimit;
console.warn(`In Corporation, found illegal 0s when trying to calculate MarketTA2 sale cost`);
}
}
else {
optimalPrice = (numerator / denominator) + product.pCost;
}
// Store this "optimal Price" in a property so we don't have to re-calculate for UI
product.marketTa2Price[city] = optimalPrice;
sCost = optimalPrice;
}
else if (product.marketTa1) {
sCost = product.pCost + markupLimit;
}
else if (isString_1.isString(product.sCost)) {
const sCostString = product.sCost;
if (product.mku === 0) {
console.error(`mku is zero, reverting to 1 to avoid Infinity`);
product.mku = 1;
}
sCost = sCostString.replace(/MP/g, (product.pCost + product.rat / product.mku) + '');
sCost = eval(sCost);
}
else {
sCost = product.sCost;
}
let markup = 1;
if (sCost > product.pCost) {
if ((sCost - product.pCost) > markupLimit) {
markup = markupLimit / (sCost - product.pCost);
}
}
const maxSell = 0.5
* Math.pow(product.rat, 0.65)
* marketFactor
* corporation.getSalesMultiplier()
* Math.pow(markup, 2)
* businessFactor
* advertisingFactor
* this.getSalesMultiplier();
let sellAmt;
if (product.sllman[city][0] && isString_1.isString(product.sllman[city][1])) {
//Sell amount is dynamically evaluated
let tmp = product.sllman[city][1].replace(/MAX/g, maxSell);
tmp = tmp.replace(/PROD/g, product.data[city][1]);
try {
tmp = eval(tmp);
}
catch (e) {
DialogBox_1.dialogBoxCreate("Error evaluating your sell price expression for " + product.name +
" in " + this.name + "'s " + city + " office. Sell price is being set to MAX");
tmp = maxSell;
}
sellAmt = Math.min(maxSell, tmp);
}
else if (product.sllman[city][0] && product.sllman[city][1] > 0) {
//Sell amount is manually limited
sellAmt = Math.min(maxSell, product.sllman[city][1]);
}
else if (product.sllman[city][0] === false) {
sellAmt = 0;
}
else {
sellAmt = maxSell;
}
if (sellAmt < 0) {
sellAmt = 0;
}
sellAmt = sellAmt * Constants_1.CorporationConstants.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 / (Constants_1.CorporationConstants.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.error(`Invalid State: ${this.state}`);
break;
} //End switch(this.state)
}
}
return totalProfit;
}
discontinueProduct(product) {
for (const productName in this.products) {
if (this.products.hasOwnProperty(productName)) {
if (product === this.products[productName]) {
delete this.products[productName];
}
}
}
}
upgrade(upgrade, refs) {
const corporation = refs.corporation;
const office = refs.office;
const upgN = upgrade[0];
while (this.upgrades.length <= upgN) {
this.upgrades.push(0);
}
++this.upgrades[upgN];
switch (upgN) {
case 0: { //Coffee, 5% energy per employee
for (let i = 0; i < office.employees.length; ++i) {
office.employees[i].ene = Math.min(office.employees[i].ene * 1.05, office.maxEne);
}
break;
}
case 1: { //AdVert.Inc,
const advMult = corporation.getAdvertisingMultiplier() * this.getAdvertisingMultiplier();
this.awareness += (3 * advMult);
this.popularity += (1 * advMult);
this.awareness *= (1.01 * advMult);
this.popularity *= ((1 + getRandomInt_1.getRandomInt(1, 3) / 100) * advMult);
break;
}
default: {
console.error(`Un-implemented function index: ${upgN}`);
break;
}
}
}
// Returns how much of a material can be produced based of office productivity (employee stats)
getOfficeProductivity(office, params = {}) {
const opProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Operations];
const engrProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Engineer];
const mgmtProd = office.employeeProd[EmployeePositions_1.EmployeePositions.Management];
const total = opProd + engrProd + mgmtProd;
if (total <= 0)
return 0;
// Management is a multiplier for the production from Operations and Engineers
const mgmtFactor = 1 + (mgmtProd / (1.2 * total));
// For production, Operations is slightly more important than engineering
// Both Engineering and Operations have diminishing returns
const prod = (Math.pow(opProd, 0.4) + Math.pow(engrProd, 0.3)) * mgmtFactor;
// Generic multiplier for the production. Used for game-balancing purposes
const balancingMult = 0.05;
if (params && params.forProduct) {
// Products are harder to create and therefore have less production
return 0.5 * balancingMult * prod;
}
else {
return balancingMult * prod;
}
}
// Returns a multiplier based on the office' 'Business' employees that affects sales
getBusinessFactor(office) {
const businessProd = 1 + office.employeeProd[EmployeePositions_1.EmployeePositions.Business];
return calculateEffectWithFactors_1.calculateEffectWithFactors(businessProd, 0.26, 10e3);
}
//Returns a set of multipliers based on the Industry's awareness, popularity, and advFac. This
//multiplier affects sales. The result is:
// [Total sales mult, total awareness mult, total pop mult, awareness/pop ratio mult]
getAdvertisingFactors() {
const awarenessFac = Math.pow(this.awareness + 1, this.advFac);
const popularityFac = Math.pow(this.popularity + 1, this.advFac);
const ratioFac = (this.awareness === 0 ? 0.01 : Math.max((this.popularity + .001) / this.awareness, 0.01));
const 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
getMarketFactor(mat) {
return Math.max(0.1, mat.dmd * (100 - mat.cmp) / 100);
}
// Returns a boolean indicating whether this Industry has the specified Research
hasResearch(name) {
return (this.researched[name] === true);
}
updateResearchTree() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry "${this.type}"`);
// Since ResearchTree data isnt saved, we'll update the Research Tree data
// based on the stored 'researched' property in the Industry object
if (Object.keys(researchTree.researched).length !== Object.keys(this.researched).length) {
for (const research in this.researched) {
researchTree.research(research);
}
}
}
// Get multipliers from Research
getAdvertisingMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getAdvertisingMultiplier();
}
getEmployeeChaMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getEmployeeChaMultiplier();
}
getEmployeeCreMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getEmployeeCreMultiplier();
}
getEmployeeEffMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getEmployeeEffMultiplier();
}
getEmployeeIntMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getEmployeeIntMultiplier();
}
getProductionMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getProductionMultiplier();
}
getProductProductionMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getProductProductionMultiplier();
}
getSalesMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getSalesMultiplier();
}
getScientificResearchMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getScientificResearchMultiplier();
}
getStorageMultiplier() {
const researchTree = IndustryData_1.IndustryResearchTrees[this.type];
if (researchTree === undefined)
throw new Error(`Invalid industry: "${this.type}"`);
this.updateResearchTree();
return researchTree.getStorageMultiplier();
}
/**
* Serialize the current object to a JSON save state.
*/
toJSON() {
return JSONReviver_1.Generic_toJSON("Industry", this);
}
/**
* Initiatizes a Industry object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(Industry, value.data);
}
}
exports.Industry = Industry;
JSONReviver_1.Reviver.constructors.Industry = Industry;
/***/ }),
/* 1126 */
/*!*****************************************!*\
!*** ./src/Corporation/ResearchTree.ts ***!
\*****************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResearchTree = exports.Node = void 0;
const ResearchMap_1 = __webpack_require__(/*! ./ResearchMap */ 493);
const numeralFormat_1 = __webpack_require__(/*! ../ui/numeralFormat */ 7);
class Node {
constructor(p = { cost: 0, text: "" }) {
// All child Nodes in the tree
// The Research held in this Node is a prerequisite for all Research in
// child Nodes
this.children = [];
// How much Scientific Research is needed for this
// Necessary to show it on the UI
this.cost = 0;
// Whether or not this Research has been unlocked
this.researched = false;
// Parent node in the tree
// The parent node defines the prerequisite Research (there can only be one)
// Set as null for no prerequisites
this.parent = null;
// Name of the Research held in this Node
this.text = "";
if (ResearchMap_1.ResearchMap[p.text] == null) {
throw new Error(`Invalid Research name used when constructing ResearchTree Node: ${p.text}`);
}
this.text = p.text;
this.cost = p.cost;
if (p.children && p.children.length > 0) {
this.children = p.children;
}
if (p.parent != null) {
this.parent = p.parent;
}
}
addChild(n) {
this.children.push(n);
n.parent = this;
}
// Return an object that describes a TreantJS-compatible markup/config for this Node
// See: http://fperucic.github.io/treant-js/
createTreantMarkup() {
const childrenArray = [];
for (let i = 0; i < this.children.length; ++i) {
childrenArray.push(this.children[i].createTreantMarkup());
}
// Determine what css class this Node should have in the diagram
let htmlClass = "";
if (this.researched) {
htmlClass = "researched";
}
else if (this.parent && this.parent.researched === false) {
htmlClass = "locked";
}
else {
htmlClass = "unlocked";
}
const research = ResearchMap_1.ResearchMap[this.text];
const sanitizedName = this.text.replace(/\s/g, '');
return {
children: childrenArray,
HTMLclass: htmlClass,
innerHTML: `
`,
text: { name: this.text },
};
}
// Recursive function for finding a Node with the specified text
findNode(text) {
// Is this the Node?
if (this.text === text) {
return this;
}
// Recursively search chilren
let res = null;
for (let i = 0; i < this.children.length; ++i) {
res = this.children[i].findNode(text);
if (res != null) {
return res;
}
}
return null;
}
setParent(n) {
this.parent = n;
}
}
exports.Node = Node;
// A ResearchTree defines all available Research in an Industry
// The root node in a Research Tree must always be the "Hi-Tech R&D Laboratory"
class ResearchTree {
constructor() {
// Object containing names of all acquired Research by name
this.researched = {};
// Root Node
this.root = null;
}
// Return an object that contains a Tree markup for TreantJS (using the JSON approach)
// See: http://fperucic.github.io/treant-js/
createTreantMarkup() {
if (this.root == null) {
return {};
}
const treeMarkup = this.root.createTreantMarkup();
return {
chart: {
container: "",
},
nodeStructure: treeMarkup,
};
}
// Gets an array with the 'text' values of ALL Nodes in the Research Tree
getAllNodes() {
const res = [];
const queue = [];
if (this.root == null) {
return res;
}
queue.push(this.root);
while (queue.length !== 0) {
const node = queue.shift();
if (node == null) {
continue;
}
res.push(node.text);
for (let i = 0; i < node.children.length; ++i) {
queue.push(node.children[i]);
}
}
return res;
}
// Get total multipliers from this Research Tree
getAdvertisingMultiplier() {
return this.getMultiplierHelper("advertisingMult");
}
getEmployeeChaMultiplier() {
return this.getMultiplierHelper("employeeChaMult");
}
getEmployeeCreMultiplier() {
return this.getMultiplierHelper("employeeCreMult");
}
getEmployeeEffMultiplier() {
return this.getMultiplierHelper("employeeEffMult");
}
getEmployeeIntMultiplier() {
return this.getMultiplierHelper("employeeIntMult");
}
getProductionMultiplier() {
return this.getMultiplierHelper("productionMult");
}
getProductProductionMultiplier() {
return this.getMultiplierHelper("productProductionMult");
}
getSalesMultiplier() {
return this.getMultiplierHelper("salesMult");
}
getScientificResearchMultiplier() {
return this.getMultiplierHelper("sciResearchMult");
}
getStorageMultiplier() {
return this.getMultiplierHelper("storageMult");
}
// Helper function for all the multiplier getter fns
getMultiplierHelper(propName) {
let res = 1;
if (this.root == null) {
return res;
}
const queue = [];
queue.push(this.root);
while (queue.length !== 0) {
const node = queue.shift();
// If the Node has not been researched, there's no need to
// process it or its children
if (node == null || !node.researched) {
continue;
}
const research = ResearchMap_1.ResearchMap[node.text];
// Safety checks
if (research == null) {
console.warn(`Invalid Research name in node: ${node.text}`);
continue;
}
const mult = research[propName];
if (mult == null) {
console.warn(`Invalid propName specified in ResearchTree.getMultiplierHelper: ${propName}`);
continue;
}
res *= mult;
for (let i = 0; i < node.children.length; ++i) {
queue.push(node.children[i]);
}
}
return res;
}
// Search for a Node with the given name ('text' property on the Node)
// Returns 'null' if it cannot be found
findNode(name) {
if (this.root == null) {
return null;
}
return this.root.findNode(name);
}
// Marks a Node as researched
research(name) {
if (this.root == null) {
return;
}
const queue = [];
queue.push(this.root);
while (queue.length !== 0) {
const node = queue.shift();
if (node == null) {
continue;
}
if (node.text === name) {
node.researched = true;
this.researched[name] = true;
return;
}
for (let i = 0; i < node.children.length; ++i) {
queue.push(node.children[i]);
}
}
console.warn(`ResearchTree.research() did not find the specified Research node for: ${name}`);
}
// Set the tree's Root Node
setRoot(root) {
this.root = root;
}
}
exports.ResearchTree = ResearchTree;
/***/ }),
/* 1127 */
/*!**************************************************!*\
!*** ./src/Corporation/data/ResearchMetadata.ts ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.researchMetadata = void 0;
exports.researchMetadata = [
{
name: "AutoBrew",
cost: 12e3,
desc: "Automatically keep your employees fully caffeinated with " +
"coffee injections. This research will keep the energy of all " +
"employees at its maximum possible value, for no cost. " +
"This will also disable the Coffee upgrade.",
},
{
name: "AutoPartyManager",
cost: 15e3,
desc: "Automatically analyzes your employees' happiness and morale " +
"and boosts them whenever it detects a decrease. This research will " +
"keep the morale and happiness of all employees at their maximum possible " +
"values, for no cost. " +
"This will also disable the 'Throw Party' feature.",
},
{
name: "Automatic Drug Administration",
cost: 10e3,
desc: "Research how to automatically administer performance-enhacing drugs to all of " +
"your employees. This unlocks Drug-related Research.",
},
{
name: "Bulk Purchasing",
cost: 5e3,
desc: "Research the art of buying materials in bulk. This allows you to purchase " +
"any amount of a material instantly.",
},
{
name: "CPH4 Injections",
cost: 25e3,
desc: "Develop an advanced and harmless synthetic drug that is administered to " +
"employees to increase all of their stats, except experience, by 10%.",
employeeCreMult: 1.1,
employeeChaMult: 1.1,
employeeEffMult: 1.1,
employeeIntMult: 1.1,
},
{
name: "Drones",
cost: 5e3,
desc: "Acquire the knowledge needed to create advanced drones. This research does nothing " +
"by itself, but unlocks other Drone-related research.",
},
{
name: "Drones - Assembly",
cost: 25e3,
desc: "Manufacture and use Assembly Drones to improve the efficiency of " +
"your production lines. This increases all production by 20%.",
productionMult: 1.2,
},
{
name: "Drones - Transport",
cost: 30e3,
desc: "Manufacture and use intelligent Transport Drones to optimize " +
"your warehouses. This increases the storage space of all warehouses " +
"by 50%.",
storageMult: 1.5,
},
{
name: "Go-Juice",
cost: 25e3,
desc: "Provide employees with Go-Juice, a coffee-derivative that further enhances " +
"the brain's dopamine production. This increases the maximum energy of all " +
"employees by 10.",
},
{
name: "Hi-Tech R&D Laboratory",
cost: 5e3,
desc: "Construct a cutting edge facility dedicated to advanced research and " +
"and development. This allows you to spend Scientific Research " +
"on powerful upgrades. It also globally increases Scientific Research " +
"production by 10%.",
sciResearchMult: 1.1,
},
{
name: "HRBuddy-Recruitment",
cost: 15e3,
desc: "Use automated software to handle the hiring of employees. With this " +
"research, each office will automatically hire one employee per " +
"market cycle if there is available space.",
},
{
name: "HRBuddy-Training",
cost: 20e3,
desc: "Use automated software to handle the training of employees. With this " +
"research, each employee hired with HRBuddy-Recruitment will automatically " +
"be assigned to 'Training', rather than being unassigned.",
},
{
name: "JoyWire",
cost: 20e3,
desc: "A brain implant which is installed in employees, increasing their " +
"maximum happiness by 10.",
},
{
name: "Market-TA.I",
cost: 20e3,
desc: "Develop advanced AI software that uses technical analysis to " +
"help you understand and exploit the market. This research " +
"allows you to know what price to sell your Materials/Products " +
"at in order to avoid losing sales due to having too high of a mark-up. " +
"It also lets you automatically use that sale price.",
},
{
name: "Market-TA.II",
cost: 50e3,
desc: "Develop double-advanced AI software that uses technical analysis to " +
"help you understand and exploit the market. This research " +
"allows you to know how many sales of a Material/Product you lose or gain " +
"from having too high or too low or a sale price. It also lets you automatically " +
"set the sale price of your Materials/Products at the optimal price such that " +
"the amount sold matches the amount produced.",
},
{
name: "Overclock",
cost: 15e3,
desc: "Equip employees with a headset that uses transcranial direct current " +
"stimulation (tDCS) to increase the speed of their neurotransmitters. " +
"This research increases the intelligence and efficiency of all " +
"employees by 25%.",
employeeEffMult: 1.25,
employeeIntMult: 1.25,
},
{
name: "Self-Correcting Assemblers",
cost: 25e3,
desc: "Create assemblers that can be used for universal production. " +
"These assemblers use deep learning to improve their efficiency " +
"at their tasks. This research increases all production by 10%",
productionMult: 1.1,
},
{
name: "Sti.mu",
cost: 30e3,
desc: "Upgrade the tDCS headset to stimulate regions of the brain that " +
"control confidence and enthusiasm. This research increases the max " +
"morale of all employees by 10.",
},
{
name: "sudo.Assist",
cost: 15e3,
desc: "Develop a virtual assistant AI to handle and manage administrative " +
"issues for your corporation.",
},
{
name: "uPgrade: Capacity.I",
cost: 20e3,
desc: "Expand the industry's capacity for designing and manufacturing its " +
"various products. This increases the industry's maximum number of products " +
"by 1 (from 3 to 4).",
},
{
name: "uPgrade: Capacity.II",
cost: 30e3,
desc: "Expand the industry's capacity for designing and manufacturing its " +
"various products. This increases the industry's maximum number of products " +
"by 1 (from 4 to 5).",
},
{
name: "uPgrade: Dashboard",
cost: 5e3,
desc: "Improve the software used to manage the industry's production line " +
"for its various products. This allows you to manage the production and " +
"sale of a product before it's finished being designed.",
},
{
name: "uPgrade: Fulcrum",
cost: 10e3,
desc: "Streamline the manufacturing of this industry's various products. " +
"This research increases the production of your products by 5%",
productProductionMult: 1.05,
},
];
/***/ }),
/* 1128 */
/*!*************************************!*\
!*** ./src/Corporation/Research.ts ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Research = void 0;
class Research {
constructor(p = { name: "", cost: 0, desc: "" }) {
// Name of research. This will be used to identify researches in the Research Tree
this.name = "";
// How much scientific research it costs to unlock this
this.cost = 0;
// Description of what the Research does
this.desc = "";
// All possible generic upgrades for the company, in the form of multipliers
this.advertisingMult = 1;
this.employeeChaMult = 1;
this.employeeCreMult = 1;
this.employeeEffMult = 1;
this.employeeIntMult = 1;
this.productionMult = 1;
this.productProductionMult = 1;
this.salesMult = 1;
this.sciResearchMult = 1;
this.storageMult = 1;
this.name = p.name;
this.cost = p.cost;
this.desc = p.desc;
if (p.advertisingMult) {
this.advertisingMult = p.advertisingMult;
}
if (p.employeeChaMult) {
this.employeeChaMult = p.employeeChaMult;
}
if (p.employeeCreMult) {
this.employeeCreMult = p.employeeCreMult;
}
if (p.employeeEffMult) {
this.employeeEffMult = p.employeeEffMult;
}
if (p.employeeIntMult) {
this.employeeIntMult = p.employeeIntMult;
}
if (p.productionMult) {
this.productionMult = p.productionMult;
}
if (p.productProductionMult) {
this.productProductionMult = p.productProductionMult;
}
if (p.salesMult) {
this.salesMult = p.salesMult;
}
if (p.sciResearchMult) {
this.sciResearchMult = p.sciResearchMult;
}
if (p.storageMult) {
this.storageMult = p.storageMult;
}
}
}
exports.Research = Research;
/***/ }),
/* 1129 */
/*!**************************************************!*\
!*** ./src/Corporation/data/BaseResearchTree.ts ***!
\**************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getProductIndustryResearchTreeCopy = exports.getBaseResearchTreeCopy = void 0;
const ResearchMap_1 = __webpack_require__(/*! ../ResearchMap */ 493);
const ResearchTree_1 = __webpack_require__(/*! ../ResearchTree */ 1126);
function makeNode(name) {
const research = ResearchMap_1.ResearchMap[name];
if (research == null) {
throw new Error(`Invalid research name: ${name}`);
}
return new ResearchTree_1.Node({ text: research.name, cost: research.cost });
}
// Creates the Nodes for the BaseResearchTree.
// Return the Root Node
function createBaseResearchTreeNodes() {
const rootNode = makeNode("Hi-Tech R&D Laboratory");
const autoBrew = makeNode("AutoBrew");
const autoParty = makeNode("AutoPartyManager");
const autoDrugs = makeNode("Automatic Drug Administration");
const bulkPurchasing = makeNode("Bulk Purchasing");
const cph4 = makeNode("CPH4 Injections");
const drones = makeNode("Drones");
const dronesAssembly = makeNode("Drones - Assembly");
const dronesTransport = makeNode("Drones - Transport");
const goJuice = makeNode("Go-Juice");
const hrRecruitment = makeNode("HRBuddy-Recruitment");
const hrTraining = makeNode("HRBuddy-Training");
const joywire = makeNode("JoyWire");
const marketta1 = makeNode("Market-TA.I");
const marketta2 = makeNode("Market-TA.II");
const overclock = makeNode("Overclock");
const scAssemblers = makeNode("Self-Correcting Assemblers");
const stimu = makeNode("Sti.mu");
autoDrugs.addChild(goJuice);
autoDrugs.addChild(cph4);
drones.addChild(dronesAssembly);
drones.addChild(dronesTransport);
hrRecruitment.addChild(hrTraining);
marketta1.addChild(marketta2);
overclock.addChild(stimu);
rootNode.addChild(autoBrew);
rootNode.addChild(autoParty);
rootNode.addChild(autoDrugs);
rootNode.addChild(bulkPurchasing);
rootNode.addChild(drones);
rootNode.addChild(hrRecruitment);
rootNode.addChild(joywire);
rootNode.addChild(marketta1);
rootNode.addChild(overclock);
rootNode.addChild(scAssemblers);
return rootNode;
}
function getBaseResearchTreeCopy() {
const baseResearchTree = new ResearchTree_1.ResearchTree();
baseResearchTree.setRoot(createBaseResearchTreeNodes());
return baseResearchTree;
}
exports.getBaseResearchTreeCopy = getBaseResearchTreeCopy;
// Base Research Tree for Industry's that make products
function getProductIndustryResearchTreeCopy() {
const researchTree = new ResearchTree_1.ResearchTree();
const root = createBaseResearchTreeNodes();
const upgradeFulcrum = makeNode("uPgrade: Fulcrum");
const upgradeCapacity1 = makeNode("uPgrade: Capacity.I");
const upgradeCapacity2 = makeNode("uPgrade: Capacity.II");
const upgradeDashboard = makeNode("uPgrade: Dashboard");
upgradeCapacity1.addChild(upgradeCapacity2);
upgradeFulcrum.addChild(upgradeCapacity1);
upgradeFulcrum.addChild(upgradeDashboard);
root.addChild(upgradeFulcrum);
researchTree.setRoot(root);
return researchTree;
}
exports.getProductIndustryResearchTreeCopy = getProductIndustryResearchTreeCopy;
/***/ }),
/* 1130 */
/*!*************************************************!*\
!*** ./src/Corporation/ui/NewIndustryPopup.tsx ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NewIndustryPopup = void 0;
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
const DialogBox_1 = __webpack_require__(/*! ../../../utils/DialogBox */ 13);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
const IndustryData_1 = __webpack_require__(/*! ../IndustryData */ 165);
const Industry_1 = __webpack_require__(/*! ../Industry */ 1125);
// Create a popup that lets the player create a new industry.
// This is created when the player clicks the "Expand into new Industry" header tab
function NewIndustryPopup(props) {
const allIndustries = Object.keys(IndustryData_1.Industries).sort();
const possibleIndustries = allIndustries.filter((industryType) => props.corp.divisions.find((division) => division.type === industryType) === undefined).sort();
const [industry, setIndustry] = react_1.useState(possibleIndustries.length > 0 ? possibleIndustries[0] : '');
const [name, setName] = react_1.useState('');
function newIndustry() {
const ind = industry;
const newDivisionName = name;
for (let i = 0; i < props.corp.divisions.length; ++i) {
if (props.corp.divisions[i].name === newDivisionName) {
DialogBox_1.dialogBoxCreate("This name is already in use!");
return;
}
}
if (props.corp.funds.lt(IndustryData_1.IndustryStartingCosts[ind])) {
DialogBox_1.dialogBoxCreate("Not enough money to create a new division in this industry");
}
else if (newDivisionName === "") {
DialogBox_1.dialogBoxCreate("New division must have a name!");
}
else {
props.corp.funds = props.corp.funds.minus(IndustryData_1.IndustryStartingCosts[ind]);
const newInd = new Industry_1.Industry({
corp: props.corp,
name: newDivisionName,
type: ind,
});
props.corp.divisions.push(newInd);
// Set routing to the new division so that the UI automatically switches to it
props.routing.routeTo(newDivisionName);
createPopup_1.removePopup(props.popupId);
}
}
function onNameChange(event) {
setName(event.target.value);
}
function onKeyDown(event) {
if (event.keyCode === 13)
newIndustry();
}
function onIndustryChange(event) {
setIndustry(event.target.value);
}
return (react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.createElement("p", null, "Create a new division to expand into a new industry:"),
react_1.default.createElement("select", { className: "dropdown", defaultValue: industry, onChange: onIndustryChange }, possibleIndustries.map((industry) => react_1.default.createElement("option", { key: industry, value: industry }, industry))),
react_1.default.createElement("p", null, IndustryData_1.IndustryDescriptions[industry]),
react_1.default.createElement("br", null),
react_1.default.createElement("br", null),
react_1.default.createElement("p", null, "Division name:"),
react_1.default.createElement("input", { autoFocus: true, value: name, onChange: onNameChange, onKeyDown: onKeyDown, type: "text", className: "text-input", style: { display: "block" }, maxLength: 30, pattern: "[a-zA-Z0-9-_]" }),
react_1.default.createElement("span", { onClick: newIndustry, className: "popup-box-button" }, "Create Division")));
}
exports.NewIndustryPopup = NewIndustryPopup;
/***/ }),
/* 1131 */
/*!******************************************!*\
!*** ./src/Corporation/ui/HeaderTab.tsx ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeaderTab = void 0;
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
function HeaderTab(props) {
let className = "cmpy-mgmt-header-tab";
if (props.current) {
className += " current";
}
return (react_1.default.createElement("button", { className: className, onClick: props.onClick }, props.text));
}
exports.HeaderTab = HeaderTab;
/***/ }),
/* 1132 */
/*!*******************************************!*\
!*** ./src/Corporation/ui/HeaderTabs.tsx ***!
\*******************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeaderTabs = void 0;
// React Components for the Corporation UI's navigation tabs
// These are the tabs at the top of the UI that let you switch to different
// divisions, see an overview of your corporation, or create a new industry
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const HeaderTab_1 = __webpack_require__(/*! ./HeaderTab */ 1131);
const NewIndustryPopup_1 = __webpack_require__(/*! ./NewIndustryPopup */ 1130);
const createPopup_1 = __webpack_require__(/*! ../../ui/React/createPopup */ 41);
function HeaderTabs(props) {
function overviewOnClick() {
props.routing.routeToOverviewPage();
props.corp.rerender(props.player);
}
function openNewIndustryPopup() {
const popupId = "cmpy-mgmt-expand-industry-popup";
createPopup_1.createPopup(popupId, NewIndustryPopup_1.NewIndustryPopup, {
corp: props.corp,
routing: props.routing,
popupId: popupId,
});
}
return (react_1.default.createElement("div", null,
react_1.default.createElement(HeaderTab_1.HeaderTab, { current: props.routing.isOnOverviewPage(), key: "overview", onClick: overviewOnClick, text: props.corp.name }),
props.corp.divisions.map((division) => react_1.default.createElement(HeaderTab_1.HeaderTab, { current: props.routing.isOn(division.name), key: division.name, onClick: () => {
props.routing.routeTo(division.name);
props.corp.rerender(props.player);
}, text: division.name })),
react_1.default.createElement(HeaderTab_1.HeaderTab, { current: false, onClick: openNewIndustryPopup, text: "Expand into new Industry" })));
}
exports.HeaderTabs = HeaderTabs;
/***/ }),
/* 1133 */
/*!*************************************!*\
!*** ./src/Corporation/ui/Root.tsx ***!
\*************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorporationRoot = void 0;
// Root React Component for the Corporation UI
const react_1 = __importDefault(__webpack_require__(/*! react */ 0));
const HeaderTabs_1 = __webpack_require__(/*! ./HeaderTabs */ 1132);
const MainPanel_1 = __webpack_require__(/*! ./MainPanel */ 1120);
function CorporationRoot(props) {
return (react_1.default.createElement("div", null,
react_1.default.createElement(HeaderTabs_1.HeaderTabs, { corp: props.corp, routing: props.routing, player: props.player }),
react_1.default.createElement(MainPanel_1.MainPanel, { corp: props.corp, routing: props.routing, player: props.player })));
}
exports.CorporationRoot = CorporationRoot;
/***/ }),
/* 1134 */
/*!**************************************!*\
!*** ./src/Literature/Literature.ts ***!
\**************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Literature = void 0;
/**
* Lore / world building literature files that can be found on servers.
* These files can be read by the player
*/
class Literature {
constructor(title, filename, txt) {
this.title = title;
this.fn = filename;
this.txt = txt;
}
}
exports.Literature = Literature;
/***/ }),
/* 1135 */
/*!***************************************!*\
!*** ./src/Literature/Literatures.ts ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Literatures = void 0;
const Literature_1 = __webpack_require__(/*! ./Literature */ 1134);
const LiteratureNames_1 = __webpack_require__(/*! ./data/LiteratureNames */ 144);
exports.Literatures = {};
(function () {
let title, fn, txt;
title = "The Beginner's Guide to Hacking";
fn = LiteratureNames_1.LiteratureNames.HackersStartingHandbook;
txt = "Some resources:
" +
"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.
" +
"-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)
" +
"-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()
" +
"-Keep security level low. Security level affects everything when hacking. Two important Netscript functions " +
"for this are getServerSecurityLevel() and getServerMinSecurityLevel()
" +
"-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
" +
"-Prioritize upgrading the RAM on your home computer. This can also be done at 'Alpha Enterprises'
" +
"-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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The Complete Handbook for Creating a Successful Corporation";
fn = LiteratureNames_1.LiteratureNames.CorporationManagementHandbook;
txt = "Getting Started with Corporations " +
"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.
" +
"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.
" +
"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.
" +
"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.
" +
"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').
" +
"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.
" +
"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.
" +
"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.
" +
"Tips/Pointers " +
"-The 'Smart Supply' upgrade is extremely useful. Consider purchasing it as soon as possible.
" +
"-Purchasing Hardware, Robots, AI Cores, and Real Estate can potentially increase your production. " +
"The effects of these depend on what industry you are in.
" +
"-In order to optimize your production, you will need a good balance of Operators, Managers, and Engineers
" +
"-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.
" +
"-If your employees have low morale, energy, or happiness, their production will greatly suffer.
" +
"-Tech is important, but don't neglect sales! Having several Businessmen can boost your sales and your bottom line.
" +
"-Don't forget to advertise your company. You won't have any business if nobody knows you.
" +
"-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
" +
"-Remember, you need to spend money to make money!
" +
"-Corporations do not reset when installing Augmentations, but they do reset when destroying a BitNode";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "A Brief History of Synthoids";
fn = LiteratureNames_1.LiteratureNames.HistoryOfSynthoids;
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.
" +
"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.
" +
"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.
" +
"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.
" +
"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.
" +
"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.
" +
"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.
" +
"To this day, tensions still exist between the remaining Synthoids and humans as a result of the Uprising.
" +
"Nobody knows what happened to the terrorist group Ascendis Totalis.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "A Green Tomorrow";
fn = LiteratureNames_1.LiteratureNames.AGreenTomorrow;
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 renewable sources such as " +
"solar and geothermal energy. Unfortunately, these efforts were not the huge success that they seem to be.
" +
"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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Alpha and Omega";
fn = LiteratureNames_1.LiteratureNames.AlphaOmega;
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.'
" +
"And once we 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.'";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Are We Living in a Computer Simulation?";
fn = LiteratureNames_1.LiteratureNames.SimulatedReality;
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.
" +
"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 continued technological advancement " +
"is a reasonable outcome, then it is very likely that such a scenario has already happened.
" +
"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?";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Beyond Man";
fn = LiteratureNames_1.LiteratureNames.BeyondMan;
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.
" +
"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?
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Brighter than the Sun";
fn = LiteratureNames_1.LiteratureNames.BrighterThanTheSun;
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.
" +
"TaiYang Digital is a Chinese internet-technology corporation that provides services such as " +
"online advertising, search engines, 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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Democracy is Dead: The Fall of an Empire";
fn = LiteratureNames_1.LiteratureNames.DemocracyIsDead;
txt = "They rose from the shadows in the street. From the places where the oppressed meet. " +
"Their cries echoed loudly through the air. As they once did in Tiananmen Square. " +
"Loudness in the silence, Darkness in the light. They came forth with power and might. " +
"Once the beacon of democracy, America was first. Its pillars of society destroyed and dispersed. " +
"Soon the cries rose everywhere, with revolt and riot. Until one day, finally, all was quiet. " +
"From the ashes rose a new order, corporatocracy was its name. " +
"Rome, Mongol, Byzantine, all of history is just the same. " +
"For man will never change in a fundamental way. " +
"And now democracy is dead, in the USA.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Figures Show Rising Crime Rates in Sector-12";
fn = LiteratureNames_1.LiteratureNames.Sector12Crime;
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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Man and the Machine";
fn = LiteratureNames_1.LiteratureNames.ManAndMachine;
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?
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Secret Societies";
fn = LiteratureNames_1.LiteratureNames.SecretSocieties;
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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Space: The Failed Frontier";
fn = LiteratureNames_1.LiteratureNames.TheFailedFrontier;
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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Coded Intelligence: Myth or Reality?";
fn = LiteratureNames_1.LiteratureNames.CodedIntelligence;
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.
" +
"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.
" +
"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.'";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Synthetic Muscles";
fn = LiteratureNames_1.LiteratureNames.SyntheticMuscles;
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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "Tensions rise in global tech race";
fn = LiteratureNames_1.LiteratureNames.TensionsInTechRace;
txt = "Have we entered a new Cold War? Is WWIII just beyond the horizon?
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The Cost of Immortality";
fn = LiteratureNames_1.LiteratureNames.CostOfImmortality;
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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The Hidden World";
fn = LiteratureNames_1.LiteratureNames.TheHiddenWorld;
txt = "WAKE UP SHEEPLE
" +
"THE GOVERNMENT DOES NOT EXIST. CORPORATIONS DO NOT RUN SOCIETY
" +
"THE ILLUMINATI ARE THE SECRET RULERS OF THE WORLD!
" +
"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.
" +
"OPEN YOUR EYES
" +
"It was the Illuminati that brought an end to democracy in the world. They are the driving force " +
"behind everything that happens.
" +
"THEY ARE ALL AROUND YOU
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The New God";
fn = LiteratureNames_1.LiteratureNames.TheNewGod;
txt = "Everyone has a moment in their life when they wonder about the bigger questions.
" +
"What's the point of all this? What is my purpose?
" +
"Some people dare to think even bigger.
" +
"What will the fate of the human race be?
" +
"We live in an era vastly different from that of 15 or even 20 years ago. We have gone " +
"beyond the limits of humanity. We have stripped ourselves of the tyranny of flesh.
" +
"The Singularity is here. The merging of man and machine. This is where humanity evolves into ";
"something greater. This is our future.
" +
"Embrace it, and you will obey a new god. The God in the Machine.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The New Triads";
fn = LiteratureNames_1.LiteratureNames.NewTriads;
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.
" +
"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.
" +
"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.";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
title = "The Secret War";
fn = LiteratureNames_1.LiteratureNames.TheSecretWar;
txt = "";
exports.Literatures[fn] = new Literature_1.Literature(title, fn, txt);
})();
/***/ }),
/* 1136 */
/*!********************************!*\
!*** ./src/ui/React/Popup.tsx ***!
\********************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Popup = void 0;
/**
* React component for a popup content container
*
* Takes in a prop for rendering the content inside the popup
*/
const react_1 = __importStar(__webpack_require__(/*! react */ 0));
function Popup(props) {
function keyDown(event) {
if (event.key === 'Escape')
props.removePopup(props.id);
}
react_1.useEffect(() => {
document.addEventListener('keydown', keyDown);
return () => {
document.removeEventListener('keydown', keyDown);
};
});
return (react_1.default.createElement("div", { className: "popup-box-content", id: `${props.id}-content` }, react_1.default.createElement(props.content, props.props)));
}
exports.Popup = Popup;
/***/ }),
/* 1137 */,
/* 1138 */,
/* 1139 */,
/* 1140 */,
/* 1141 */,
/* 1142 */
/*!*********************************************!*\
!*** ./src/Corporation/CorporationState.ts ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorporationState = exports.AllCorporationStates = void 0;
const JSONReviver_1 = __webpack_require__(/*! ../../utils/JSONReviver */ 29);
// Array of all valid states
exports.AllCorporationStates = ["START", "PURCHASE", "PRODUCTION", "SALE", "EXPORT"];
class CorporationState {
constructor() {
// Number representing what state the Corporation is in. The number
// is an index for the array that holds all Corporation States
this.state = 0;
}
// Get the name of the current state
// NOTE: This does NOT return the number stored in the 'state' property,
// which is just an index for the array of all possible Corporation States.
getState() {
return exports.AllCorporationStates[this.state];
}
// Transition to the next state
nextState() {
if (this.state < 0 || this.state >= exports.AllCorporationStates.length) {
this.state = 0;
}
++this.state;
if (this.state >= exports.AllCorporationStates.length) {
this.state = 0;
}
}
// Serialize the current object to a JSON save state.
toJSON() {
return JSONReviver_1.Generic_toJSON("CorporationState", this);
}
// Initiatizes a CorporationState object from a JSON save state.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value) {
return JSONReviver_1.Generic_fromJSON(CorporationState, value.data);
}
}
exports.CorporationState = CorporationState;
JSONReviver_1.Reviver.constructors.CorporationState = CorporationState;
/***/ }),
/* 1143 */
/*!********************************************************!*\
!*** ./src/Augmentation/ui/InstalledAugmentations.tsx ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstalledAugmentations = void 0;
/**
* React Component for displaying a list of the player's installed Augmentations
* on the Augmentations UI
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const Player_1 = __webpack_require__(/*! ../../Player */ 2);
const Augmentations_1 = __webpack_require__(/*! ../../Augmentation/Augmentations */ 12);
const AugmentationNames_1 = __webpack_require__(/*! ../../Augmentation/data/AugmentationNames */ 4);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const SettingEnums_1 = __webpack_require__(/*! ../../Settings/SettingEnums */ 222);
const AugmentationAccordion_1 = __webpack_require__(/*! ../../ui/React/AugmentationAccordion */ 642);
function InstalledAugmentations() {
const sourceAugs = Player_1.Player.augmentations.slice();
if (Settings_1.Settings.OwnedAugmentationsOrder === SettingEnums_1.OwnedAugmentationsOrderSetting.Alphabetically) {
sourceAugs.sort((aug1, aug2) => {
return aug1.name <= aug2.name ? -1 : 1;
});
}
const augs = sourceAugs.map((e) => {
const aug = Augmentations_1.Augmentations[e.name];
let level = null;
if (e.name === AugmentationNames_1.AugmentationNames.NeuroFluxGovernor) {
level = e.level;
}
return (React.createElement("li", { key: e.name },
React.createElement(AugmentationAccordion_1.AugmentationAccordion, { aug: aug, level: level })));
});
return (React.createElement(React.Fragment, null, augs));
}
exports.InstalledAugmentations = InstalledAugmentations;
/***/ }),
/* 1144 */
/*!**********************************************************************!*\
!*** ./src/Augmentation/ui/InstalledAugmentationsAndSourceFiles.tsx ***!
\**********************************************************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstalledAugmentationsAndSourceFiles = void 0;
/**
* React Component for displaying all of the player's installed Augmentations and
* Source-Files.
*
* It also contains 'configuration' buttons that allow you to change how the
* Augs/SF's are displayed
*/
const React = __importStar(__webpack_require__(/*! react */ 0));
const InstalledAugmentations_1 = __webpack_require__(/*! ./InstalledAugmentations */ 1143);
const ListConfiguration_1 = __webpack_require__(/*! ./ListConfiguration */ 963);
const OwnedSourceFiles_1 = __webpack_require__(/*! ./OwnedSourceFiles */ 962);
const SourceFileMinus1_1 = __webpack_require__(/*! ./SourceFileMinus1 */ 960);
const Settings_1 = __webpack_require__(/*! ../../Settings/Settings */ 24);
const SettingEnums_1 = __webpack_require__(/*! ../../Settings/SettingEnums */ 222);
class InstalledAugmentationsAndSourceFiles extends React.Component {
constructor(props) {
super(props);
this.state = {
rerenderFlag: false,
};
this.collapseAllHeaders = this.collapseAllHeaders.bind(this);
this.expandAllHeaders = this.expandAllHeaders.bind(this);
this.sortByAcquirementTime = this.sortByAcquirementTime.bind(this);
this.sortInOrder = this.sortInOrder.bind(this);
this.listRef = React.createRef();
}
collapseAllHeaders() {
const ul = this.listRef.current;
if (ul == null) {
return;
}
const tickers = ul.getElementsByClassName("accordion-header");
for (let i = 0; i < tickers.length; ++i) {
const ticker = tickers[i];
if (!(ticker instanceof HTMLButtonElement)) {
continue;
}
if (ticker.classList.contains("active")) {
ticker.click();
}
}
}
expandAllHeaders() {
const ul = this.listRef.current;
if (ul == null) {
return;
}
const tickers = ul.getElementsByClassName("accordion-header");
for (let i = 0; i < tickers.length; ++i) {
const ticker = tickers[i];
if (!(ticker instanceof HTMLButtonElement)) {
continue;
}
if (!ticker.classList.contains("active")) {
ticker.click();
}
}
}
rerender() {
this.setState((prevState) => {
return {
rerenderFlag: !prevState.rerenderFlag,
};
});
}
sortByAcquirementTime() {
Settings_1.Settings.OwnedAugmentationsOrder = SettingEnums_1.OwnedAugmentationsOrderSetting.AcquirementTime;
this.rerender();
}
sortInOrder() {
Settings_1.Settings.OwnedAugmentationsOrder = SettingEnums_1.OwnedAugmentationsOrderSetting.Alphabetically;
this.rerender();
}
render() {
return (React.createElement(React.Fragment, null,
React.createElement(ListConfiguration_1.ListConfiguration, { collapseAllButtonsFn: this.collapseAllHeaders, expandAllButtonsFn: this.expandAllHeaders, sortByAcquirementTimeFn: this.sortByAcquirementTime, sortInOrderFn: this.sortInOrder }),
React.createElement("ul", { className: "augmentations-list", ref: this.listRef },
React.createElement(SourceFileMinus1_1.SourceFileMinus1, null),
React.createElement(OwnedSourceFiles_1.OwnedSourceFiles, null),
React.createElement(InstalledAugmentations_1.InstalledAugmentations, null))));
}
}
exports.InstalledAugmentationsAndSourceFiles = InstalledAugmentationsAndSourceFiles;
/***/ })
/******/ ]);
//# sourceMappingURL=engine.bundle.js.map