all the lints

This commit is contained in:
Olivier Gagnon 2021-05-01 03:17:31 -04:00
parent abe0330dc3
commit d745150c45
231 changed files with 1458 additions and 1439 deletions

@ -2,3 +2,7 @@ node_modules/
doc/build/ doc/build/
dist/ dist/
tests/*.bundle.* tests/*.bundle.*
src/ThirdParty/*
src/ScriptEditor/CodeMirrorNetscriptMode.js
src/ScriptEditor/CodeMirrorNetscriptLint.js
src/JSInterpreter.js

@ -858,8 +858,18 @@ module.exports = {
"error", "error",
"never", "never",
], ],
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/explicit-function-return-type": "off",
}, },
"overrides": [ "overrides": [
{
// enable the rule specifically for TypeScript files
"files": ["*.ts", "*.tsx"],
"rules": {
"@typescript-eslint/explicit-function-return-type": ["error"],
"@typescript-eslint/explicit-module-boundary-types": ["error"],
},
},
{ {
// TypeScript configuration // TypeScript configuration
"files": [ "**/*.ts", "**/*.tsx" ], "files": [ "**/*.ts", "**/*.tsx" ],

@ -22,12 +22,12 @@ export function loadGlobalAliases(saveString: string): void {
// Prints all aliases to terminal // Prints all aliases to terminal
export function printAliases(): void { export function printAliases(): void {
for (var name in Aliases) { for (const name in Aliases) {
if (Aliases.hasOwnProperty(name)) { if (Aliases.hasOwnProperty(name)) {
post("alias " + name + "=" + Aliases[name]); post("alias " + name + "=" + Aliases[name]);
} }
} }
for (var name in GlobalAliases) { for (const name in GlobalAliases) {
if (GlobalAliases.hasOwnProperty(name)) { if (GlobalAliases.hasOwnProperty(name)) {
post("global alias " + name + "=" + GlobalAliases[name]); post("global alias " + name + "=" + GlobalAliases[name]);
} }
@ -100,17 +100,17 @@ export function substituteAliases(origCommand: string): string {
// For the unalias command, dont substite // For the unalias command, dont substite
if (commandArray[0] === "unalias") { return commandArray.join(" "); } if (commandArray[0] === "unalias") { return commandArray.join(" "); }
var alias = getAlias(commandArray[0]); const alias = getAlias(commandArray[0]);
if (alias != null) { if (alias != null) {
commandArray[0] = alias; commandArray[0] = alias;
} else { } else {
var alias = getGlobalAlias(commandArray[0]); const alias = getGlobalAlias(commandArray[0]);
if (alias != null) { if (alias != null) {
commandArray[0] = alias; commandArray[0] = alias;
} }
} }
for (let i = 0; i < commandArray.length; ++i) { for (let i = 0; i < commandArray.length; ++i) {
var alias = getGlobalAlias(commandArray[i]); const alias = getGlobalAlias(commandArray[i]);
if (alias != null) { if (alias != null) {
commandArray[i] = alias; commandArray[i] = alias;
} }

@ -49,10 +49,6 @@ interface IConstructorParams {
} }
export class Augmentation { export class Augmentation {
// Initiatizes a Augmentation object from a JSON save state.
static fromJSON(value: any): Augmentation {
return Generic_fromJSON(Augmentation, value.data);
}
// How much money this costs to buy // How much money this costs to buy
baseCost = 0; baseCost = 0;
@ -141,7 +137,7 @@ export class Augmentation {
console.warn(`In Augmentation.addToFactions(), could not find faction with this name: ${factionList[i]}`); console.warn(`In Augmentation.addToFactions(), could not find faction with this name: ${factionList[i]}`);
continue; continue;
} }
faction!.augmentations.push(this.name); faction.augmentations.push(this.name);
} }
} }
@ -154,7 +150,7 @@ export class Augmentation {
console.warn(`Invalid Faction object in addToAllFactions(). Key value: ${fac}`); console.warn(`Invalid Faction object in addToAllFactions(). Key value: ${fac}`);
continue; continue;
} }
facObj!.augmentations.push(this.name); facObj.augmentations.push(this.name);
} }
} }
} }
@ -163,6 +159,12 @@ export class Augmentation {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Augmentation", this); return 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: any): Augmentation {
return Generic_fromJSON(Augmentation, value.data);
}
} }
Reviver.constructors.Augmentation = Augmentation; Reviver.constructors.Augmentation = Augmentation;

@ -8,29 +8,13 @@ import { AugmentationsRoot } from "./ui/Root";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { CONSTANTS } from "../Constants"; import { CONSTANTS } from "../Constants";
import { Factions, factionExists } from "../Faction/Factions"; import { Factions, factionExists } from "../Faction/Factions";
import { startWorkerScript } from "../NetscriptWorker";
import { Player } from "../Player"; import { Player } from "../Player";
import { prestigeAugmentation } from "../Prestige"; import { prestigeAugmentation } from "../Prestige";
import { saveObject } from "../SaveObject"; import { saveObject } from "../SaveObject";
import { RunningScript } from "../Script/RunningScript";
import { Script } from "../Script/Script";
import { Server } from "../Server/Server";
import { OwnedAugmentationsOrderSetting } from "../Settings/SettingEnums";
import { Settings } from "../Settings/Settings";
import { Page, routing } from "../ui/navigationTracking"; import { Page, routing } from "../ui/navigationTracking";
import { dialogBoxCreate } from "../../utils/DialogBox"; import { dialogBoxCreate } from "../../utils/DialogBox";
import { createAccordionElement } from "../../utils/uiHelpers/createAccordionElement";
import {
Reviver,
Generic_toJSON,
Generic_fromJSON,
} from "../../utils/JSONReviver";
import { formatNumber } from "../../utils/StringHelperFunctions";
import { clearObject } from "../../utils/helpers/clearObject"; import { clearObject } from "../../utils/helpers/clearObject";
import { createElement } from "../../utils/uiHelpers/createElement";
import { isString } from "../../utils/helpers/isString";
import { removeChildrenFromElement } from "../../utils/uiHelpers/removeChildrenFromElement";
import { Money } from "../ui/React/Money"; import { Money } from "../ui/React/Money";
import React from "react"; import React from "react";

@ -15,7 +15,9 @@ import { SourceFileMinus1 } from "./SourceFileMinus1";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { OwnedAugmentationsOrderSetting } from "../../Settings/SettingEnums"; import { OwnedAugmentationsOrderSetting } from "../../Settings/SettingEnums";
type IProps = {} type IProps = {
// nothing special.
}
type IState = { type IState = {
rerenderFlag: boolean; rerenderFlag: boolean;
@ -39,7 +41,7 @@ export class InstalledAugmentationsAndSourceFiles extends React.Component<IProps
this.listRef = React.createRef(); this.listRef = React.createRef();
} }
collapseAllHeaders() { collapseAllHeaders(): void {
const ul = this.listRef.current; const ul = this.listRef.current;
if (ul == null) { return; } if (ul == null) { return; }
const tickers = ul.getElementsByClassName("accordion-header"); const tickers = ul.getElementsByClassName("accordion-header");
@ -55,7 +57,7 @@ export class InstalledAugmentationsAndSourceFiles extends React.Component<IProps
} }
} }
expandAllHeaders() { expandAllHeaders(): void {
const ul = this.listRef.current; const ul = this.listRef.current;
if (ul == null) { return; } if (ul == null) { return; }
const tickers = ul.getElementsByClassName("accordion-header"); const tickers = ul.getElementsByClassName("accordion-header");
@ -71,7 +73,7 @@ export class InstalledAugmentationsAndSourceFiles extends React.Component<IProps
} }
} }
rerender() { rerender(): void {
this.setState((prevState) => { this.setState((prevState) => {
return { return {
rerenderFlag: !prevState.rerenderFlag, rerenderFlag: !prevState.rerenderFlag,
@ -79,17 +81,17 @@ export class InstalledAugmentationsAndSourceFiles extends React.Component<IProps
}); });
} }
sortByAcquirementTime() { sortByAcquirementTime(): void {
Settings.OwnedAugmentationsOrder = OwnedAugmentationsOrderSetting.AcquirementTime; Settings.OwnedAugmentationsOrder = OwnedAugmentationsOrderSetting.AcquirementTime;
this.rerender(); this.rerender();
} }
sortInOrder() { sortInOrder(): void {
Settings.OwnedAugmentationsOrder = OwnedAugmentationsOrderSetting.Alphabetically Settings.OwnedAugmentationsOrder = OwnedAugmentationsOrderSetting.Alphabetically
this.rerender(); this.rerender();
} }
render() { render(): React.ReactNode {
return ( return (
<> <>
<ListConfiguration <ListConfiguration

@ -7,7 +7,7 @@ import { Player } from "../../Player";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../../ui/numeralFormat";
import { Augmentations} from "../Augmentations"; import { Augmentations} from "../Augmentations";
function calculateAugmentedStats() { function calculateAugmentedStats(): any {
const augP: any = {}; const augP: any = {};
for(const aug of Player.queuedAugmentations) { for(const aug of Player.queuedAugmentations) {
const augObj = Augmentations[aug.name]; const augObj = Augmentations[aug.name];
@ -22,8 +22,8 @@ function calculateAugmentedStats() {
export function PlayerMultipliers(): React.ReactElement { export function PlayerMultipliers(): React.ReactElement {
const mults = calculateAugmentedStats(); const mults = calculateAugmentedStats();
function MultiplierTable(rows: any[]): React.ReactElement { function MultiplierTable(rows: any[]): React.ReactElement {
function improvements(r: number) { function improvements(r: number): JSX.Element[] {
let elems: any[] = []; let elems: JSX.Element[] = [];
if(r) { if(r) {
elems = [ elems = [
<td key="2">&nbsp;{"=>"}&nbsp;</td>, <td key="2">&nbsp;{"=>"}&nbsp;</td>,

@ -25,7 +25,7 @@ export class AugmentationsRoot extends React.Component<IProps, IState> {
super(props); super(props);
} }
render() { render(): React.ReactNode {
return ( return (
<div id="augmentations-content"> <div id="augmentations-content">
<h1>Purchased Augmentations</h1> <h1>Purchased Augmentations</h1>

@ -5,9 +5,6 @@
import * as React from "react"; import * as React from "react";
import { Player } from "../../Player"; import { Player } from "../../Player";
import { Settings } from "../../Settings/Settings";
import { OwnedAugmentationsOrderSetting } from "../../Settings/SettingEnums";
import { SourceFiles } from "../../SourceFile/SourceFiles";
import { Exploit, ExploitName } from "../../Exploits/Exploit"; import { Exploit, ExploitName } from "../../Exploits/Exploit";
import { Accordion } from "../../ui/React/Accordion"; import { Accordion } from "../../ui/React/Accordion";

@ -252,7 +252,7 @@ BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON");
BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON"); BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON");
BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON"); BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON");
export function initBitNodeMultipliers(p: IPlayer) { export function initBitNodeMultipliers(p: IPlayer): void {
if (p.bitNodeN == null) { if (p.bitNodeN == null) {
p.bitNodeN = 1; p.bitNodeN = 1;
} }
@ -433,15 +433,15 @@ export function initBitNodeMultipliers(p: IPlayer) {
BitNodeMultipliers.FourSigmaMarketDataCost = 4; BitNodeMultipliers.FourSigmaMarketDataCost = 4;
BitNodeMultipliers.FourSigmaMarketDataApiCost = 4; BitNodeMultipliers.FourSigmaMarketDataApiCost = 4;
break; break;
case 12: //The Recursion case 12: { //The Recursion
var sf12Lvl = 0; let sf12Lvl = 0;
for (let i = 0; i < p.sourceFiles.length; i++) { for (let i = 0; i < p.sourceFiles.length; i++) {
if (p.sourceFiles[i].n === 12) { if (p.sourceFiles[i].n === 12) {
sf12Lvl = p.sourceFiles[i].lvl; sf12Lvl = p.sourceFiles[i].lvl;
} }
} }
var inc = Math.pow(1.02, sf12Lvl); const inc = Math.pow(1.02, sf12Lvl);
var dec = 1/inc; const dec = 1/inc;
// Multiplier for number of augs needed for Daedalus increases // Multiplier for number of augs needed for Daedalus increases
// up to a maximum of 1.34, which results in 40 Augs required // up to a maximum of 1.34, which results in 40 Augs required
@ -499,6 +499,7 @@ export function initBitNodeMultipliers(p: IPlayer) {
BitNodeMultipliers.BladeburnerRank = dec; BitNodeMultipliers.BladeburnerRank = dec;
BitNodeMultipliers.BladeburnerSkillCost = inc; BitNodeMultipliers.BladeburnerSkillCost = inc;
break; break;
}
default: default:
console.warn("Player.bitNodeN invalid"); console.warn("Player.bitNodeN invalid");
break; break;

@ -1,7 +1,6 @@
import { Augmentations } from "./Augmentation/Augmentations"; import { Augmentations } from "./Augmentation/Augmentations";
import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; import { AugmentationNames } from "./Augmentation/data/AugmentationNames";
import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers";
import { CONSTANTS } from "./Constants";
import { Engine } from "./engine"; import { Engine } from "./engine";
import { Faction } from "./Faction/Faction"; import { Faction } from "./Faction/Faction";
import { Factions, factionExists } from "./Faction/Factions"; import { Factions, factionExists } from "./Faction/Factions";
@ -20,14 +19,16 @@ import {
Generic_fromJSON, Generic_fromJSON,
} from "../utils/JSONReviver"; } from "../utils/JSONReviver";
import { setTimeoutRef } from "./utils/SetTimeoutRef"; import { setTimeoutRef } from "./utils/SetTimeoutRef";
import { formatNumber } from "../utils/StringHelperFunctions"; import {
formatNumber,
convertTimeMsToTimeElapsedString,
} from "../utils/StringHelperFunctions";
import { ConsoleHelpText } from "./Bladeburner/data/Help"; import { ConsoleHelpText } from "./Bladeburner/data/Help";
import { City } from "./Bladeburner/City"; import { City } from "./Bladeburner/City";
import { BladeburnerConstants } from "./Bladeburner/data/Constants"; import { BladeburnerConstants } from "./Bladeburner/data/Constants";
import { Skill } from "./Bladeburner/Skill"; import { Skill } from "./Bladeburner/Skill";
import { Skills } from "./Bladeburner/Skills"; import { Skills } from "./Bladeburner/Skills";
import { SkillNames } from "./Bladeburner/data/SkillNames";
import { Operation } from "./Bladeburner/Operation"; import { Operation } from "./Bladeburner/Operation";
import { BlackOperation } from "./Bladeburner/BlackOperation"; import { BlackOperation } from "./Bladeburner/BlackOperation";
import { BlackOperations } from "./Bladeburner/BlackOperations"; import { BlackOperations } from "./Bladeburner/BlackOperations";
@ -45,7 +46,6 @@ import { KEY } from "../utils/helpers/keyCodes";
import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement";
import { appendLineBreaks } from "../utils/uiHelpers/appendLineBreaks"; import { appendLineBreaks } from "../utils/uiHelpers/appendLineBreaks";
import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions";
import { createElement } from "../utils/uiHelpers/createElement"; import { createElement } from "../utils/uiHelpers/createElement";
import { createPopup } from "../utils/uiHelpers/createPopup"; import { createPopup } from "../utils/uiHelpers/createPopup";
import { removeElement } from "../utils/uiHelpers/removeElement"; import { removeElement } from "../utils/uiHelpers/removeElement";
@ -2132,7 +2132,6 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
})); }));
// General Info // General Info
var difficulty = action.getDifficulty();
var actionTime = action.getActionTime(this); var actionTime = action.getActionTime(this);
appendLineBreaks(el, 2); appendLineBreaks(el, 2);
el.appendChild(createElement("pre", { el.appendChild(createElement("pre", {
@ -2170,7 +2169,6 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
var isActive = el.classList.contains(ActiveActionCssClass); var isActive = el.classList.contains(ActiveActionCssClass);
var isCompleted = (this.blackops[action.name] != null); var isCompleted = (this.blackops[action.name] != null);
var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); var estimatedSuccessChance = action.getSuccessChance(this, {est:true});
var difficulty = action.getDifficulty();
var actionTime = action.getActionTime(this); var actionTime = action.getActionTime(this);
var hasReqdRank = this.rank >= action.reqdRank; var hasReqdRank = this.rank >= action.reqdRank;
@ -3210,7 +3208,7 @@ Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, worker
return -1; return -1;
} }
const sanitizedSize = Math.round(size); let sanitizedSize = Math.round(size);
if (isNaN(sanitizedSize) || sanitizedSize < 0) { if (isNaN(sanitizedSize) || sanitizedSize < 0) {
workerScript.log("bladeburner.setTeamSize", `Invalid size: ${size}`); workerScript.log("bladeburner.setTeamSize", `Invalid size: ${size}`);
return -1; return -1;

@ -3,11 +3,12 @@ import { getRandomInt } from "../../utils/helpers/getRandomInt";
import { addOffset } from "../../utils/helpers/addOffset"; import { addOffset } from "../../utils/helpers/addOffset";
import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver"; import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver";
import { BladeburnerConstants } from "./data/Constants"; import { BladeburnerConstants } from "./data/Constants";
// import { Contract } from "./Contract"; import { IBladeburner } from "./IBladeburner";
// import { Operation } from "./Operation"; import { IAction, ISuccessChanceParams } from "./IAction";
// import { BlackOperation } from "./BlackOperation";
class StatsMultiplier { class StatsMultiplier {
[key: string]: number;
hack = 0; hack = 0;
str = 0; str = 0;
def = 0; def = 0;
@ -15,8 +16,6 @@ class StatsMultiplier {
agi = 0; agi = 0;
cha = 0; cha = 0;
int = 0; int = 0;
[key: string]: number;
} }
export interface IActionParams { export interface IActionParams {
@ -43,7 +42,7 @@ export interface IActionParams {
teamCount?: number; teamCount?: number;
} }
export class Action { export class Action implements IAction {
name = ""; name = "";
desc = ""; desc = "";
@ -138,7 +137,7 @@ export class Action {
* Tests for success. Should be called when an action has completed * Tests for success. Should be called when an action has completed
* @param inst {Bladeburner} - Bladeburner instance * @param inst {Bladeburner} - Bladeburner instance
*/ */
attempt(inst: any): boolean { attempt(inst: IBladeburner): boolean {
return (Math.random() < this.getSuccessChance(inst)); return (Math.random() < this.getSuccessChance(inst));
} }
@ -147,7 +146,7 @@ export class Action {
return 1; return 1;
} }
getActionTime(inst: any): number { getActionTime(inst: IBladeburner): number {
const difficulty = this.getDifficulty(); const difficulty = this.getDifficulty();
let baseTime = difficulty / BladeburnerConstants.DifficultyToTimeFactor; let baseTime = difficulty / BladeburnerConstants.DifficultyToTimeFactor;
const skillFac = inst.skillMultipliers.actionTime; // Always < 1 const skillFac = inst.skillMultipliers.actionTime; // Always < 1
@ -165,15 +164,15 @@ export class Action {
} }
// For actions that have teams. To be implemented by subtypes. // For actions that have teams. To be implemented by subtypes.
getTeamSuccessBonus(inst: any): number { getTeamSuccessBonus(inst: IBladeburner): number {
return 1; return 1;
} }
getActionTypeSkillSuccessBonus(inst: any): number { getActionTypeSkillSuccessBonus(inst: IBladeburner): number {
return 1; return 1;
} }
getChaosCompetencePenalty(inst: any, params: any): number { getChaosCompetencePenalty(inst: IBladeburner, params: ISuccessChanceParams): number {
const city = inst.getCurrentCity(); const city = inst.getCurrentCity();
if (params.est) { if (params.est) {
return Math.pow((city.popEst / BladeburnerConstants.PopulationThreshold), BladeburnerConstants.PopulationExponent); return Math.pow((city.popEst / BladeburnerConstants.PopulationThreshold), BladeburnerConstants.PopulationExponent);
@ -182,7 +181,7 @@ export class Action {
} }
} }
getChaosDifficultyBonus(inst: any, params: any): number { getChaosDifficultyBonus(inst: IBladeburner/*, params: ISuccessChanceParams*/): number {
const city = inst.getCurrentCity(); const city = inst.getCurrentCity();
if (city.chaos > BladeburnerConstants.ChaosThreshold) { if (city.chaos > BladeburnerConstants.ChaosThreshold) {
const diff = 1 + (city.chaos - BladeburnerConstants.ChaosThreshold); const diff = 1 + (city.chaos - BladeburnerConstants.ChaosThreshold);
@ -198,7 +197,7 @@ export class Action {
* @params - options: * @params - options:
* est (bool): Get success chance estimate instead of real success chance * est (bool): Get success chance estimate instead of real success chance
*/ */
getSuccessChance(inst: any, params: any={}) { getSuccessChance(inst: IBladeburner, params: ISuccessChanceParams={est: false}): number {
if (inst == null) {throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");} if (inst == null) {throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");}
let difficulty = this.getDifficulty(); let difficulty = this.getDifficulty();
let competence = 0; let competence = 0;
@ -220,7 +219,7 @@ export class Action {
competence *= this.getTeamSuccessBonus(inst); competence *= this.getTeamSuccessBonus(inst);
competence *= this.getChaosCompetencePenalty(inst, params); competence *= this.getChaosCompetencePenalty(inst, params);
difficulty *= this.getChaosDifficultyBonus(inst, params); difficulty *= this.getChaosDifficultyBonus(inst);
if(this.name == "Raid" && inst.getCurrentCity().comms <= 0) { if(this.name == "Raid" && inst.getCurrentCity().comms <= 0) {
return 0; return 0;
@ -253,18 +252,14 @@ export class Action {
} }
} }
static fromJSON(value: any): Action {
return Generic_fromJSON(Action, value.data);
}
toJSON(): any { toJSON(): any {
return Generic_toJSON("Action", this); return Generic_toJSON("Action", this);
} }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): Action {
return Generic_fromJSON(Action, value.data);
}
} }
Reviver.constructors.Action = Action; Reviver.constructors.Action = Action;

@ -13,21 +13,22 @@ export class BlackOperation extends Operation {
return 1.5; return 1.5;
} }
getChaosCompetencePenalty(inst: any, params: any): number { getChaosCompetencePenalty(/*inst: IBladeburner, params: ISuccessChanceParams*/): number {
return 1; return 1;
} }
getChaosDifficultyBonus(inst: any, params: any): number { getChaosDifficultyBonus(/*inst: IBladeburner, params: ISuccessChanceParams*/): number {
return 1; return 1;
} }
static fromJSON(value: any): Operation {
return Generic_fromJSON(BlackOperation, value.data);
}
toJSON(): any { toJSON(): any {
return Generic_toJSON("BlackOperation", this); return Generic_toJSON("BlackOperation", this);
} }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): Operation {
return Generic_fromJSON(BlackOperation, value.data);
}
} }
Reviver.constructors.BlackOperation = BlackOperation; Reviver.constructors.BlackOperation = BlackOperation;

@ -154,19 +154,20 @@ export class City {
if (this.chaos < 0) {this.chaos = 0;} if (this.chaos < 0) {this.chaos = 0;}
} }
/**
* Initiatizes a City object from a JSON save state.
*/
static fromJSON(value: any): City {
return Generic_fromJSON(City, value.data);
}
/** /**
* Serialize the current object to a JSON save state. * Serialize the current object to a JSON save state.
*/ */
toJSON(): any { toJSON(): any {
return Generic_toJSON("City", this); return Generic_toJSON("City", this);
} }
/**
* Initiatizes a City object from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): City {
return Generic_fromJSON(City, value.data);
}
} }
Reviver.constructors.City = City; Reviver.constructors.City = City;

@ -1,4 +1,4 @@
// import { BladeburnerConstants } from "./data/Constants"; import { IBladeburner } from "./IBladeburner";
import { Action, IActionParams } from "./Action"; import { Action, IActionParams } from "./Action";
import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver"; import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver";
@ -8,17 +8,18 @@ export class Contract extends Action {
super(params); super(params);
} }
getActionTypeSkillSuccessBonus(inst: any): number { getActionTypeSkillSuccessBonus(inst: IBladeburner): number {
return inst.skillMultipliers.successChanceContract; return inst.skillMultipliers.successChanceContract;
} }
static fromJSON(value: any): Contract {
return Generic_fromJSON(Contract, value.data);
}
toJSON(): any { toJSON(): any {
return Generic_toJSON("Contract", this); return Generic_toJSON("Contract", this);
} }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): Contract {
return Generic_fromJSON(Contract, value.data);
}
} }
Reviver.constructors.Contract = Contract; Reviver.constructors.Contract = Contract;

@ -0,0 +1,71 @@
import { IBladeburner } from "./IBladeburner";
export interface IStatsMultiplier {
[key: string]: number;
hack: number;
str: number;
def: number;
dex: number;
agi: number;
cha: number;
int: number;
}
export interface ISuccessChanceParams {
est: boolean;
}
export interface IAction {
name: string;
desc: string;
// Difficulty scales with level. See getDifficulty() method
level: number;
maxLevel: number;
autoLevel: boolean;
baseDifficulty: number;
difficultyFac: number;
// Rank increase/decrease is affected by this exponent
rewardFac: number;
successes: number;
failures: number;
// All of these scale with level/difficulty
rankGain: number;
rankLoss: number;
hpLoss: number;
hpLost: number;
// Action Category. Current categories are stealth and kill
isStealth: boolean;
isKill: boolean;
/**
* Number of this contract remaining, and its growth rate
* Growth rate is an integer and the count will increase by that integer every "cycle"
*/
count: number;
countGrowth: number;
// Weighting of each stat in determining action success rate
weights: IStatsMultiplier;
// Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1)
decays: IStatsMultiplier;
teamCount: number;
getDifficulty(): number;
attempt(inst: IBladeburner): boolean;
getActionTimePenalty(): number;
getActionTime(inst: IBladeburner): number;
getTeamSuccessBonus(inst: IBladeburner): number;
getActionTypeSkillSuccessBonus(inst: IBladeburner): number;
getChaosCompetencePenalty(inst: IBladeburner, params: ISuccessChanceParams): number;
getChaosDifficultyBonus(inst: IBladeburner): number;
getSuccessChance(inst: IBladeburner, params: ISuccessChanceParams): number;
getSuccessesNeededForNextLevel(baseSuccessesPerLevel: number): number;
setMaxLevel(baseSuccessesPerLevel: number): void;
toJSON(): any;
}

@ -0,0 +1,4 @@
export interface IActionIdentifier {
name: string;
type: string;
}

@ -0,0 +1,39 @@
import { IActionIdentifier } from "./IActionIdentifier";
import { City } from "./City";
export interface IBladeburner {
numHosp: number;
moneyLost: number;
rank: number;
maxRank: number;
skillPoints: number;
totalSkillPoints: number;
teamSize: number;
teamLost: number;
storedCycles: number;
randomEventCounter: number;
actionTimeToComplete: number;
actionTimeCurrent: number;
action: IActionIdentifier;
cities: any;
city: string;
skills: any;
skillMultipliers: any;
staminaBonus: number;
maxStamina: number;
stamina: number;
contracts: any;
operations: any;
blackops: any;
logging: any;
automateEnabled: boolean;
automateActionHigh: number;
automateThreshHigh: number;
automateActionLow: number;
automateThreshLow: number;
consoleHistory: string[];
consoleLogs: string[];
getCurrentCity(): City;
calculateStaminaPenalty(): number;
}

@ -1,3 +1,4 @@
import { IBladeburner } from "./IBladeburner";
import { BladeburnerConstants } from "./data/Constants"; import { BladeburnerConstants } from "./data/Constants";
import { Action, IActionParams } from "./Action"; import { Action, IActionParams } from "./Action";
import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver"; import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver";
@ -18,7 +19,7 @@ export class Operation extends Action {
} }
// For actions that have teams. To be implemented by subtypes. // For actions that have teams. To be implemented by subtypes.
getTeamSuccessBonus(inst: any): number { getTeamSuccessBonus(inst: IBladeburner): number {
if (this.teamCount && this.teamCount > 0) { if (this.teamCount && this.teamCount > 0) {
this.teamCount = Math.min(this.teamCount, inst.teamSize); this.teamCount = Math.min(this.teamCount, inst.teamSize);
const teamMultiplier = Math.pow(this.teamCount, 0.05); const teamMultiplier = Math.pow(this.teamCount, 0.05);
@ -28,11 +29,11 @@ export class Operation extends Action {
return 1; return 1;
} }
getActionTypeSkillSuccessBonus(inst: any): number { getActionTypeSkillSuccessBonus(inst: IBladeburner): number {
return inst.skillMultipliers.successChanceOperation; return inst.skillMultipliers.successChanceOperation;
} }
getChaosDifficultyBonus(inst: any, params: any): number { getChaosDifficultyBonus(inst: IBladeburner/*, params: ISuccessChanceParams*/): number {
const city = inst.getCurrentCity(); const city = inst.getCurrentCity();
if (city.chaos > BladeburnerConstants.ChaosThreshold) { if (city.chaos > BladeburnerConstants.ChaosThreshold) {
const diff = 1 + (city.chaos - BladeburnerConstants.ChaosThreshold); const diff = 1 + (city.chaos - BladeburnerConstants.ChaosThreshold);
@ -43,13 +44,14 @@ export class Operation extends Action {
return 1; return 1;
} }
static fromJSON(value: any): Operation {
return Generic_fromJSON(Operation, value.data);
}
toJSON(): any { toJSON(): any {
return Generic_toJSON("Operation", this); return Generic_toJSON("Operation", this);
} }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): Operation {
return Generic_fromJSON(Operation, value.data);
}
} }
Reviver.constructors.Operation = Operation; Reviver.constructors.Operation = Operation;

@ -1,4 +1,14 @@
export const ConsoleHelpText: {} = { export const ConsoleHelpText: {
helpList: string[];
automate: string[];
clear: string[];
cls: string[];
help: string[];
log: string[];
skill: string[];
start: string[];
stop: string[];
} = {
helpList: [ helpList: [
"Use 'help [command]' to get more information about a particular Bladeburner console command.", "Use 'help [command]' to get more information about a particular Bladeburner console command.",
"", "",

@ -38,7 +38,7 @@ for (var i = blackops.length-1; i >= 0 ; --i) {
import * as React from "react"; import * as React from "react";
export function BlackOperationsPage(inst: any): React.ReactElement { export function BlackOperationsPage(): React.ReactElement {
// Put Black Operations in sequence of required rank // Put Black Operations in sequence of required rank
const blackops = []; const blackops = [];
for (const name in BlackOperations) { for (const name in BlackOperations) {
@ -55,7 +55,7 @@ export function BlackOperationsPage(inst: any): React.ReactElement {
Black Operations (Black Ops) are special, one-time covert operations. Each Black Op must be unlocked successively by completing the one before it.<br /><br /> Black Operations (Black Ops) are special, one-time covert operations. Each Black Op must be unlocked successively by completing the one before it.<br /><br />
<b>Your ultimate goal to climb through the ranks of Bladeburners is to complete all of the Black Ops.</b><br /><br /> <b>Your ultimate goal to climb through the ranks of Bladeburners is to complete all of the Black Ops.</b><br /><br />
Like normal operations, you may use a team for Black Ops. Failing a black op will incur heavy HP and rank losses.</p> Like normal operations, you may use a team for Black Ops. Failing a black op will incur heavy HP and rank losses.</p>
{blackops.map( op => <div className="bladeburner-action"> {blackops.map(() => <div className="bladeburner-action">
</div>, </div>,
)} )}
</div>) </div>)

@ -41,7 +41,7 @@ export class CoinFlip extends Game<IProps, IState> {
this.updateInvestment = this.updateInvestment.bind(this); this.updateInvestment = this.updateInvestment.bind(this);
} }
updateInvestment(e: React.FormEvent<HTMLInputElement>) { updateInvestment(e: React.FormEvent<HTMLInputElement>): void {
let investment: number = parseInt(e.currentTarget.value); let investment: number = parseInt(e.currentTarget.value);
if (isNaN(investment)) { if (isNaN(investment)) {
investment = minPlay; investment = minPlay;
@ -55,7 +55,7 @@ export class CoinFlip extends Game<IProps, IState> {
this.setState({investment: investment}); this.setState({investment: investment});
} }
play(guess: string) { play(guess: string): void {
if(this.reachedLimit(this.props.p)) return; if(this.reachedLimit(this.props.p)) return;
const v = BadRNG.random(); const v = BadRNG.random();
let letter: string; let letter: string;
@ -80,7 +80,7 @@ export class CoinFlip extends Game<IProps, IState> {
} }
render() { render(): React.ReactNode {
return <> return <>
<pre> <pre>
++<br /> ++<br />

@ -18,7 +18,7 @@ class RNG0 implements RNG {
this.reset(); this.reset();
} }
step() { step(): void {
this.x = (this.a*this.x+this.c) % this.m; this.x = (this.a*this.x+this.c) % this.m;
} }
@ -27,7 +27,7 @@ class RNG0 implements RNG {
return this.x/this.m; return this.x/this.m;
} }
reset() { reset(): void {
this.x = (new Date()).getTime() % this.m; this.x = (new Date()).getTime() % this.m;
} }
} }
@ -51,7 +51,7 @@ export class WHRNG implements RNG {
this.s3 = v; this.s3 = v;
} }
step() { step(): void {
this.s1 = (171 * this.s1) % 30269; this.s1 = (171 * this.s1) % 30269;
this.s2 = (172 * this.s2) % 30307; this.s2 = (172 * this.s2) % 30307;
this.s3 = (170 * this.s3) % 30323; this.s3 = (170 * this.s3) % 30323;

@ -28,10 +28,6 @@ function isRed(n: number): boolean {
21, 23, 25, 27, 30, 32, 34, 36].includes(n); 21, 23, 25, 27, 30, 32, 34, 36].includes(n);
} }
function isBlack(n: number): boolean {
return !isRed(n);
}
type Strategy = { type Strategy = {
match: (n: number) => boolean; match: (n: number) => boolean;
payout: number; payout: number;
@ -140,7 +136,7 @@ export class Roulette extends Game<IProps, IState> {
lock: true, lock: true,
strategy: { strategy: {
payout: 0, payout: 0,
match: (n: number): boolean => { return false }, match: (): boolean => { return false },
}, },
} }
@ -150,21 +146,21 @@ export class Roulette extends Game<IProps, IState> {
} }
componentDidMount() { componentDidMount(): void {
this.interval = setInterval(this.step, 50); this.interval = setInterval(this.step, 50);
} }
step() { step(): void {
if (!this.state.lock) { if (!this.state.lock) {
this.setState({n: Math.floor(Math.random()*37)}); this.setState({n: Math.floor(Math.random()*37)});
} }
} }
componentWillUnmount() { componentWillUnmount(): void {
clearInterval(this.interval); clearInterval(this.interval);
} }
updateInvestment(e: React.FormEvent<HTMLInputElement>) { updateInvestment(e: React.FormEvent<HTMLInputElement>): void {
let investment: number = parseInt(e.currentTarget.value); let investment: number = parseInt(e.currentTarget.value);
if (isNaN(investment)) { if (isNaN(investment)) {
investment = minPlay; investment = minPlay;
@ -178,13 +174,13 @@ export class Roulette extends Game<IProps, IState> {
this.setState({investment: investment}); this.setState({investment: investment});
} }
currentNumber() { currentNumber(): string {
if (this.state.n === 0) return '0'; if (this.state.n === 0) return '0';
const color = isRed(this.state.n) ? 'R' : 'B'; const color = isRed(this.state.n) ? 'R' : 'B';
return `${this.state.n}${color}`; return `${this.state.n}${color}`;
} }
play(s: Strategy) { play(s: Strategy): void {
if(this.reachedLimit(this.props.p)) return; if(this.reachedLimit(this.props.p)) return;
this.setState({ this.setState({
canPlay: false, canPlay: false,
@ -223,7 +219,7 @@ export class Roulette extends Game<IProps, IState> {
} }
render() { render(): React.ReactNode {
return <> return <>
<h1>{this.currentNumber()}</h1> <h1>{this.currentNumber()}</h1>
<input type="number" className="text-input" onChange={this.updateInvestment} placeholder={"Amount to play"} value={this.state.investment} disabled={!this.state.canPlay} /> <input type="number" className="text-input" onChange={this.updateInvestment} placeholder={"Amount to play"} value={this.state.investment} disabled={!this.state.canPlay} />

@ -86,11 +86,11 @@ export class SlotMachine extends Game<IProps, IState> {
this.updateInvestment = this.updateInvestment.bind(this); this.updateInvestment = this.updateInvestment.bind(this);
} }
componentDidMount() { componentDidMount(): void {
this.interval = setInterval(this.step, 50); this.interval = setInterval(this.step, 50);
} }
step() { step(): void {
let stoppedOne = false; let stoppedOne = false;
const index = this.state.index.slice(); const index = this.state.index.slice();
for(const i in index) { for(const i in index) {
@ -106,7 +106,7 @@ export class SlotMachine extends Game<IProps, IState> {
} }
} }
componentWillUnmount() { componentWillUnmount(): void {
clearInterval(this.interval); clearInterval(this.interval);
} }
@ -118,7 +118,7 @@ export class SlotMachine extends Game<IProps, IState> {
]; ];
} }
play() { play(): void {
if(this.reachedLimit(this.props.p)) return; if(this.reachedLimit(this.props.p)) return;
this.setState({status: 'playing'}); this.setState({status: 'playing'});
this.win(this.props.p, -this.state.investment); this.win(this.props.p, -this.state.investment);
@ -127,7 +127,7 @@ export class SlotMachine extends Game<IProps, IState> {
setTimeout(this.lock, this.rng.random()*2000+1000); setTimeout(this.lock, this.rng.random()*2000+1000);
} }
lock() { lock(): void {
this.setState({ this.setState({
locks: [ locks: [
Math.floor(this.rng.random()*symbols.length), Math.floor(this.rng.random()*symbols.length),
@ -139,7 +139,7 @@ export class SlotMachine extends Game<IProps, IState> {
}) })
} }
checkWinnings() { checkWinnings(): void {
const t = this.getTable(); const t = this.getTable();
const getPaylineData = function(payline: number[][]): string[] { const getPaylineData = function(payline: number[][]): string[] {
const data = []; const data = [];
@ -176,14 +176,14 @@ export class SlotMachine extends Game<IProps, IState> {
if(this.reachedLimit(this.props.p)) return; if(this.reachedLimit(this.props.p)) return;
} }
unlock() { unlock(): void {
this.setState({ this.setState({
locks: [-1, -1, -1, -1, -1], locks: [-1, -1, -1, -1, -1],
canPlay: false, canPlay: false,
}) })
} }
updateInvestment(e: React.FormEvent<HTMLInputElement>) { updateInvestment(e: React.FormEvent<HTMLInputElement>): void {
let investment: number = parseInt(e.currentTarget.value); let investment: number = parseInt(e.currentTarget.value);
if (isNaN(investment)) { if (isNaN(investment)) {
investment = minPlay; investment = minPlay;
@ -197,7 +197,7 @@ export class SlotMachine extends Game<IProps, IState> {
this.setState({investment: investment}); this.setState({investment: investment});
} }
render() { render(): React.ReactNode {
const t = this.getTable(); const t = this.getTable();
return <> return <>
<pre> <pre>

@ -90,7 +90,7 @@ function cinematicTextEnd() {
var mainMenu = document.getElementById("mainmenu-container"); var mainMenu = document.getElementById("mainmenu-container");
container.appendChild(createElement("br")); container.appendChild(createElement("br"));
return new Promise (function(resolve, reject) { return new Promise (function(resolve) {
container.appendChild(createElement("a", { container.appendChild(createElement("a", {
class:"a-link-button", innerText:"Continue...", class:"a-link-button", innerText:"Continue...",
clickListener:()=>{ clickListener:()=>{

@ -15,7 +15,7 @@ import { HacknetServer } from "./Hacknet/HacknetServer";
import { getRandomInt } from "../utils/helpers/getRandomInt"; import { getRandomInt } from "../utils/helpers/getRandomInt";
export function generateRandomContract() { export function generateRandomContract(): void {
// First select a random problem type // First select a random problem type
const problemType = getRandomProblemType(); const problemType = getRandomProblemType();
@ -31,7 +31,7 @@ export function generateRandomContract() {
randServer.addContract(contract); randServer.addContract(contract);
} }
export function generateRandomContractOnHome() { export function generateRandomContractOnHome(): void {
// First select a random problem type // First select a random problem type
const problemType = getRandomProblemType(); const problemType = getRandomProblemType();
@ -53,7 +53,7 @@ export interface IGenerateContractParams {
fn?: string; fn?: string;
} }
export function generateContract(params: IGenerateContractParams) { export function generateContract(params: IGenerateContractParams): void {
// Problem Type // Problem Type
let problemType; let problemType;
const problemTypes = Object.keys(CodingContractTypes); const problemTypes = Object.keys(CodingContractTypes);
@ -117,7 +117,7 @@ function sanitizeRewardType(rewardType: CodingContractRewardType): CodingContrac
return type; return type;
} }
function getRandomProblemType() { function getRandomProblemType(): string {
const problemTypes = Object.keys(CodingContractTypes); const problemTypes = Object.keys(CodingContractTypes);
const randIndex = getRandomInt(0, problemTypes.length - 1); const randIndex = getRandomInt(0, problemTypes.length - 1);

@ -108,12 +108,6 @@ export interface ICodingContractReward {
* The player receives a reward if the problem is solved correctly * The player receives a reward if the problem is solved correctly
*/ */
export class CodingContract { export class CodingContract {
/**
* Initiatizes a CodingContract from a JSON save state.
*/
static fromJSON(value: any): CodingContract {
return Generic_fromJSON(CodingContract, value.data);
}
/* Relevant data for the contract's problem */ /* Relevant data for the contract's problem */
data: any; data: any;
@ -178,7 +172,7 @@ export class CodingContract {
*/ */
async prompt(): Promise<CodingContractResult> { async prompt(): Promise<CodingContractResult> {
// tslint:disable-next-line // tslint:disable-next-line
return new Promise<CodingContractResult>((resolve: Function, reject: Function) => { return new Promise<CodingContractResult>((resolve) => {
const contractType: CodingContractType = CodingContractTypes[this.type]; const contractType: CodingContractType = CodingContractTypes[this.type];
const popupId = `coding-contract-prompt-popup-${this.fn}`; const popupId = `coding-contract-prompt-popup-${this.fn}`;
const title: HTMLElement = createElement("h1", { const title: HTMLElement = createElement("h1", {
@ -190,10 +184,16 @@ export class CodingContract {
"after which the contract will self-destruct.<br><br>", "after which the contract will self-destruct.<br><br>",
`${contractType.desc(this.data).replace(/\n/g, "<br>")}`].join(" "), `${contractType.desc(this.data).replace(/\n/g, "<br>")}`].join(" "),
}); });
let answerInput: HTMLInputElement;
let solveBtn: HTMLElement; let solveBtn: HTMLElement;
let cancelBtn: HTMLElement; const cancelBtn = createElement("a", {
answerInput = createElement("input", { class: "a-link-button",
clickListener: () => {
resolve(CodingContractResult.Cancelled);
removeElementById(popupId);
},
innerText: "Cancel",
});
const answerInput = createElement("input", {
onkeydown: (e: any) => { onkeydown: (e: any) => {
if (e.keyCode === KEY.ENTER && answerInput.value !== "") { if (e.keyCode === KEY.ENTER && answerInput.value !== "") {
e.preventDefault(); e.preventDefault();
@ -219,14 +219,6 @@ export class CodingContract {
}, },
innerText: "Solve", innerText: "Solve",
}); });
cancelBtn = createElement("a", {
class: "a-link-button",
clickListener: () => {
resolve(CodingContractResult.Cancelled);
removeElementById(popupId);
},
innerText: "Cancel",
});
const lineBreak: HTMLElement = createElement("br"); const lineBreak: HTMLElement = createElement("br");
createPopup(popupId, [title, lineBreak, txt, lineBreak, lineBreak, answerInput, solveBtn, cancelBtn]); createPopup(popupId, [title, lineBreak, txt, lineBreak, lineBreak, answerInput, solveBtn, cancelBtn]);
answerInput.focus(); answerInput.focus();
@ -239,6 +231,14 @@ export class CodingContract {
toJSON(): any { toJSON(): any {
return Generic_toJSON("CodingContract", this); return Generic_toJSON("CodingContract", this);
} }
/**
* Initiatizes a CodingContract from a JSON save state.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static fromJSON(value: any): CodingContract {
return Generic_fromJSON(CodingContract, value.data);
}
} }
Reviver.constructors.CodingContract = CodingContract; Reviver.constructors.CodingContract = CodingContract;

@ -6,7 +6,7 @@ import { Reviver } from "../../utils/JSONReviver";
export let Companies: IMap<Company> = {}; export let Companies: IMap<Company> = {};
function addCompany(params: IConstructorParams) { function addCompany(params: IConstructorParams): void {
if (Companies[params.name] != null) { if (Companies[params.name] != null) {
console.warn(`Duplicate Company Position being defined: ${params.name}`); console.warn(`Duplicate Company Position being defined: ${params.name}`);
} }
@ -15,7 +15,7 @@ function addCompany(params: IConstructorParams) {
// Used to initialize new Company objects for the Companies map // Used to initialize new Company objects for the Companies map
// Called when creating new game or after a prestige/reset // Called when creating new game or after a prestige/reset
export function initCompanies() { export function initCompanies(): void {
// Save Old Company data for 'favor' // Save Old Company data for 'favor'
const oldCompanies = Companies; const oldCompanies = Companies;
@ -40,11 +40,11 @@ export function initCompanies() {
} }
// Used to load Companies map from a save // Used to load Companies map from a save
export function loadCompanies(saveString: string) { export function loadCompanies(saveString: string): void {
Companies = JSON.parse(saveString, Reviver); Companies = JSON.parse(saveString, Reviver);
} }
// Utility function to check if a string is valid company name // Utility function to check if a string is valid company name
export function companyExists(name: string) { export function companyExists(name: string): boolean {
return Companies.hasOwnProperty(name); return Companies.hasOwnProperty(name);
} }

@ -25,12 +25,6 @@ const DefaultConstructorParams: IConstructorParams = {
} }
export class Company { export class Company {
/**
* Initiatizes a Company from a JSON save state.
*/
static fromJSON(value: any): Company {
return Generic_fromJSON(Company, value.data);
}
/** /**
* Company name * Company name
@ -170,6 +164,14 @@ export class Company {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Company", this); return 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: any): Company {
return Generic_fromJSON(Company, value.data);
}
} }
Reviver.constructors.Company = Company; Reviver.constructors.Company = Company;

@ -5,7 +5,7 @@ import { IMap } from "../types";
export const CompanyPositions: IMap<CompanyPosition> = {}; export const CompanyPositions: IMap<CompanyPosition> = {};
function addCompanyPosition(params: IConstructorParams) { function addCompanyPosition(params: IConstructorParams): void {
if (CompanyPositions[params.name] != null) { if (CompanyPositions[params.name] != null) {
console.warn(`Duplicate Company Position being defined: ${params.name}`); console.warn(`Duplicate Company Position being defined: ${params.name}`);
} }

@ -5,7 +5,6 @@ import { CorporationUpgrades } from "./data/Corporation
import { EmployeePositions } from "./EmployeePositions"; import { EmployeePositions } from "./EmployeePositions";
import { Industries, import { Industries,
IndustryStartingCosts, IndustryStartingCosts,
IndustryDescriptions,
IndustryResearchTrees } from "./IndustryData"; IndustryResearchTrees } from "./IndustryData";
import { IndustryUpgrades } from "./IndustryUpgrades"; import { IndustryUpgrades } from "./IndustryUpgrades";
import { Material } from "./Material"; import { Material } from "./Material";
@ -15,11 +14,8 @@ import { ResearchMap } from "./ResearchMap";
import { Warehouse } from "./Warehouse"; import { Warehouse } from "./Warehouse";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { CONSTANTS } from "../Constants";
import { Factions } from "../Faction/Factions";
import { showLiterature } from "../Literature/LiteratureHelpers"; import { showLiterature } from "../Literature/LiteratureHelpers";
import { LiteratureNames } from "../Literature/data/LiteratureNames"; import { LiteratureNames } from "../Literature/data/LiteratureNames";
import { createCityMap } from "../Locations/Cities";
import { CityName } from "../Locations/data/CityNames"; import { CityName } from "../Locations/data/CityNames";
import { Player } from "../Player"; import { Player } from "../Player";
@ -29,7 +25,6 @@ import { Page, routing } from "../ui/navigationTr
import { calculateEffectWithFactors } from "../utils/calculateEffectWithFactors"; import { calculateEffectWithFactors } from "../utils/calculateEffectWithFactors";
import { dialogBoxCreate } from "../../utils/DialogBox"; import { dialogBoxCreate } from "../../utils/DialogBox";
import { clearSelector } from "../../utils/uiHelpers/clearSelector";
import { Reviver, import { Reviver,
Generic_toJSON, Generic_toJSON,
Generic_fromJSON } from "../../utils/JSONReviver"; Generic_fromJSON } from "../../utils/JSONReviver";
@ -99,7 +94,6 @@ export const BaseMaxProducts = 3; // Initial value for maximum
let researchTreeBoxOpened = false; let researchTreeBoxOpened = false;
let researchTreeBox = null; let researchTreeBox = null;
$(document).mousedown(function(event) { $(document).mousedown(function(event) {
const boxId = "corporation-research-popup-box";
const contentId = "corporation-research-popup-box-content"; const contentId = "corporation-research-popup-box-content";
if (researchTreeBoxOpened) { if (researchTreeBoxOpened) {
if ( $(event.target).closest("#" + contentId).get(0) == null ) { if ( $(event.target).closest("#" + contentId).get(0) == null ) {
@ -111,7 +105,6 @@ $(document).mousedown(function(event) {
} }
}); });
var empManualAssignmentModeActive = false;
function Industry(params={}) { function Industry(params={}) {
this.offices = { //Maps locations to offices. 0 if no office at that location this.offices = { //Maps locations to offices. 0 if no office at that location
[CityName.Aevum]: 0, [CityName.Aevum]: 0,
@ -441,8 +434,7 @@ Industry.prototype.calculateProductionFactors = function() {
continue; continue;
} }
var materials = warehouse.materials, var materials = warehouse.materials;
office = this.offices[city];
var cityMult = Math.pow(0.002 * materials.RealEstate.qty+1, this.reFac) * var cityMult = Math.pow(0.002 * materials.RealEstate.qty+1, this.reFac) *
Math.pow(0.002 * materials.Hardware.qty+1, this.hwFac) * Math.pow(0.002 * materials.Hardware.qty+1, this.hwFac) *
@ -535,7 +527,7 @@ Industry.prototype.process = function(marketCycles=1, state, company) {
} }
// Process change in demand and competition for this industry's materials // Process change in demand and competition for this industry's materials
Industry.prototype.processMaterialMarket = function(marketCycles=1) { Industry.prototype.processMaterialMarket = function() {
//References to prodMats and reqMats //References to prodMats and reqMats
var reqMats = this.reqMats, prodMats = this.prodMats; var reqMats = this.reqMats, prodMats = this.prodMats;
@ -589,7 +581,7 @@ Industry.prototype.processProductMarket = function(marketCycles=1) {
//Process production, purchase, and import/export of materials //Process production, purchase, and import/export of materials
Industry.prototype.processMaterials = function(marketCycles=1, company) { Industry.prototype.processMaterials = function(marketCycles=1, company) {
var revenue = 0, expenses = 0, industry = this; var revenue = 0, expenses = 0;
this.calculateProductionFactors(); this.calculateProductionFactors();
//At the start of the export state, set the imports of everything to 0 //At the start of the export state, set the imports of everything to 0
@ -642,7 +634,7 @@ Industry.prototype.processMaterials = function(marketCycles=1, company) {
mat.qty += buyAmt; mat.qty += buyAmt;
expenses += (buyAmt * mat.bCost); expenses += (buyAmt * mat.bCost);
} }
})(matName, industry); })(matName, this);
this.updateWarehouseSizeUsed(warehouse); this.updateWarehouseSizeUsed(warehouse);
} }
} //End process purchase of materials } //End process purchase of materials
@ -1003,7 +995,7 @@ Industry.prototype.processProduct = function(marketCycles=1, product, corporatio
if (warehouse instanceof Warehouse) { if (warehouse instanceof Warehouse) {
switch(this.state) { switch(this.state) {
case "PRODUCTION": case "PRODUCTION": {
//Calculate the maximum production of this material based //Calculate the maximum production of this material based
//on the office's productivity //on the office's productivity
var maxProd = this.getOfficeProductivity(office, {forProduct:true}) var maxProd = this.getOfficeProductivity(office, {forProduct:true})
@ -1065,8 +1057,8 @@ Industry.prototype.processProduct = function(marketCycles=1, product, corporatio
//Keep track of production Per second //Keep track of production Per second
product.data[city][1] = prod * producableFrac / (SecsPerMarketCycle * marketCycles); product.data[city][1] = prod * producableFrac / (SecsPerMarketCycle * marketCycles);
break; break;
}
case "SALE": case "SALE": {
//Process sale of Products //Process sale of Products
product.pCost = 0; //Estimated production cost product.pCost = 0; //Estimated production cost
for (var reqMatName in product.reqMats) { for (var reqMatName in product.reqMats) {
@ -1174,7 +1166,7 @@ Industry.prototype.processProduct = function(marketCycles=1, product, corporatio
product.data[city][2] = 0; //data[2] is sell property product.data[city][2] = 0; //data[2] is sell property
} }
break; break;
}
case "START": case "START":
case "PURCHASE": case "PURCHASE":
case "EXPORT": case "EXPORT":
@ -1199,10 +1191,9 @@ Industry.prototype.discontinueProduct = function(product) {
} }
Industry.prototype.upgrade = function(upgrade, refs) { Industry.prototype.upgrade = function(upgrade, refs) {
var corporation = refs.corporation, division = refs.division, var corporation = refs.corporation;
office = refs.office; var office = refs.office;
var upgN = upgrade[0], basePrice = upgrade[1], priceMult = upgrade[2], var upgN = upgrade[0];
upgradeBenefit = upgrade[3];
while (this.upgrades.length <= upgN) {this.upgrades.push(0);} while (this.upgrades.length <= upgN) {this.upgrades.push(0);}
++this.upgrades[upgN]; ++this.upgrades[upgN];
@ -1374,9 +1365,6 @@ Industry.prototype.createResearchBox = function() {
}, },
} }
// Construct the tree with Treant
const treantTree = new Treant(markup);
// Add Event Listeners for all Nodes // Add Event Listeners for all Nodes
const allResearch = researchTree.getAllNodes(); const allResearch = researchTree.getAllNodes();
for (let i = 0; i < allResearch.length; ++i) { for (let i = 0; i < allResearch.length; ++i) {
@ -1658,7 +1646,7 @@ OfficeSpace.prototype.atCapacity = function() {
} }
OfficeSpace.prototype.process = function(marketCycles=1, parentRefs) { OfficeSpace.prototype.process = function(marketCycles=1, parentRefs) {
var corporation = parentRefs.corporation, industry = parentRefs.industry; var industry = parentRefs.industry;
// HRBuddy AutoRecruitment and training // HRBuddy AutoRecruitment and training
if (industry.hasResearch("HRBuddy-Recruitment") && !this.atCapacity()) { if (industry.hasResearch("HRBuddy-Recruitment") && !this.atCapacity()) {
@ -1741,7 +1729,6 @@ OfficeSpace.prototype.calculateEmployeeProductivity = function(parentRefs) {
//Takes care of UI as well //Takes care of UI as well
OfficeSpace.prototype.findEmployees = function(parentRefs) { OfficeSpace.prototype.findEmployees = function(parentRefs) {
var company = parentRefs.corporation, division = parentRefs.industry;
if (this.atCapacity()) { return; } if (this.atCapacity()) { return; }
if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null) {return;} if (document.getElementById("cmpy-mgmt-hire-employee-popup") != null) {return;}
@ -1825,7 +1812,7 @@ OfficeSpace.prototype.findEmployees = function(parentRefs) {
} }
OfficeSpace.prototype.hireEmployee = function(employee, parentRefs) { OfficeSpace.prototype.hireEmployee = function(employee, parentRefs) {
var company = parentRefs.corporation, division = parentRefs.industry; var company = parentRefs.corporation;
var yesBtn = yesNoTxtInpBoxGetYesButton(), var yesBtn = yesNoTxtInpBoxGetYesButton(),
noBtn = yesNoTxtInpBoxGetNoButton(); noBtn = yesNoTxtInpBoxGetNoButton();
yesBtn.innerHTML = "Hire"; yesBtn.innerHTML = "Hire";
@ -1958,15 +1945,14 @@ Corporation.prototype.storeCycles = function(numCycles=1) {
} }
Corporation.prototype.process = function() { Corporation.prototype.process = function() {
var corp = this;
if (this.storedCycles >= CyclesPerIndustryStateCycle) { if (this.storedCycles >= CyclesPerIndustryStateCycle) {
const state = this.getState(); const state = this.getState();
const marketCycles = 1; const marketCycles = 1;
const gameCycles = (marketCycles * CyclesPerIndustryStateCycle); const gameCycles = (marketCycles * CyclesPerIndustryStateCycle);
this.storedCycles -= gameCycles; this.storedCycles -= gameCycles;
this.divisions.forEach(function(ind) { this.divisions.forEach((ind) => {
ind.process(marketCycles, state, corp); ind.process(marketCycles, state, this);
}); });
// Process cooldowns // Process cooldowns
@ -2208,7 +2194,6 @@ Corporation.prototype.calculateShareSale = function(numShares) {
Corporation.prototype.convertCooldownToString = function(cd) { Corporation.prototype.convertCooldownToString = function(cd) {
// The cooldown value is based on game cycles. Convert to a simple string // The cooldown value is based on game cycles. Convert to a simple string
const CyclesPerSecond = 1000 / CONSTANTS.MilliPerCycle;
const seconds = cd / 5; const seconds = cd / 5;
const SecondsPerMinute = 60; const SecondsPerMinute = 60;

@ -6,17 +6,11 @@ import { Generic_fromJSON,
export const AllCorporationStates: string[] = ["START", "PURCHASE", "PRODUCTION", "SALE", "EXPORT"]; export const AllCorporationStates: string[] = ["START", "PURCHASE", "PRODUCTION", "SALE", "EXPORT"];
export class CorporationState { export class CorporationState {
// Initiatizes a CorporationState object from a JSON save state.
static fromJSON(value: any): CorporationState {
return Generic_fromJSON(CorporationState, value.data);
}
// Number representing what state the Corporation is in. The number // Number representing what state the Corporation is in. The number
// is an index for the array that holds all Corporation States // is an index for the array that holds all Corporation States
state = 0; state = 0;
constructor() {}
// Get the name of the current state // Get the name of the current state
// NOTE: This does NOT return the number stored in the 'state' property, // 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. // which is just an index for the array of all possible Corporation States.
@ -40,6 +34,12 @@ export class CorporationState {
toJSON(): any { toJSON(): any {
return Generic_toJSON("CorporationState", this); return 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: any): CorporationState {
return Generic_fromJSON(CorporationState, value.data);
}
} }
Reviver.constructors.CorporationState = CorporationState; Reviver.constructors.CorporationState = CorporationState;

@ -4,8 +4,6 @@ import { getBaseResearchTreeCopy,
import { numeralWrapper } from "../ui/numeralFormat"; import { numeralWrapper } from "../ui/numeralFormat";
import { Reviver } from "../../utils/JSONReviver";
interface IIndustryMap<T> { interface IIndustryMap<T> {
Energy: T; Energy: T;
Utilities: T; Utilities: T;
@ -124,7 +122,7 @@ export const IndustryResearchTrees: IIndustryMap<ResearchTree> = {
RealEstate: getProductIndustryResearchTreeCopy(), RealEstate: getProductIndustryResearchTreeCopy(),
} }
export function resetIndustryResearchTrees() { export function resetIndustryResearchTrees(): void {
IndustryResearchTrees.Energy = getBaseResearchTreeCopy(); IndustryResearchTrees.Energy = getBaseResearchTreeCopy();
IndustryResearchTrees.Utilities = getBaseResearchTreeCopy(); IndustryResearchTrees.Utilities = getBaseResearchTreeCopy();
IndustryResearchTrees.Agriculture = getBaseResearchTreeCopy(); IndustryResearchTrees.Agriculture = getBaseResearchTreeCopy();

@ -7,10 +7,6 @@ interface IConstructorParams {
} }
export class Material { export class Material {
// Initiatizes a Material object from a JSON save state.
static fromJSON(value: any): Material {
return Generic_fromJSON(Material, value.data);
}
// Name of material // Name of material
name = "InitName"; name = "InitName";
@ -192,6 +188,12 @@ export class Material {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Material", this); return 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: any): Material {
return Generic_fromJSON(Material, value.data);
}
} }
Reviver.constructors.Material = Material; Reviver.constructors.Material = Material;

@ -42,10 +42,6 @@ interface IIndustry {
export class Product { export class Product {
// Initiatizes a Product object from a JSON save state.
static fromJSON(value: any): Product {
return Generic_fromJSON(Product, value.data);
}
// Product name // Product name
name = ""; name = "";
@ -196,7 +192,7 @@ export class Product {
//Calculate the product's required materials //Calculate the product's required materials
//For now, just set it to be the same as the requirements to make materials //For now, just set it to be the same as the requirements to make materials
for (var matName in industry.reqMats) { for (const matName in industry.reqMats) {
if (industry.reqMats.hasOwnProperty(matName)) { if (industry.reqMats.hasOwnProperty(matName)) {
this.reqMats[matName] = industry.reqMats[matName]; this.reqMats[matName] = industry.reqMats[matName];
} }
@ -205,7 +201,7 @@ export class Product {
//Calculate the product's size //Calculate the product's size
//For now, just set it to be the same size as the requirements to make materials //For now, just set it to be the same size as the requirements to make materials
this.siz = 0; this.siz = 0;
for (var matName in industry.reqMats) { for (const matName in industry.reqMats) {
this.siz += MaterialSizes[matName] * industry.reqMats[matName]; this.siz += MaterialSizes[matName] * industry.reqMats[matName];
} }
@ -240,6 +236,12 @@ export class Product {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Product", this); return 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: any): Product {
return Generic_fromJSON(Product, value.data);
}
} }
Reviver.constructors.Product = Product; Reviver.constructors.Product = Product;

@ -10,7 +10,7 @@ export interface IProductRatingWeight {
Reliability?: number; Reliability?: number;
} }
export const ProductRatingWeights: IMap<object> = { export const ProductRatingWeights: IMap<any> = {
[Industries.Food]: { [Industries.Food]: {
Quality: 0.7, Quality: 0.7,
Durability: 0.1, Durability: 0.1,

@ -7,7 +7,7 @@ import { IMap } from "../types";
export const ResearchMap: IMap<Research> = {}; export const ResearchMap: IMap<Research> = {};
function addResearch(p: IConstructorParams) { function addResearch(p: IConstructorParams): void {
if (ResearchMap[p.name] != null) { if (ResearchMap[p.name] != null) {
console.warn(`Duplicate Research being defined: ${p.name}`); console.warn(`Duplicate Research being defined: ${p.name}`);
} }

@ -56,14 +56,14 @@ export class Node {
} }
} }
addChild(n: Node) { addChild(n: Node): void {
this.children.push(n); this.children.push(n);
n.parent = this; n.parent = this;
} }
// Return an object that describes a TreantJS-compatible markup/config for this Node // Return an object that describes a TreantJS-compatible markup/config for this Node
// See: http://fperucic.github.io/treant-js/ // See: http://fperucic.github.io/treant-js/
createTreantMarkup(): object { createTreantMarkup(): any {
const childrenArray = []; const childrenArray = [];
for (let i = 0; i < this.children.length; ++i) { for (let i = 0; i < this.children.length; ++i) {
childrenArray.push(this.children[i].createTreantMarkup()); childrenArray.push(this.children[i].createTreantMarkup());
@ -109,7 +109,7 @@ export class Node {
return null; return null;
} }
setParent(n: Node) { setParent(n: Node): void {
this.parent = n; this.parent = n;
} }
} }
@ -124,11 +124,9 @@ export class ResearchTree {
// Root Node // Root Node
root: Node | null = null; root: Node | null = null;
constructor() {}
// Return an object that contains a Tree markup for TreantJS (using the JSON approach) // Return an object that contains a Tree markup for TreantJS (using the JSON approach)
// See: http://fperucic.github.io/treant-js/ // See: http://fperucic.github.io/treant-js/
createTreantMarkup(): object { createTreantMarkup(): any {
if (this.root == null) { return {}; } if (this.root == null) { return {}; }
const treeMarkup = this.root.createTreantMarkup(); const treeMarkup = this.root.createTreantMarkup();

@ -19,10 +19,6 @@ interface IConstructorParams {
} }
export class Warehouse { export class Warehouse {
// Initiatizes a Warehouse object from a JSON save state.
static fromJSON(value: any): Warehouse {
return Generic_fromJSON(Warehouse, value.data);
}
// Text that describes how the space in this Warehouse is being used // Text that describes how the space in this Warehouse is being used
// Used to create a tooltip in the UI // Used to create a tooltip in the UI
@ -79,7 +75,7 @@ export class Warehouse {
} }
// Re-calculate how much space is being used by this Warehouse // Re-calculate how much space is being used by this Warehouse
updateMaterialSizeUsed() { updateMaterialSizeUsed(): void {
this.sizeUsed = 0; this.sizeUsed = 0;
this.breakdown = ""; this.breakdown = "";
for (const matName in this.materials) { for (const matName in this.materials) {
@ -96,7 +92,7 @@ export class Warehouse {
} }
} }
updateSize(corporation: IParent, industry: IParent) { updateSize(corporation: IParent, industry: IParent): void {
try { try {
this.size = (this.level * 100) this.size = (this.level * 100)
* corporation.getStorageMultiplier() * corporation.getStorageMultiplier()
@ -110,6 +106,12 @@ export class Warehouse {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Warehouse", this); return 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: any): Warehouse {
return Generic_fromJSON(Warehouse, value.data);
}
} }
Reviver.constructors.Warehouse = Warehouse; Reviver.constructors.Warehouse = Warehouse;

@ -17,6 +17,4 @@ export class BaseReactComponent extends Component {
routing() { routing() {
return this.props.routing; return this.props.routing;
} }
render() {}
} }

@ -16,7 +16,7 @@ import { Corporation,
import { Industries, import { Industries,
IndustryStartingCosts, IndustryStartingCosts,
IndustryDescriptions, IndustryDescriptions,
IndustryResearchTrees } from "../IndustryData"; } from "../IndustryData";
import { MaterialSizes } from "../MaterialSizes"; import { MaterialSizes } from "../MaterialSizes";
@ -679,8 +679,6 @@ export class CorporationEventHandler {
// Create a popup that lets the player use the Market TA research for Materials // Create a popup that lets the player use the Market TA research for Materials
createMaterialMarketTaPopup(mat, industry) { createMaterialMarketTaPopup(mat, industry) {
const corp = this.corp;
const popupId = "cmpy-mgmt-marketta-popup"; const popupId = "cmpy-mgmt-marketta-popup";
const markupLimit = mat.getMarkupLimit(); const markupLimit = mat.getMarkupLimit();
const ta1 = createElement("p", { const ta1 = createElement("p", {
@ -964,8 +962,6 @@ export class CorporationEventHandler {
// Create a popup that lets the player use the Market TA research for Products // Create a popup that lets the player use the Market TA research for Products
createProductMarketTaPopup(product, industry) { createProductMarketTaPopup(product, industry) {
const corp = this.corp;
const popupId = "cmpy-mgmt-marketta-popup"; const popupId = "cmpy-mgmt-marketta-popup";
const markupLimit = product.rat / product.mku; const markupLimit = product.rat / product.mku;
const ta1 = createElement("p", { const ta1 = createElement("p", {
@ -1515,8 +1511,6 @@ export class CorporationEventHandler {
} else { } else {
const stockSaleResults = this.corp.calculateShareSale(numShares); const stockSaleResults = this.corp.calculateShareSale(numShares);
const profit = stockSaleResults[0]; const profit = stockSaleResults[0];
const newSharePrice = stockSaleResults[1];
const newSharesUntilUpdate = stockSaleResults[2];
profitIndicator.innerText = "Sell " + numShares + " shares for a total of " + profitIndicator.innerText = "Sell " + numShares + " shares for a total of " +
numeralWrapper.format(profit, '$0.000a'); numeralWrapper.format(profit, '$0.000a');
} }

@ -4,8 +4,6 @@
import React from "react"; import React from "react";
import { BaseReactComponent } from "./BaseReactComponent"; import { BaseReactComponent } from "./BaseReactComponent";
import { overviewPage } from "./Routing";
function HeaderTab(props) { function HeaderTab(props) {
let className = "cmpy-mgmt-header-tab"; let className = "cmpy-mgmt-header-tab";
if (props.current) { if (props.current) {

@ -62,7 +62,6 @@ export class IndustryOffice extends BaseReactComponent {
// Calculate how many NEW emplyoees we need to account for // Calculate how many NEW emplyoees we need to account for
const currentNumEmployees = office.employees.length; const currentNumEmployees = office.employees.length;
const newEmployees = currentNumEmployees - this.state.numEmployees;
// Record the number of employees in each position, for NEW employees only // Record the number of employees in each position, for NEW employees only
for (let i = this.state.numEmployees; i < office.employees.length; ++i) { for (let i = this.state.numEmployees; i < office.employees.length; ++i) {

@ -12,7 +12,6 @@ import { createProgressBarText } from "../../../utils/helpers/createProgressB
export class IndustryOverview extends BaseReactComponent { export class IndustryOverview extends BaseReactComponent {
renderMakeProductButton() { renderMakeProductButton() {
const corp = this.corp();
const division = this.routing().currentDivision; // Validated inside render() const division = this.routing().currentDivision; // Validated inside render()
var createProductButtonText, createProductPopupText; var createProductButtonText, createProductPopupText;
@ -97,7 +96,6 @@ export class IndustryOverview extends BaseReactComponent {
const popularity = `Popularity: ${numeralWrapper.format(division.popularity, "0.000")}`; const popularity = `Popularity: ${numeralWrapper.format(division.popularity, "0.000")}`;
let advertisingInfo = false; let advertisingInfo = false;
let advertisingTooltip;
const advertisingFactors = division.getAdvertisingFactors(); const advertisingFactors = division.getAdvertisingFactors();
const awarenessFac = advertisingFactors[1]; const awarenessFac = advertisingFactors[1];
const popularityFac = advertisingFactors[2]; const popularityFac = advertisingFactors[2];

@ -19,7 +19,6 @@ import { isString } from "../../../utils/helpers/isString";
function ProductComponent(props) { function ProductComponent(props) {
const corp = props.corp; const corp = props.corp;
const division = props.division; const division = props.division;
const warehouse = props.warehouse;
const city = props.city; const city = props.city;
const product = props.product; const product = props.product;
const eventHandler = props.eventHandler; const eventHandler = props.eventHandler;
@ -203,15 +202,6 @@ function MaterialComponent(props) {
// Total gain or loss of this material (per second) // Total gain or loss of this material (per second)
const totalGain = mat.buy + mat.prd + mat.imp - mat.sll - mat.totalExp; const totalGain = mat.buy + mat.prd + mat.imp - mat.sll - mat.totalExp;
// Competition and demand info, if they're unlocked
let cmpAndDmdText = "";
if (corp.unlockUpgrades[2] === 1) {
cmpAndDmdText += "<br>Demand: " + numeralWrapper.format(mat.dmd, nf);
}
if (corp.unlockUpgrades[3] === 1) {
cmpAndDmdText += "<br>Competition: " + numeralWrapper.format(mat.cmp, nf);
}
// Flag that determines whether this industry is "new" and the current material should be // Flag that determines whether this industry is "new" and the current material should be
// marked with flashing-red lights // marked with flashing-red lights
const tutorial = division.newInd && Object.keys(division.reqMats).includes(mat.name) && const tutorial = division.newInd && Object.keys(division.reqMats).includes(mat.name) &&
@ -511,7 +501,6 @@ export class IndustryWarehouse extends BaseReactComponent {
} }
render() { render() {
const corp = this.corp();
const division = this.routing().currentDivision; const division = this.routing().currentDivision;
if (division == null) { if (division == null) {
throw new Error(`Routing does not hold reference to the current Industry`); throw new Error(`Routing does not hold reference to the current Industry`);

@ -7,7 +7,6 @@ import { BaseReactComponent } from "./BaseReactComponent";
import { CityTabs } from "./CityTabs"; import { CityTabs } from "./CityTabs";
import { Industry } from "./Industry"; import { Industry } from "./Industry";
import { Overview } from "./Overview"; import { Overview } from "./Overview";
import { overviewPage } from "./Routing";
import { OfficeSpace } from "../Corporation"; import { OfficeSpace } from "../Corporation";

@ -4,7 +4,19 @@ export const overviewPage = "Overview";
// Interfaces for whatever's required to sanitize routing with Corporation Data // Interfaces for whatever's required to sanitize routing with Corporation Data
interface IOfficeSpace { interface IOfficeSpace {
loc: string;
cost: number;
size: number;
comf: number;
beau: number;
tier: any;
minEne: number;
maxEne: number;
minHap: number;
maxHap: number;
maxMor: number;
employees: any;
employeeProd: any;
} }
interface IDivision { interface IDivision {

@ -1,9 +1,10 @@
import { Crimes } from "./Crimes"; import { Crimes } from "./Crimes";
import { Crime } from "./Crime";
import { IPlayer } from "../PersonObjects/IPlayer"; import { IPlayer } from "../PersonObjects/IPlayer";
import { dialogBoxCreate } from "../../utils/DialogBox"; import { dialogBoxCreate } from "../../utils/DialogBox";
export function determineCrimeSuccess(p: IPlayer, type: string) { export function determineCrimeSuccess(p: IPlayer, type: string): boolean {
let chance = 0; let chance = 0;
let found = false; let found = false;
for (const i in Crimes) { for (const i in Crimes) {
@ -17,7 +18,7 @@ export function determineCrimeSuccess(p: IPlayer, type: string) {
if (!found) { if (!found) {
dialogBoxCreate(`ERR: Unrecognized crime type: ${type} This is probably a bug please contact the developer`, false); dialogBoxCreate(`ERR: Unrecognized crime type: ${type} This is probably a bug please contact the developer`, false);
return; return false;
} }
if (Math.random() <= chance) { if (Math.random() <= chance) {
@ -29,7 +30,7 @@ export function determineCrimeSuccess(p: IPlayer, type: string) {
} }
} }
export function findCrime(roughName: string) { export function findCrime(roughName: string): Crime | null {
if (roughName.includes("shoplift")) { if (roughName.includes("shoplift")) {
return Crimes.Shoplift; return Crimes.Shoplift;
} else if (roughName.includes("rob") && roughName.includes("store")) { } else if (roughName.includes("rob") && roughName.includes("store")) {

@ -22,7 +22,7 @@ export interface IPerson {
crime_success_mult: number; crime_success_mult: number;
} }
export function calculateCrimeSuccessChance(crime: ICrime, person: IPerson) { export function calculateCrimeSuccessChance(crime: ICrime, person: IPerson): number {
let chance: number = (crime.hacking_success_weight * person.hacking_skill + let chance: number = (crime.hacking_success_weight * person.hacking_skill +
crime.strength_success_weight * person.strength + crime.strength_success_weight * person.strength +
crime.defense_success_weight * person.defense + crime.defense_success_weight * person.defense +

@ -7,8 +7,6 @@ import { post, postElement } from "../ui/postToTerminal";
import { Money } from "../ui/React/Money"; import { Money } from "../ui/React/Money";
import { isValidIPAddress } from "../../utils/helpers/isValidIPAddress"; import { isValidIPAddress } from "../../utils/helpers/isValidIPAddress";
import { formatNumber } from "../../utils/StringHelperFunctions";
import { numeralWrapper } from "../ui/numeralFormat";
//Posts a "help" message if connected to DarkWeb //Posts a "help" message if connected to DarkWeb
export function checkIfConnectedToDarkweb(): void { export function checkIfConnectedToDarkweb(): void {
@ -29,27 +27,28 @@ export function checkIfConnectedToDarkweb(): void {
export function executeDarkwebTerminalCommand(commandArray: string[]): void { export function executeDarkwebTerminalCommand(commandArray: string[]): void {
if (commandArray.length == 0) {return;} if (commandArray.length == 0) {return;}
switch (commandArray[0]) { switch (commandArray[0]) {
case "buy": case "buy": {
if (commandArray.length != 2) { if (commandArray.length != 2) {
post("Incorrect number of arguments. Usage: "); post("Incorrect number of arguments. Usage: ");
post("buy -l"); post("buy -l");
post("buy [item name]"); post("buy [item name]");
return; return;
} }
var arg = commandArray[1]; const arg = commandArray[1];
if (arg == "-l") { if (arg == "-l") {
listAllDarkwebItems(); listAllDarkwebItems();
} else { } else {
buyDarkwebItem(arg); buyDarkwebItem(arg);
} }
break; break;
}
default: default:
post("Command not found"); post("Command not found");
break; break;
} }
} }
function listAllDarkwebItems() { function listAllDarkwebItems(): void {
for(const key in DarkWebItems) { for(const key in DarkWebItems) {
const item = DarkWebItems[key]; const item = DarkWebItems[key];
postElement(<>{item.program} - {Money(item.price)} - {item.description}</>); postElement(<>{item.program} - {Money(item.price)} - {item.description}</>);

@ -1,5 +1,3 @@
import { numeralWrapper } from "../ui/numeralFormat";
export class DarkWebItem { export class DarkWebItem {
program: string; program: string;
price: number; price: number;

@ -6,7 +6,6 @@ import {
generateRandomContractOnHome, generateRandomContractOnHome,
} from "./CodingContractGenerator"; } from "./CodingContractGenerator";
import { Companies } from "./Company/Companies"; import { Companies } from "./Company/Companies";
import { Company } from "./Company/Company";
import { Programs } from "./Programs/Programs"; import { Programs } from "./Programs/Programs";
import { Factions } from "./Faction/Factions"; import { Factions } from "./Faction/Factions";
import { Player } from "./Player"; import { Player } from "./Player";
@ -14,17 +13,11 @@ import { PlayerOwnedSourceFile } from "./SourceFile/PlayerOwnedSourceFile";
import { AllServers } from "./Server/AllServers"; import { AllServers } from "./Server/AllServers";
import { GetServerByHostname } from "./Server/ServerHelpers"; import { GetServerByHostname } from "./Server/ServerHelpers";
import { hackWorldDaemon } from "./RedPill"; import { hackWorldDaemon } from "./RedPill";
import { StockMarket, SymbolToStockMap } from "./StockMarket/StockMarket"; import { StockMarket } from "./StockMarket/StockMarket";
import { Stock } from "./StockMarket/Stock"; import { Stock } from "./StockMarket/Stock";
import { Terminal } from "./Terminal";
import { numeralWrapper } from "./ui/numeralFormat";
import { dialogBoxCreate } from "../utils/DialogBox"; import { dialogBoxCreate } from "../utils/DialogBox";
import { exceptionAlert } from "../utils/helpers/exceptionAlert";
import { createElement } from "../utils/uiHelpers/createElement"; import { createElement } from "../utils/uiHelpers/createElement";
import { createOptionElement } from "../utils/uiHelpers/createOptionElement";
import { getSelectText } from "../utils/uiHelpers/getSelectData";
import { removeElementById } from "../utils/uiHelpers/removeElementById"; import { removeElementById } from "../utils/uiHelpers/removeElementById";
import { Money } from "./ui/React/Money"; import { Money } from "./ui/React/Money";
@ -54,7 +47,6 @@ class ValueAdjusterComponent extends Component {
render() { render() {
const { title, add, subtract, reset } = this.props; const { title, add, subtract, reset } = this.props;
const { value } = this.state;
return ( return (
<> <>
<button className="std-button add-exp-button" onClick={() => add(this.state.value)}>+</button> <button className="std-button add-exp-button" onClick={() => add(this.state.value)}>+</button>
@ -281,9 +273,8 @@ class DevMenuComponent extends Component {
} }
modifyFactionRep(modifier) { modifyFactionRep(modifier) {
const component = this; return (reputation) => {
return function(reputation) { const fac = Factions[this.state.faction];
const fac = Factions[component.state.faction];
if (fac != null && !isNaN(reputation)) { if (fac != null && !isNaN(reputation)) {
fac.playerReputation += reputation*modifier; fac.playerReputation += reputation*modifier;
} }
@ -298,9 +289,8 @@ class DevMenuComponent extends Component {
} }
modifyFactionFavor(modifier) { modifyFactionFavor(modifier) {
const component = this; return (favor) => {
return function(favor) { const fac = Factions[this.state.faction];
const fac = Factions[component.state.faction];
if (fac != null && !isNaN(favor)) { if (fac != null && !isNaN(favor)) {
fac.favor += favor*modifier; fac.favor += favor*modifier;
} }
@ -370,10 +360,9 @@ class DevMenuComponent extends Component {
} }
setAllSF(sfLvl) { setAllSF(sfLvl) {
const component = this; return () => {
return function(){
for (let i = 0; i < validSFN.length; i++) { for (let i = 0; i < validSFN.length; i++) {
component.setSF(validSFN[i], sfLvl)(); this.setSF(validSFN[i], sfLvl)();
} }
} }
} }
@ -443,9 +432,8 @@ class DevMenuComponent extends Component {
} }
modifyCompanyRep(modifier) { modifyCompanyRep(modifier) {
const component = this; return (reputation) => {
return function(reputation) { const company = Companies[this.state.company];
const company = Companies[component.state.company];
if (company != null && !isNaN(reputation)) { if (company != null && !isNaN(reputation)) {
company.playerReputation += reputation*modifier; company.playerReputation += reputation*modifier;
} }
@ -458,9 +446,8 @@ class DevMenuComponent extends Component {
} }
modifyCompanyFavor(modifier) { modifyCompanyFavor(modifier) {
const component = this; return (favor) => {
return function(favor) { const company = Companies[this.state.company];
const company = Companies[component.state.company];
if (company != null && !isNaN(favor)) { if (company != null && !isNaN(favor)) {
company.favor += favor*modifier; company.favor += favor*modifier;
} }
@ -582,10 +569,10 @@ class DevMenuComponent extends Component {
}); });
} }
processStocks(cb) { processStocks(sub) {
const inputSymbols = document.getElementById('dev-stock-symbol').value.toString().replace(/\s/g, ''); const inputSymbols = document.getElementById('dev-stock-symbol').value.toString().replace(/\s/g, '');
let match = function(symbol) { return true; } let match = function() { return true; }
if (inputSymbols !== '' && inputSymbols !== 'all') { if (inputSymbols !== '' && inputSymbols !== 'all') {
match = function(symbol) { match = function(symbol) {
@ -597,7 +584,7 @@ class DevMenuComponent extends Component {
if (StockMarket.hasOwnProperty(name)) { if (StockMarket.hasOwnProperty(name)) {
const stock = StockMarket[name]; const stock = StockMarket[name];
if (stock instanceof Stock && match(stock.symbol)) { if (stock instanceof Stock && match(stock.symbol)) {
cb(stock); sub(stock);
} }
} }
} }
@ -638,13 +625,13 @@ class DevMenuComponent extends Component {
} }
} }
sleeveMaxAllSync() { sleeveSyncMaxAll() {
for (let i = 0; i < Player.sleeves.length; ++i) { for (let i = 0; i < Player.sleeves.length; ++i) {
Player.sleeves[i].sync = 100; Player.sleeves[i].sync = 100;
} }
} }
sleeveClearAllSync() { sleeveSyncClearAll() {
for (let i = 0; i < Player.sleeves.length; ++i) { for (let i = 0; i < Player.sleeves.length; ++i) {
Player.sleeves[i].sync = 0; Player.sleeves[i].sync = 0;
} }
@ -1212,8 +1199,8 @@ class DevMenuComponent extends Component {
</tr> </tr>
<tr> <tr>
<td><span className="text">Sync:</span></td> <td><span className="text">Sync:</span></td>
<td><button className="std-button" onClick={this.sleeveMaxAllSync}>Max all</button></td> <td><button className="std-button" onClick={this.sleeveSyncMaxAll}>Max all</button></td>
<td><button className="std-button" onClick={this.sleeveClearAllSync}>Clear all</button></td> <td><button className="std-button" onClick={this.sleeveSyncClearAll}>Clear all</button></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

@ -1,6 +1,6 @@
import { Player } from "../Player"; import { Player } from "../Player";
export function applyExploit() { export function applyExploit(): void {
if (Player.exploits && Player.exploits.length === 0) { if (Player.exploits && Player.exploits.length === 0) {
return; return;
} }

@ -2,7 +2,7 @@ import { Player } from "../Player";
import { Exploit } from "./Exploit"; import { Exploit } from "./Exploit";
(function() { (function() {
function clickTheUnclickable(event: MouseEvent) { function clickTheUnclickable(event: MouseEvent): void {
if(!event.target || !(event.target instanceof Element)) return; if(!event.target || !(event.target instanceof Element)) return;
const display = window.getComputedStyle(event.target as Element).display; const display = window.getComputedStyle(event.target as Element).display;
if(display === 'none' && event.isTrusted) if(display === 'none' && event.isTrusted)
@ -10,7 +10,7 @@ import { Exploit } from "./Exploit";
} }
function targetElement() { function targetElement(): void {
const elem = document.getElementById('unclickable'); const elem = document.getElementById('unclickable');
if(elem == null) { if(elem == null) {
console.error('Could not find the unclickable elem for the related exploit.'); console.error('Could not find the unclickable elem for the related exploit.');

@ -4,12 +4,6 @@ import { FactionInfo,
import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver"; import { Generic_fromJSON, Generic_toJSON, Reviver } from "../../utils/JSONReviver";
export class Faction { export class Faction {
/**
* Initiatizes a Faction object from a JSON save state.
*/
static fromJSON(value: any): Faction {
return Generic_fromJSON(Faction, value.data);
}
/** /**
* Flag signalling whether the player has already received an invitation * Flag signalling whether the player has already received an invitation
@ -103,6 +97,14 @@ export class Faction {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Faction", this); return 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: any): Faction {
return Generic_fromJSON(Faction, value.data);
}
} }
Reviver.constructors.Faction = Faction; Reviver.constructors.Faction = Faction;

@ -24,13 +24,6 @@ import {
import { Page, routing } from "../ui/navigationTracking"; import { Page, routing } from "../ui/navigationTracking";
import { dialogBoxCreate } from "../../utils/DialogBox"; import { dialogBoxCreate } from "../../utils/DialogBox";
import { factionInvitationBoxCreate } from "../../utils/FactionInvitationBox"; import { factionInvitationBoxCreate } from "../../utils/FactionInvitationBox";
import {
Reviver,
Generic_toJSON,
Generic_fromJSON,
} from "../../utils/JSONReviver";
import { formatNumber } from "../../utils/StringHelperFunctions";
import { numeralWrapper } from "../ui/numeralFormat";
import { Money } from "../ui/React/Money"; import { Money } from "../ui/React/Money";
import { import {
yesNoBoxCreate, yesNoBoxCreate,

@ -16,7 +16,7 @@ export function loadFactions(saveString: string): void {
Factions = JSON.parse(saveString, Reviver); Factions = JSON.parse(saveString, Reviver);
} }
export function AddToFactions(faction: Faction) { export function AddToFactions(faction: Faction): void {
const name: string = faction.name; const name: string = faction.name;
Factions[name] = faction; Factions[name] = faction;
} }
@ -25,7 +25,7 @@ export function factionExists(name: string): boolean {
return Factions.hasOwnProperty(name); return Factions.hasOwnProperty(name);
} }
export function initFactions(bitNode=1) { export function initFactions(): void {
for (const name in FactionInfos) { for (const name in FactionInfos) {
resetFaction(new Faction(name)); resetFaction(new Faction(name));
} }
@ -34,7 +34,7 @@ export function initFactions(bitNode=1) {
//Resets a faction during (re-)initialization. Saves the favor in the new //Resets a faction during (re-)initialization. Saves the favor in the new
//Faction object and deletes the old Faction Object from "Factions". Then //Faction object and deletes the old Faction Object from "Factions". Then
//reinserts the new Faction object //reinserts the new Faction object
export function resetFaction(newFactionObject: Faction) { export function resetFaction(newFactionObject: Faction): void {
if (!(newFactionObject instanceof Faction)) { if (!(newFactionObject instanceof Faction)) {
throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()"); throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()");
} }

@ -118,22 +118,21 @@ export class AugmentationsPage extends React.Component<IProps, IState> {
}); });
} }
render() { render(): React.ReactNode {
const augs = this.getAugsSorted(); const augs = this.getAugsSorted();
const purchasable = augs.filter((aug: string) => aug === AugmentationNames.NeuroFluxGovernor || const purchasable = augs.filter((aug: string) => aug === AugmentationNames.NeuroFluxGovernor ||
(!this.props.p.augmentations.some(a => a.name === aug) && (!this.props.p.augmentations.some(a => a.name === aug) &&
!this.props.p.queuedAugmentations.some(a => a.name === aug)), !this.props.p.queuedAugmentations.some(a => a.name === aug)),
) )
const parent = this; const purchaseableAugmentation = (aug: string): React.ReactNode => {
function purchaseableAugmentation(aug: string) {
return ( return (
<PurchaseableAugmentation <PurchaseableAugmentation
augName={aug} augName={aug}
faction={parent.props.faction} faction={this.props.faction}
key={aug} key={aug}
p={parent.props.p} p={this.props.p}
rerender={parent.rerender} rerender={this.rerender}
/> />
) )
} }

@ -7,7 +7,6 @@ import { CONSTANTS } from "../../Constants";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../../Faction/Faction";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
import { Reputation } from "../../ui/React/Reputation"; import { Reputation } from "../../ui/React/Reputation";
@ -32,7 +31,7 @@ const inputStyleMarkup = {
export class DonateOption extends React.Component<IProps, IState> { export class DonateOption extends React.Component<IProps, IState> {
// Style markup for block elements. Stored as property // Style markup for block elements. Stored as property
blockStyle: object = { display: "block" }; blockStyle: any = { display: "block" };
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -87,7 +86,7 @@ export class DonateOption extends React.Component<IProps, IState> {
} }
} }
render() { render(): React.ReactNode {
return ( return (
<div className={"faction-work-div"}> <div className={"faction-work-div"}>
<div className={"faction-work-div-wrapper"}> <div className={"faction-work-div-wrapper"}>

@ -6,7 +6,6 @@ import * as React from "react";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../../Faction/Faction";
import { FactionInfo } from "../../Faction/FactionInfo"; import { FactionInfo } from "../../Faction/FactionInfo";
import { numeralWrapper } from "../../ui/numeralFormat";
import { AutoupdatingParagraph } from "../../ui/React/AutoupdatingParagraph"; import { AutoupdatingParagraph } from "../../ui/React/AutoupdatingParagraph";
import { ParagraphWithTooltip } from "../../ui/React/ParagraphWithTooltip"; import { ParagraphWithTooltip } from "../../ui/React/ParagraphWithTooltip";
@ -48,7 +47,7 @@ export class Info extends React.Component<IProps, any> {
return <>Reputation: {Reputation(this.props.faction.playerReputation)}</> return <>Reputation: {Reputation(this.props.faction.playerReputation)}</>
} }
render() { render(): React.ReactNode {
const favorTooltip = "Faction favor increases the rate at which you earn reputation for " + const favorTooltip = "Faction favor increases the rate at which you earn reputation for " +
"this faction by 1% per favor. Faction favor is gained whenever you " + "this faction by 1% per favor. Faction favor is gained whenever you " +
"reset after installing an Augmentation. The amount of " + "reset after installing an Augmentation. The amount of " +

@ -14,7 +14,7 @@ type IProps = {
} }
export class Option extends React.Component<IProps, any> { export class Option extends React.Component<IProps, any> {
render() { render(): React.ReactNode {
return ( return (
<div className={"faction-work-div"}> <div className={"faction-work-div"}>
<div className={"faction-work-div-wrapper"}> <div className={"faction-work-div-wrapper"}>

@ -17,7 +17,6 @@ import { AugmentationNames } from "../../Augmentation/data/AugmentationNames";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../../Faction/Faction";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
import { Reputation } from "../../ui/React/Reputation"; import { Reputation } from "../../ui/React/Reputation";
import { IMap } from "../../types"; import { IMap } from "../../types";
@ -42,35 +41,37 @@ const inlineStyleMarkup = {
} }
export class PurchaseableAugmentation extends React.Component<IProps, any> { export class PurchaseableAugmentation extends React.Component<IProps, any> {
aug: Augmentation | null; aug: Augmentation;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
this.aug = Augmentations[this.props.augName]; const aug = Augmentations[this.props.augName];
if(aug == null) throw new Error(`aug ${this.props.augName} does not exists`);
this.aug = aug;
this.handleClick = this.handleClick.bind(this); this.handleClick = this.handleClick.bind(this);
} }
getMoneyCost(): number { getMoneyCost(): number {
return this.aug!.baseCost * this.props.faction.getInfo().augmentationPriceMult; return this.aug.baseCost * this.props.faction.getInfo().augmentationPriceMult;
} }
getRepCost(): number { getRepCost(): number {
return this.aug!.baseRepRequirement * this.props.faction.getInfo().augmentationRepRequirementMult; return this.aug.baseRepRequirement * this.props.faction.getInfo().augmentationRepRequirementMult;
} }
handleClick() { handleClick(): void {
if (!Settings.SuppressBuyAugmentationConfirmation) { if (!Settings.SuppressBuyAugmentationConfirmation) {
purchaseAugmentationBoxCreate(this.aug!, this.props.faction); purchaseAugmentationBoxCreate(this.aug, this.props.faction);
} else { } else {
purchaseAugmentation(this.aug!, this.props.faction); purchaseAugmentation(this.aug, this.props.faction);
} }
} }
// Whether the player has the prerequisite Augmentations // Whether the player has the prerequisite Augmentations
hasPrereqs(): boolean { hasPrereqs(): boolean {
return hasAugmentationPrereqs(this.aug!); return hasAugmentationPrereqs(this.aug);
} }
// Whether the player has enough rep for this Augmentation // Whether the player has enough rep for this Augmentation
@ -98,7 +99,7 @@ export class PurchaseableAugmentation extends React.Component<IProps, any> {
return owned; return owned;
} }
render() { render(): React.ReactNode {
if (this.aug == null) { if (this.aug == null) {
console.error(`Invalid Augmentation when trying to create PurchaseableAugmentation display element: ${this.props.augName}`); console.error(`Invalid Augmentation when trying to create PurchaseableAugmentation display element: ${this.props.augName}`);
return null; return null;

@ -92,7 +92,7 @@ export class FactionRoot extends React.Component<IProps, IState> {
this.startSecurityWork = this.startSecurityWork.bind(this); this.startSecurityWork = this.startSecurityWork.bind(this);
} }
manageGang() { manageGang(): void {
// If player already has a gang, just go to the gang UI // If player already has a gang, just go to the gang UI
if (this.props.p.inGang()) { if (this.props.p.inGang()) {
return this.props.engine.loadGangContent(); return this.props.engine.loadGangContent();
@ -146,7 +146,7 @@ export class FactionRoot extends React.Component<IProps, IState> {
"create a Gang with, and each of these Factions have all Augmentations available."); "create a Gang with, and each of these Factions have all Augmentations available.");
} }
rerender() { rerender(): void {
this.setState((prevState) => { this.setState((prevState) => {
return { return {
rerenderFlag: !prevState.rerenderFlag, rerenderFlag: !prevState.rerenderFlag,
@ -155,42 +155,42 @@ export class FactionRoot extends React.Component<IProps, IState> {
} }
// Route to the main faction page // Route to the main faction page
routeToMain() { routeToMain(): void {
this.setState({ purchasingAugs: false }); this.setState({ purchasingAugs: false });
} }
// Route to the purchase augmentation UI for this faction // Route to the purchase augmentation UI for this faction
routeToPurchaseAugs() { routeToPurchaseAugs(): void {
this.setState({ purchasingAugs: true }); this.setState({ purchasingAugs: true });
} }
sleevePurchases() { sleevePurchases(): void {
createSleevePurchasesFromCovenantPopup(this.props.p); createSleevePurchasesFromCovenantPopup(this.props.p);
} }
startFieldWork() { startFieldWork(): void {
this.props.p.startFactionFieldWork(this.props.faction); this.props.p.startFactionFieldWork(this.props.faction);
} }
startHackingContracts() { startHackingContracts(): void {
this.props.p.startFactionHackWork(this.props.faction); this.props.p.startFactionHackWork(this.props.faction);
} }
startHackingMission() { startHackingMission(): void {
const fac = this.props.faction; const fac = this.props.faction;
this.props.engine.loadMissionContent(); this.props.engine.loadMissionContent();
this.props.startHackingMissionFn(fac); this.props.startHackingMissionFn(fac);
} }
startSecurityWork() { startSecurityWork(): void {
this.props.p.startFactionSecurityWork(this.props.faction); this.props.p.startFactionSecurityWork(this.props.faction);
} }
render() { render(): React.ReactNode {
return this.state.purchasingAugs ? this.renderAugmentationsPage() : this.renderMainPage(); return this.state.purchasingAugs ? this.renderAugmentationsPage() : this.renderMainPage();
} }
renderMainPage() { renderMainPage(): React.ReactNode {
const p = this.props.p; const p = this.props.p;
const faction = this.props.faction; const faction = this.props.faction;
const factionInfo = faction.getInfo(); const factionInfo = faction.getInfo();
@ -288,7 +288,7 @@ export class FactionRoot extends React.Component<IProps, IState> {
) )
} }
renderAugmentationsPage() { renderAugmentationsPage(): React.ReactNode {
return ( return (
<div> <div>
<AugmentationsPage <AugmentationsPage

@ -21,7 +21,10 @@ import {
Generic_toJSON, Generic_toJSON,
Generic_fromJSON, Generic_fromJSON,
} from "../utils/JSONReviver"; } from "../utils/JSONReviver";
import { formatNumber } from "../utils/StringHelperFunctions"; import {
formatNumber,
convertTimeMsToTimeElapsedString,
} from "../utils/StringHelperFunctions";
import { exceptionAlert } from "../utils/helpers/exceptionAlert"; import { exceptionAlert } from "../utils/helpers/exceptionAlert";
import { getRandomInt } from "../utils/helpers/getRandomInt"; import { getRandomInt } from "../utils/helpers/getRandomInt";
@ -33,7 +36,6 @@ import { createPopup } from "../utils/uiHelpers/createPopup";
import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement";
import { removeElement } from "../utils/uiHelpers/removeElement"; import { removeElement } from "../utils/uiHelpers/removeElement";
import { removeElementById } from "../utils/uiHelpers/removeElementById"; import { removeElementById } from "../utils/uiHelpers/removeElementById";
import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions";
import { StatsTable } from "./ui/React/StatsTable"; import { StatsTable } from "./ui/React/StatsTable";
import { Money } from "./ui/React/Money"; import { Money } from "./ui/React/Money";
@ -47,7 +49,6 @@ import { renderToStaticMarkup } from "react-dom/server"
// Constants // Constants
const GangRespectToReputationRatio = 5; // Respect is divided by this to get rep gain const GangRespectToReputationRatio = 5; // Respect is divided by this to get rep gain
const MaximumGangMembers = 30; const MaximumGangMembers = 30;
const GangRecruitCostMultiplier = 2;
const CyclesPerTerritoryAndPowerUpdate = 100; const CyclesPerTerritoryAndPowerUpdate = 100;
const AscensionMultiplierRatio = 15 / 100; // Portion of upgrade multiplier that is kept after ascending const AscensionMultiplierRatio = 15 / 100; // Portion of upgrade multiplier that is kept after ascending
@ -69,7 +70,6 @@ $(document).keydown(function(event) {
// Delete upgrade box when clicking outside // Delete upgrade box when clicking outside
$(document).mousedown(function(event) { $(document).mousedown(function(event) {
var boxId = "gang-member-upgrade-popup-box";
var contentId = "gang-member-upgrade-popup-box-content"; var contentId = "gang-member-upgrade-popup-box-content";
if (UIElems.gangMemberUpgradeBoxOpened) { if (UIElems.gangMemberUpgradeBoxOpened) {
if ( $(event.target).closest("#" + contentId).get(0) == null ) { if ( $(event.target).closest("#" + contentId).get(0) == null ) {
@ -461,8 +461,6 @@ Gang.prototype.clash = function(won=false) {
} }
Gang.prototype.killMember = function(memberObj) { Gang.prototype.killMember = function(memberObj) {
const gangName = this.facName;
// Player loses a percentage of total respect, plus whatever respect that member has earned // Player loses a percentage of total respect, plus whatever respect that member has earned
const totalRespect = this.respect; const totalRespect = this.respect;
const lostRespect = (0.05 * totalRespect) + memberObj.earnedRespect; const lostRespect = (0.05 * totalRespect) + memberObj.earnedRespect;
@ -1266,10 +1264,7 @@ Gang.prototype.displayGangContent = function(player) {
}); });
// Get variables // Get variables
var facName = this.facName, var facName = this.facName;
members = this.members,
wanted = this.wanted,
respect = this.respect;
// Back button // Back button
UIElems.gangContainer.appendChild(createElement("a", { UIElems.gangContainer.appendChild(createElement("a", {
@ -1757,7 +1752,6 @@ Gang.prototype.createGangMemberDisplayElement = function(memberObj) {
hdrText: name, hdrText: name,
}); });
const li = accordion[0]; const li = accordion[0];
const hdr = accordion[1];
const gangMemberDiv = accordion[2]; const gangMemberDiv = accordion[2];
UIElems.gangMemberPanels[name]["panel"] = gangMemberDiv; UIElems.gangMemberPanels[name]["panel"] = gangMemberDiv;

@ -1,9 +1,7 @@
import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers";
import { Player } from "./Player";
import { IPlayer } from "./PersonObjects/IPlayer"; import { IPlayer } from "./PersonObjects/IPlayer";
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence"; import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
import { Server } from "./Server/Server"; import { Server } from "./Server/Server";
import { HacknetServer } from "./Hacknet/HacknetServer";
/** /**
* Returns the chance the player has to successfully hack a server * Returns the chance the player has to successfully hack a server

@ -28,8 +28,6 @@ import { GetServerByHostname } from "../Server/ServerHelpers";
import { SourceFileFlags } from "../SourceFile/SourceFileFlags"; import { SourceFileFlags } from "../SourceFile/SourceFileFlags";
import { Page, routing } from "../ui/navigationTracking"; import { Page, routing } from "../ui/navigationTracking";
import { getElementById } from "../../utils/uiHelpers/getElementById";
import React from "react"; import React from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import { HacknetRoot } from "./ui/Root"; import { HacknetRoot } from "./ui/Root";
@ -68,7 +66,7 @@ export function purchaseHacknet() {
if (!Player.canAfford(cost)) { return -1; } if (!Player.canAfford(cost)) { return -1; }
Player.loseMoney(cost); Player.loseMoney(cost);
const server = Player.createHacknetServer(); Player.createHacknetServer();
updateHashManagerCapacity(); updateHashManagerCapacity();
return numOwned; return numOwned;

@ -8,7 +8,6 @@ import { IHacknetNode } from "./IHacknetNode";
import { CONSTANTS } from "../Constants"; import { CONSTANTS } from "../Constants";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { import {
calculateMoneyGainRate, calculateMoneyGainRate,
calculateLevelUpgradeCost, calculateLevelUpgradeCost,
@ -23,12 +22,6 @@ import { Generic_fromJSON,
Reviver } from "../../utils/JSONReviver"; Reviver } from "../../utils/JSONReviver";
export class HacknetNode implements IHacknetNode { export class HacknetNode implements IHacknetNode {
/**
* Initiatizes a HacknetNode object from a JSON save state.
*/
static fromJSON(value: any): HacknetNode {
return Generic_fromJSON(HacknetNode, value.data);
}
// Node's number of cores // Node's number of cores
cores = 1; cores = 1;
@ -127,6 +120,14 @@ export class HacknetNode implements IHacknetNode {
toJSON(): any { toJSON(): any {
return Generic_toJSON("HacknetNode", this); return 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: any): HacknetNode {
return Generic_fromJSON(HacknetNode, value.data);
}
} }
Reviver.constructors.HacknetNode = HacknetNode; Reviver.constructors.HacknetNode = HacknetNode;

@ -5,7 +5,6 @@ import { CONSTANTS } from "../Constants";
import { IHacknetNode } from "./IHacknetNode"; import { IHacknetNode } from "./IHacknetNode";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { BaseServer } from "../Server/BaseServer"; import { BaseServer } from "../Server/BaseServer";
import { RunningScript } from "../Script/RunningScript"; import { RunningScript } from "../Script/RunningScript";
import { HacknetServerConstants } from "./data/Constants"; import { HacknetServerConstants } from "./data/Constants";
@ -35,10 +34,6 @@ interface IConstructorParams {
} }
export class HacknetServer extends BaseServer implements IHacknetNode { export class HacknetServer extends BaseServer implements IHacknetNode {
// Initializes a HacknetServer Object from a JSON save state
static fromJSON(value: any): HacknetServer {
return Generic_fromJSON(HacknetServer, value.data);
}
// Cache level. Affects hash Capacity // Cache level. Affects hash Capacity
cache = 1; cache = 1;
@ -141,6 +136,12 @@ export class HacknetServer extends BaseServer implements IHacknetNode {
toJSON(): any { toJSON(): any {
return Generic_toJSON("HacknetServer", this); return 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: any): HacknetServer {
return Generic_fromJSON(HacknetServer, value.data);
}
} }
Reviver.constructors.HacknetServer = HacknetServer; Reviver.constructors.HacknetServer = HacknetServer;

@ -15,10 +15,6 @@ import { Generic_fromJSON,
Reviver } from "../../utils/JSONReviver"; Reviver } from "../../utils/JSONReviver";
export class HashManager { export class HashManager {
// Initiatizes a HashManager object from a JSON save state.
static fromJSON(value: any): HashManager {
return Generic_fromJSON(HashManager, value.data);
}
// Max number of hashes this can hold. Equal to the sum of capacities of // Max number of hashes this can hold. Equal to the sum of capacities of
// all Hacknet Servers // all Hacknet Servers
@ -159,6 +155,12 @@ export class HashManager {
toJSON(): any { toJSON(): any {
return Generic_toJSON("HashManager", this); return 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: any): HashManager {
return Generic_fromJSON(HashManager, value.data);
}
} }
Reviver.constructors.HashManager = HashManager; Reviver.constructors.HashManager = HashManager;

@ -9,7 +9,7 @@ import { IMap } from "../types";
export const HashUpgrades: IMap<HashUpgrade> = {}; export const HashUpgrades: IMap<HashUpgrade> = {};
function createHashUpgrade(p: IConstructorParams) { function createHashUpgrade(p: IConstructorParams): void {
HashUpgrades[p.name] = new HashUpgrade(p); HashUpgrades[p.name] = new HashUpgrade(p);
} }

@ -16,7 +16,6 @@ import {
import { Player } from "../../Player"; import { Player } from "../../Player";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
import { MoneyRate } from "../../ui/React/MoneyRate"; import { MoneyRate } from "../../ui/React/MoneyRate";

@ -19,7 +19,6 @@ import {
import { Player } from "../../Player"; import { Player } from "../../Player";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
import { Hashes } from "../../ui/React/Hashes"; import { Hashes } from "../../ui/React/Hashes";
import { HashRate } from "../../ui/React/HashRate"; import { HashRate } from "../../ui/React/HashRate";

@ -8,12 +8,9 @@ import { HashManager } from "../HashManager";
import { HashUpgrades } from "../HashUpgrades"; import { HashUpgrades } from "../HashUpgrades";
import { Player } from "../../Player"; import { Player } from "../../Player";
import { AllServers } from "../../Server/AllServers";
import { Server } from "../../Server/Server";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../../ui/numeralFormat";
import { removePopup } from "../../ui/React/createPopup";
import { PopupCloseButton } from "../../ui/React/PopupCloseButton"; import { PopupCloseButton } from "../../ui/React/PopupCloseButton";
import { ServerDropdown, import { ServerDropdown,
ServerType } from "../../ui/React/ServerDropdown" ServerType } from "../../ui/React/ServerDropdown"

@ -8,7 +8,6 @@ import React from "react";
import { hasHacknetServers } from "../HacknetHelpers"; import { hasHacknetServers } from "../HacknetHelpers";
import { Player } from "../../Player"; import { Player } from "../../Player";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
import { MoneyRate } from "../../ui/React/MoneyRate"; import { MoneyRate } from "../../ui/React/MoneyRate";
import { HashRate } from "../../ui/React/HashRate"; import { HashRate } from "../../ui/React/HashRate";

@ -6,7 +6,6 @@ import React from "react";
import { hasHacknetServers, import { hasHacknetServers,
hasMaxNumberHacknetServers } from "../HacknetHelpers"; hasMaxNumberHacknetServers } from "../HacknetHelpers";
import { Player } from "../../Player"; import { Player } from "../../Player";
import { numeralWrapper } from "../../ui/numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
export function PurchaseButton(props) { export function PurchaseButton(props) {

@ -20,7 +20,6 @@ import { Player } from "../../Player";
import { AllServers } from "../../Server/AllServers"; import { AllServers } from "../../Server/AllServers";
import { createPopup } from "../../ui/React/createPopup"; import { createPopup } from "../../ui/React/createPopup";
import { PopupCloseButton } from "../../ui/React/PopupCloseButton";
export const PurchaseMultipliers = Object.freeze({ export const PurchaseMultipliers = Object.freeze({
"x1": 1, "x1": 1,

@ -490,7 +490,6 @@ function updateInfiltrationLevelText(inst) {
BitNodeMultipliers.InfiltrationMoney; BitNodeMultipliers.InfiltrationMoney;
} }
var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel;
// TODO: fix this to not rely on <pre> and whitespace for formatting... // TODO: fix this to not rely on <pre> and whitespace for formatting...
/* eslint-disable no-irregular-whitespace */ /* eslint-disable no-irregular-whitespace */
document.getElementById("infiltration-level-text").innerHTML = document.getElementById("infiltration-level-text").innerHTML =

@ -116,7 +116,7 @@ export function createPurchaseServerPopup(ram: number, p: IPlayer): void {
* Create a popup that lets the player start a Corporation * Create a popup that lets the player start a Corporation
* @param {IPlayer} p - Player object * @param {IPlayer} p - Player object
*/ */
export function createStartCorporationPopup(p: IPlayer) { export function createStartCorporationPopup(p: IPlayer): void {
if (!p.canAccessCorporation() || p.hasCorporation()) { return; } if (!p.canAccessCorporation() || p.hasCorporation()) { return; }
const popupId = "create-corporation-popup"; const popupId = "create-corporation-popup";
@ -196,7 +196,7 @@ export function createStartCorporationPopup(p: IPlayer) {
* Create a popup that lets the player upgrade the cores on his/her home computer * Create a popup that lets the player upgrade the cores on his/her home computer
* @param {IPlayer} p - Player object * @param {IPlayer} p - Player object
*/ */
export function createUpgradeHomeCoresPopup(p: IPlayer) { export function createUpgradeHomeCoresPopup(p: IPlayer): void {
const currentCores = p.getHomeComputer().cpuCores; const currentCores = p.getHomeComputer().cpuCores;
if (currentCores >= 8) { if (currentCores >= 8) {
dialogBoxCreate(<> dialogBoxCreate(<>
@ -252,7 +252,7 @@ cost {Money(cost)}</>);
* Create a popup that lets the player upgrade the RAM on his/her home computer * Create a popup that lets the player upgrade the RAM on his/her home computer
* @param {IPlayer} p - Player object * @param {IPlayer} p - Player object
*/ */
export function createUpgradeHomeRamPopup(p: IPlayer) { export function createUpgradeHomeRamPopup(p: IPlayer): void {
const cost: number = p.getUpgradeHomeRamCost(); const cost: number = p.getUpgradeHomeRamCost();
const ram: number = p.getHomeComputer().maxRam; const ram: number = p.getHomeComputer().maxRam;
@ -291,7 +291,7 @@ export function createUpgradeHomeRamPopup(p: IPlayer) {
* Attempt to purchase a TOR router * Attempt to purchase a TOR router
* @param {IPlayer} p - Player object * @param {IPlayer} p - Player object
*/ */
export function purchaseTorRouter(p: IPlayer) { export function purchaseTorRouter(p: IPlayer): void {
if (p.hasTorRouter()) { if (p.hasTorRouter()) {
dialogBoxCreate(`You already have a TOR Router`); dialogBoxCreate(`You already have a TOR Router`);
return; return;

@ -15,7 +15,7 @@ type IProps = {
entryPosType: CompanyPosition; entryPosType: CompanyPosition;
onClick: (e: React.MouseEvent<HTMLElement>) => void; onClick: (e: React.MouseEvent<HTMLElement>) => void;
p: IPlayer; p: IPlayer;
style?: object; style?: any;
text: string; text: string;
} }
@ -35,7 +35,7 @@ export class ApplyToJobButton extends React.Component<IProps, any> {
return getJobRequirementText(this.props.company, pos, true); return getJobRequirementText(this.props.company, pos, true);
} }
render() { render(): React.ReactNode {
return ( return (
<StdButton <StdButton
onClick={this.props.onClick} onClick={this.props.onClick}

@ -17,13 +17,14 @@ type IProps = {
} }
export class LocationCity extends React.Component<IProps, any> { export class LocationCity extends React.Component<IProps, any> {
asciiCity() { asciiCity(): React.ReactNode {
const thiscity = this; const LocationLetter = (location: LocationName): JSX.Element => {
const topprop = this.props;
function LocationLetter(location: LocationName) {
if (location) if (location)
return <span key={location} className="tooltip" style={{color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px', cursor: 'pointer'}} onClick={topprop.enterLocation.bind(thiscity, location)}> return <span
key={location}
className="tooltip"
style={{color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px', cursor: 'pointer'}}
onClick={this.props.enterLocation.bind(this, location)}>
X X
</span> </span>
return <span>*</span> return <span>*</span>
@ -35,8 +36,7 @@ export class LocationCity extends React.Component<IProps, any> {
'P': 15,'Q': 16,'R': 17,'S': 18,'T': 19,'U': 20,'V': 21,'W': 22, 'P': 15,'Q': 16,'R': 17,'S': 18,'T': 19,'U': 20,'V': 21,'W': 22,
'X': 23,'Y': 24,'Z': 25} 'X': 23,'Y': 24,'Z': 25}
let locI = 0; const lineElems = (s: string): JSX.Element[] => {
function lineElems(s: string) {
const elems: any[] = []; const elems: any[] = [];
const matches: any[] = []; const matches: any[] = [];
let match: any; let match: any;
@ -48,20 +48,18 @@ export class LocationCity extends React.Component<IProps, any> {
return elems; return elems;
} }
const parts: any[] = [];
for(let i = 0; i < matches.length; i++) { for(let i = 0; i < matches.length; i++) {
const startI = i === 0 ? 0 : matches[i-1].index+1; const startI = i === 0 ? 0 : matches[i-1].index+1;
const endI = matches[i].index; const endI = matches[i].index;
elems.push(s.slice(startI, endI)) elems.push(s.slice(startI, endI))
const locationI = letterMap[s[matches[i].index]]; const locationI = letterMap[s[matches[i].index]];
elems.push(LocationLetter(thiscity.props.city.locations[locationI])) elems.push(LocationLetter(this.props.city.locations[locationI]))
locI++;
} }
elems.push(s.slice(matches[matches.length-1].index+1)) elems.push(s.slice(matches[matches.length-1].index+1))
return elems; return elems;
} }
const elems: any[] = []; const elems: JSX.Element[] = [];
const lines = this.props.city.asciiArt.split('\n'); const lines = this.props.city.asciiArt.split('\n');
for(const i in lines) { for(const i in lines) {
elems.push(<pre key={i}>{lineElems(lines[i])}</pre>) elems.push(<pre key={i}>{lineElems(lines[i])}</pre>)
@ -70,7 +68,7 @@ export class LocationCity extends React.Component<IProps, any> {
return elems; return elems;
} }
listCity() { listCity(): React.ReactNode {
const locationButtons = this.props.city.locations.map((locName) => { const locationButtons = this.props.city.locations.map((locName) => {
return ( return (
<li key={locName}> <li key={locName}>
@ -86,7 +84,7 @@ export class LocationCity extends React.Component<IProps, any> {
) )
} }
render() { render(): React.ReactNode {
return ( return (
<> <>
{Settings.DisableASCIIArt ? this.listCity() : this.asciiCity()} {Settings.DisableASCIIArt ? this.listCity() : this.asciiCity()}

@ -21,7 +21,6 @@ import { CompanyPositions } from "../../Company/CompanyPositions";
import * as posNames from "../../Company/data/companypositionnames"; import * as posNames from "../../Company/data/companypositionnames";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { numeralWrapper } from "../../ui/numeralFormat";
import { StdButton } from "../../ui/React/StdButton"; import { StdButton } from "../../ui/React/StdButton";
import { Reputation } from "../../ui/React/Reputation"; import { Reputation } from "../../ui/React/Reputation";
import { Favor } from "../../ui/React/Favor"; import { Favor } from "../../ui/React/Favor";
@ -63,7 +62,7 @@ export class CompanyLocation extends React.Component<IProps, IState> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
/** /**
* Reference to the Location that this component is being rendered for * Reference to the Location that this component is being rendered for
@ -112,73 +111,73 @@ export class CompanyLocation extends React.Component<IProps, IState> {
this.checkIfEmployedHere(false); this.checkIfEmployedHere(false);
} }
applyForAgentJob(e: React.MouseEvent<HTMLElement>) { applyForAgentJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForAgentJob(); this.props.p.applyForAgentJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForBusinessConsultantJob(e: React.MouseEvent<HTMLElement>) { applyForBusinessConsultantJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForBusinessConsultantJob(); this.props.p.applyForBusinessConsultantJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForBusinessJob(e: React.MouseEvent<HTMLElement>) { applyForBusinessJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForBusinessJob(); this.props.p.applyForBusinessJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForEmployeeJob(e: React.MouseEvent<HTMLElement>) { applyForEmployeeJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForEmployeeJob(); this.props.p.applyForEmployeeJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForItJob(e: React.MouseEvent<HTMLElement>) { applyForItJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForItJob(); this.props.p.applyForItJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForPartTimeEmployeeJob(e: React.MouseEvent<HTMLElement>) { applyForPartTimeEmployeeJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForPartTimeEmployeeJob(); this.props.p.applyForPartTimeEmployeeJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForPartTimeWaiterJob(e: React.MouseEvent<HTMLElement>) { applyForPartTimeWaiterJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForPartTimeWaiterJob(); this.props.p.applyForPartTimeWaiterJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForSecurityJob(e: React.MouseEvent<HTMLElement>) { applyForSecurityJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForSecurityJob(); this.props.p.applyForSecurityJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForSoftwareConsultantJob(e: React.MouseEvent<HTMLElement>) { applyForSoftwareConsultantJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForSoftwareConsultantJob(); this.props.p.applyForSoftwareConsultantJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForSoftwareJob(e: React.MouseEvent<HTMLElement>) { applyForSoftwareJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForSoftwareJob(); this.props.p.applyForSoftwareJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
applyForWaiterJob(e: React.MouseEvent<HTMLElement>) { applyForWaiterJob(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
this.props.p.applyForWaiterJob(); this.props.p.applyForWaiterJob();
this.checkIfEmployedHere(true); this.checkIfEmployedHere(true);
} }
checkIfEmployedHere(updateState=false) { checkIfEmployedHere(updateState=false): void {
this.jobTitle = this.props.p.jobs[this.props.locName]; this.jobTitle = this.props.p.jobs[this.props.locName];
if (this.jobTitle != null) { if (this.jobTitle != null) {
this.companyPosition = CompanyPositions[this.jobTitle]; this.companyPosition = CompanyPositions[this.jobTitle];
@ -191,19 +190,19 @@ export class CompanyLocation extends React.Component<IProps, IState> {
} }
} }
startInfiltration(e: React.MouseEvent<HTMLElement>) { startInfiltration(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
const loc = this.location; const loc = this.location;
this.props.engine.loadInfiltrationContent(); this.props.engine.loadInfiltrationContent();
const data = loc.infiltrationData; const data = loc.infiltrationData;
if (data == null) { return false; } if (data == null) { return; }
beginInfiltration(this.props.locName, data.startingSecurityLevel, data.baseRewardValue, data.maxClearanceLevel, data.difficulty); beginInfiltration(this.props.locName, data.startingSecurityLevel, data.baseRewardValue, data.maxClearanceLevel, data.difficulty);
} }
work(e: React.MouseEvent<HTMLElement>) { work(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
const pos = this.companyPosition; const pos = this.companyPosition;
if (pos instanceof CompanyPosition) { if (pos instanceof CompanyPosition) {
@ -215,8 +214,8 @@ export class CompanyLocation extends React.Component<IProps, IState> {
} }
} }
quit(e: React.MouseEvent<HTMLElement>) { quit(e: React.MouseEvent<HTMLElement>): void {
if (!e.isTrusted) { return false; } if (!e.isTrusted) { return; }
const yesBtn = yesNoBoxGetYesButton(); const yesBtn = yesNoBoxGetYesButton();
const noBtn = yesNoBoxGetNoButton(); const noBtn = yesNoBoxGetNoButton();
@ -235,7 +234,7 @@ export class CompanyLocation extends React.Component<IProps, IState> {
yesNoBoxCreate(<>Would you like to quit your job at {this.company.name}?</>); yesNoBoxCreate(<>Would you like to quit your job at {this.company.name}?</>);
} }
render() { render(): React.ReactNode {
const isEmployedHere = this.jobTitle != null; const isEmployedHere = this.jobTitle != null;
const favorGain = this.company.getFavorGain(); const favorGain = this.company.getFavorGain();

@ -42,7 +42,7 @@ export class GenericLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -149,7 +149,7 @@ export class GenericLocation extends React.Component<IProps, any> {
return content; return content;
} }
render() { render(): React.ReactNode {
const locContent: React.ReactNode[] = this.getLocationSpecificContent(); const locContent: React.ReactNode[] = this.getLocationSpecificContent();
const ip = SpecialServerIps.getIp(this.props.loc.name); const ip = SpecialServerIps.getIp(this.props.loc.name);
const server = getServer(ip); const server = getServer(ip);

@ -13,7 +13,6 @@ import { getServer } from "../../Server/ServerHelpers";
import { Server } from "../../Server/Server"; import { Server } from "../../Server/Server";
import { SpecialServerIps } from "../../Server/SpecialServerIps"; import { SpecialServerIps } from "../../Server/SpecialServerIps";
import { numeralWrapper } from "../../ui/numeralFormat";
import { StdButton } from "../../ui/React/StdButton"; import { StdButton } from "../../ui/React/StdButton";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
@ -26,7 +25,7 @@ export class GymLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -50,28 +49,28 @@ export class GymLocation extends React.Component<IProps, any> {
return this.props.loc.costMult * discount; return this.props.loc.costMult * discount;
} }
train(stat: string) { train(stat: string): void {
const loc = this.props.loc; const loc = this.props.loc;
this.props.p.startClass(this.calculateCost(), loc.expMult, stat); this.props.p.startClass(this.calculateCost(), loc.expMult, stat);
} }
trainStrength() { trainStrength(): void {
return this.train(CONSTANTS.ClassGymStrength); this.train(CONSTANTS.ClassGymStrength);
} }
trainDefense() { trainDefense(): void {
return this.train(CONSTANTS.ClassGymDefense); this.train(CONSTANTS.ClassGymDefense);
} }
trainDexterity() { trainDexterity(): void {
return this.train(CONSTANTS.ClassGymDexterity); this.train(CONSTANTS.ClassGymDexterity);
} }
trainAgility() { trainAgility(): void {
return this.train(CONSTANTS.ClassGymAgility); this.train(CONSTANTS.ClassGymAgility);
} }
render() { render(): React.ReactNode {
const cost = CONSTANTS.ClassGymBaseCost * this.calculateCost(); const cost = CONSTANTS.ClassGymBaseCost * this.calculateCost();
return ( return (

@ -5,11 +5,9 @@
*/ */
import * as React from "react"; import * as React from "react";
import { CONSTANTS } from "../../Constants";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { getHospitalizationCost } from "../../Hospital/Hospital"; import { getHospitalizationCost } from "../../Hospital/Hospital";
import { numeralWrapper } from "../../ui/numeralFormat";
import { AutoupdatingStdButton } from "../../ui/React/AutoupdatingStdButton"; import { AutoupdatingStdButton } from "../../ui/React/AutoupdatingStdButton";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
@ -27,7 +25,7 @@ export class HospitalLocation extends React.Component<IProps, IState> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -65,7 +63,7 @@ export class HospitalLocation extends React.Component<IProps, IState> {
dialogBoxCreate(<>You were healed to full health! The hospital billed you for {Money(cost)}</>); dialogBoxCreate(<>You were healed to full health! The hospital billed you for {Money(cost)}</>);
} }
render() { render(): React.ReactNode {
const cost = this.getCost(); const cost = this.getCost();
return ( return (

@ -141,7 +141,7 @@ export class LocationRoot extends React.Component<IProps, IState> {
} }
} }
render() { render(): React.ReactNode {
if (this.state.inCity) { if (this.state.inCity) {
return this.renderCity(); return this.renderCity();
} else { } else {

@ -19,7 +19,7 @@ export class SlumsLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -100,7 +100,7 @@ export class SlumsLocation extends React.Component<IProps, any> {
Crimes.Heist.commit(this.props.p); Crimes.Heist.commit(this.props.p);
} }
render() { render(): React.ReactNode {
const shopliftChance = Crimes.Shoplift.successRate(this.props.p); const shopliftChance = Crimes.Shoplift.successRate(this.props.p);
const robStoreChance = Crimes.RobStore.successRate(this.props.p); const robStoreChance = Crimes.RobStore.successRate(this.props.p);
const mugChance = Crimes.Mug.successRate(this.props.p); const mugChance = Crimes.Mug.successRate(this.props.p);

@ -38,7 +38,7 @@ export class SpecialLocation extends React.Component<IProps, IState> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -57,14 +57,14 @@ export class SpecialLocation extends React.Component<IProps, IState> {
/** /**
* Click handler for "Create Corporation" button at Sector-12 City Hall * Click handler for "Create Corporation" button at Sector-12 City Hall
*/ */
createCorporationPopup() { createCorporationPopup(): void {
createStartCorporationPopup(this.props.p); createStartCorporationPopup(this.props.p);
} }
/** /**
* Click handler for Bladeburner button at Sector-12 NSA * Click handler for Bladeburner button at Sector-12 NSA
*/ */
handleBladeburner() { handleBladeburner(): void {
const p = this.props.p; const p = this.props.p;
if (p.inBladeburner()) { if (p.inBladeburner()) {
// Enter Bladeburner division // Enter Bladeburner division
@ -91,7 +91,7 @@ export class SpecialLocation extends React.Component<IProps, IState> {
/** /**
* Click handler for Resleeving button at New Tokyo VitaLife * Click handler for Resleeving button at New Tokyo VitaLife
*/ */
handleResleeving() { handleResleeving(): void {
this.props.engine.loadResleevingContent(); this.props.engine.loadResleevingContent();
} }
@ -130,7 +130,7 @@ export class SpecialLocation extends React.Component<IProps, IState> {
) )
} }
render() { render(): React.ReactNode {
switch (this.props.loc.name) { switch (this.props.loc.name) {
case LocationName.NewTokyoVitaLife: { case LocationName.NewTokyoVitaLife: {
return this.renderResleeving(); return this.renderResleeving();

@ -15,7 +15,6 @@ import { CONSTANTS } from "../../Constants";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { getPurchaseServerCost } from "../../Server/ServerPurchases"; import { getPurchaseServerCost } from "../../Server/ServerPurchases";
import { numeralWrapper } from "../../ui/numeralFormat";
import { StdButtonPurchased } from "../../ui/React/StdButtonPurchased"; import { StdButtonPurchased } from "../../ui/React/StdButtonPurchased";
import { StdButton } from "../../ui/React/StdButton"; import { StdButton } from "../../ui/React/StdButton";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
@ -29,7 +28,7 @@ export class TechVendorLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -45,22 +44,22 @@ export class TechVendorLocation extends React.Component<IProps, any> {
this.purchaseTorRouter = this.purchaseTorRouter.bind(this); this.purchaseTorRouter = this.purchaseTorRouter.bind(this);
} }
createUpgradeHomeCoresPopup() { createUpgradeHomeCoresPopup(): void {
createUpgradeHomeCoresPopup(this.props.p); createUpgradeHomeCoresPopup(this.props.p);
} }
createUpgradeHomeRamPopup() { createUpgradeHomeRamPopup(): void {
createUpgradeHomeRamPopup(this.props.p); createUpgradeHomeRamPopup(this.props.p);
} }
purchaseTorRouter() { purchaseTorRouter(): void {
purchaseTorRouter(this.props.p); purchaseTorRouter(this.props.p);
this.setState({ this.setState({
torPurchased: this.props.p.hasTorRouter(), torPurchased: this.props.p.hasTorRouter(),
}); });
} }
render() { render(): React.ReactNode {
const loc: Location = this.props.loc; const loc: Location = this.props.loc;
const purchaseServerButtons: React.ReactNode[] = []; const purchaseServerButtons: React.ReactNode[] = [];

@ -12,7 +12,6 @@ import { CONSTANTS } from "../../Constants";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { numeralWrapper } from "../../ui/numeralFormat";
import { StdButton } from "../../ui/React/StdButton"; import { StdButton } from "../../ui/React/StdButton";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
@ -25,7 +24,7 @@ export class TravelAgencyLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -33,12 +32,10 @@ export class TravelAgencyLocation extends React.Component<IProps, any> {
this.btnStyle = { display: "block" }; this.btnStyle = { display: "block" };
} }
asciiWorldMap() { asciiWorldMap(): React.ReactNode {
const thisTravelAgencyLocation = this; const LocationLetter = (props: any): JSX.Element => {
if(props.city !== this.props.p.city) {
function LocationLetter(props: any) { return <span className="tooltip" style={{color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px'}} onClick={createTravelPopup.bind(null, props.city, this.props.travel)}>
if(props.city !== thisTravelAgencyLocation.props.p.city) {
return <span className="tooltip" style={{color: 'blue', whiteSpace: 'nowrap', margin: '0px', padding: '0px'}} onClick={createTravelPopup.bind(null, props.city, thisTravelAgencyLocation.props.travel)}>
<span className="tooltiptext">{props.city}</span> <span className="tooltiptext">{props.city}</span>
{props.city[0]} {props.city[0]}
</span> </span>
@ -79,7 +76,7 @@ export class TravelAgencyLocation extends React.Component<IProps, any> {
} }
listWorldMap() { listWorldMap(): React.ReactNode {
const travelBtns: React.ReactNode[] = []; const travelBtns: React.ReactNode[] = [];
for (const key in CityName) { for (const key in CityName) {
const city: CityName = (CityName as any)[key]; const city: CityName = (CityName as any)[key];
@ -108,7 +105,7 @@ export class TravelAgencyLocation extends React.Component<IProps, any> {
) )
} }
render() { render(): React.ReactNode {
if (Settings.DisableASCIIArt) { if (Settings.DisableASCIIArt) {
return this.listWorldMap(); return this.listWorldMap();
} else { } else {

@ -13,7 +13,6 @@ import { getServer } from "../../Server/ServerHelpers";
import { Server } from "../../Server/Server"; import { Server } from "../../Server/Server";
import { SpecialServerIps } from "../../Server/SpecialServerIps"; import { SpecialServerIps } from "../../Server/SpecialServerIps";
import { numeralWrapper } from "../../ui/numeralFormat";
import { StdButton } from "../../ui/React/StdButton"; import { StdButton } from "../../ui/React/StdButton";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";
@ -26,7 +25,7 @@ export class UniversityLocation extends React.Component<IProps, any> {
/** /**
* Stores button styling that sets them all to block display * Stores button styling that sets them all to block display
*/ */
btnStyle: object; btnStyle: any;
constructor(props: IProps) { constructor(props: IProps) {
super(props); super(props);
@ -53,36 +52,36 @@ export class UniversityLocation extends React.Component<IProps, any> {
return this.props.loc.costMult * discount; return this.props.loc.costMult * discount;
} }
take(stat: string) { take(stat: string): void {
const loc = this.props.loc; const loc = this.props.loc;
this.props.p.startClass(this.calculateCost(), loc.expMult, stat); this.props.p.startClass(this.calculateCost(), loc.expMult, stat);
} }
study() { study(): void {
return this.take(CONSTANTS.ClassStudyComputerScience); this.take(CONSTANTS.ClassStudyComputerScience);
} }
dataStructures() { dataStructures(): void {
return this.take(CONSTANTS.ClassDataStructures); this.take(CONSTANTS.ClassDataStructures);
} }
networks() { networks(): void {
return this.take(CONSTANTS.ClassNetworks); this.take(CONSTANTS.ClassNetworks);
} }
algorithms() { algorithms(): void {
return this.take(CONSTANTS.ClassAlgorithms); this.take(CONSTANTS.ClassAlgorithms);
} }
management() { management(): void {
return this.take(CONSTANTS.ClassManagement); this.take(CONSTANTS.ClassManagement);
} }
leadership() { leadership(): void {
return this.take(CONSTANTS.ClassLeadership); this.take(CONSTANTS.ClassLeadership);
} }
render() { render(): React.ReactNode {
const costMult: number = this.calculateCost(); const costMult: number = this.calculateCost();
const dataStructuresCost = CONSTANTS.ClassDataStructuresBaseCost * costMult; const dataStructuresCost = CONSTANTS.ClassDataStructuresBaseCost * costMult;

@ -3,10 +3,6 @@ import { Reviver,
Generic_fromJSON } from "../../utils/JSONReviver"; Generic_fromJSON } from "../../utils/JSONReviver";
export class Message { export class Message {
// Initializes a Message Object from a JSON save state
static fromJSON(value: any): Message {
return Generic_fromJSON(Message, value.data);
}
// Name of Message file // Name of Message file
filename = ""; filename = "";
@ -27,6 +23,12 @@ export class Message {
toJSON(): any { toJSON(): any {
return Generic_toJSON("Message", this); return 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: any): Message {
return Generic_fromJSON(Message, value.data);
}
} }
Reviver.constructors.Message = Message; Reviver.constructors.Message = Message;

@ -1,5 +1,4 @@
import { Message } from "./Message"; import { Message } from "./Message";
import { Augmentatation } from "../Augmentation/Augmentation";
import { Augmentations } from "../Augmentation/Augmentations"; import { Augmentations } from "../Augmentation/Augmentations";
import { AugmentationNames } from "../Augmentation/data/AugmentationNames"; import { AugmentationNames } from "../Augmentation/data/AugmentationNames";
import { Programs } from "../Programs/Programs"; import { Programs } from "../Programs/Programs";

@ -7,7 +7,7 @@ import * as ReactDOM from "react-dom";
let milestonesContainer: HTMLElement | null = null; let milestonesContainer: HTMLElement | null = null;
(function(){ (function(){
function setContainer() { function setContainer(): void {
milestonesContainer = document.getElementById("milestones-container"); milestonesContainer = document.getElementById("milestones-container");
document.removeEventListener("DOMContentLoaded", setContainer); document.removeEventListener("DOMContentLoaded", setContainer);
} }
@ -15,7 +15,7 @@ let milestonesContainer: HTMLElement | null = null;
document.addEventListener("DOMContentLoaded", setContainer); document.addEventListener("DOMContentLoaded", setContainer);
})(); })();
export function displayMilestonesContent() { export function displayMilestonesContent(): void {
if (!routing.isOn(Page.Milestones)) { if (!routing.isOn(Page.Milestones)) {
return; return;
} }

@ -1,5 +1,4 @@
import { Milestone } from "./Milestone"; import { Milestone } from "./Milestone";
import { IMap } from "../types";
import { IPlayer } from "../PersonObjects/IPlayer"; import { IPlayer } from "../PersonObjects/IPlayer";
import { Factions } from "../Faction/Factions"; import { Factions } from "../Faction/Factions";
import { Faction } from "../Faction/Faction"; import { Faction } from "../Faction/Faction";
@ -16,7 +15,7 @@ function allFactionAugs(p: IPlayer, f: Faction): boolean {
export const Milestones: Milestone[] = [ export const Milestones: Milestone[] = [
{ {
title: "Gain root access on CSEC", title: "Gain root access on CSEC",
fulfilled: (p: IPlayer) => { fulfilled: (): boolean => {
const server = GetServerByHostname("CSEC"); const server = GetServerByHostname("CSEC");
if(!server || !server.hasOwnProperty('hasAdminRights')) return false; if(!server || !server.hasOwnProperty('hasAdminRights')) return false;
return (server as any).hasAdminRights; return (server as any).hasAdminRights;
@ -24,7 +23,7 @@ export const Milestones: Milestone[] = [
}, },
{ {
title: "Install the backdoor on CSEC", title: "Install the backdoor on CSEC",
fulfilled: (p: IPlayer) => { fulfilled: (): boolean => {
const server = GetServerByHostname("CSEC"); const server = GetServerByHostname("CSEC");
if(!server || !server.hasOwnProperty('backdoorInstalled')) return false; if(!server || !server.hasOwnProperty('backdoorInstalled')) return false;
return (server as any).backdoorInstalled; return (server as any).backdoorInstalled;
@ -32,67 +31,67 @@ export const Milestones: Milestone[] = [
}, },
{ {
title: "Join the faction hinted at in j1.msg", title: "Join the faction hinted at in j1.msg",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.factions.includes("CyberSec"); return p.factions.includes("CyberSec");
}, },
}, },
{ {
title: "Install all the Augmentations from CSEC", title: "Install all the Augmentations from CSEC",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return allFactionAugs(p, Factions["CyberSec"]); return allFactionAugs(p, Factions["CyberSec"]);
}, },
}, },
{ {
title: "Join the faction hinted at in j2.msg", title: "Join the faction hinted at in j2.msg",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.factions.includes("NiteSec"); return p.factions.includes("NiteSec");
}, },
}, },
{ {
title: "Install all the Augmentations from NiteSec", title: "Install all the Augmentations from NiteSec",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return allFactionAugs(p, Factions["NiteSec"]); return allFactionAugs(p, Factions["NiteSec"]);
}, },
}, },
{ {
title: "Join the faction hinted at in j3.msg", title: "Join the faction hinted at in j3.msg",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.factions.includes("The Black Hand"); return p.factions.includes("The Black Hand");
}, },
}, },
{ {
title: "Install all the Augmentations from The Black Hand", title: "Install all the Augmentations from The Black Hand",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return allFactionAugs(p, Factions["The Black Hand"]); return allFactionAugs(p, Factions["The Black Hand"]);
}, },
}, },
{ {
title: "Join the faction hinted at in j4.msg", title: "Join the faction hinted at in j4.msg",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.factions.includes("BitRunners"); return p.factions.includes("BitRunners");
}, },
}, },
{ {
title: "Install all the Augmentations from BitRunners", title: "Install all the Augmentations from BitRunners",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return allFactionAugs(p, Factions["BitRunners"]); return allFactionAugs(p, Factions["BitRunners"]);
}, },
}, },
{ {
title: "Join the final faction", title: "Join the final faction",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.factions.includes("Daedalus"); return p.factions.includes("Daedalus");
}, },
}, },
{ {
title: "Install the special Augmentation from Daedalus", title: "Install the special Augmentation from Daedalus",
fulfilled: (p: IPlayer) => { fulfilled: (p: IPlayer): boolean => {
return p.augmentations.some(aug => aug.name == "The Red Pill") return p.augmentations.some(aug => aug.name == "The Red Pill")
}, },
}, },
{ {
title: "Install the final backdoor and free yourself.", title: "Install the final backdoor and free yourself.",
fulfilled: () => { fulfilled: (): boolean => {
return false; return false;
}, },
}, },

@ -16,7 +16,7 @@ function highestMilestone(p: IPlayer, milestones: Milestone[]): number {
return n; return n;
} }
export function Root(props: IProps) { export function Root(props: IProps): JSX.Element {
const n = highestMilestone(props.player, Milestones); const n = highestMilestone(props.player, Milestones);
const milestones = Milestones.map((milestone: Milestone, i: number) => { const milestones = Milestones.map((milestone: Milestone, i: number) => {
if (i<=n+1) { if (i<=n+1) {

@ -5,7 +5,6 @@ import { Player } from "./Player";
import { dialogBoxCreate } from "../utils/DialogBox"; import { dialogBoxCreate } from "../utils/DialogBox";
import { formatNumber } from "../utils/StringHelperFunctions"; import { formatNumber } from "../utils/StringHelperFunctions";
import { numeralWrapper } from "./ui/numeralFormat";
import { Reputation } from "./ui/React/Reputation"; import { Reputation } from "./ui/React/Reputation";
import { addOffset } from "../utils/helpers/addOffset"; import { addOffset } from "../utils/helpers/addOffset";
@ -14,8 +13,6 @@ import { isString } from "../utils/helpers/isString";
import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners";
import jsplumb from "jsplumb";
import React from "react"; import React from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
@ -783,11 +780,11 @@ HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
return; return;
} }
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; let id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt"); let txtEl = document.getElementById(id + "-txt");
// Set node classes based on type // Set node classes based on type
var txt; let txt;
switch (nodeObj.type) { switch (nodeObj.type) {
case NodeTypes.Core: case NodeTypes.Core:
txt = "CPU Core<br>" + "HP: " + txt = "CPU Core<br>" + "HP: " +
@ -901,14 +898,13 @@ HackingMission.prototype.configurePlayerNodeElement = function(el) {
if (nodeObj == null) {console.error("Failed getting Node object");} if (nodeObj == null) {console.error("Failed getting Node object");}
// Add event listener // Add event listener
var self = this; const selectNodeWrapper = () => {
function selectNodeWrapper() { selectNode(this, el);
selectNode(self, el);
} }
el.addEventListener("click", selectNodeWrapper); el.addEventListener("click", selectNodeWrapper);
function multiselectNodeWrapper() { const multiselectNodeWrapper = () => {
multiselectNode(self, el); multiselectNode(this, el);
} }
el.addEventListener("dblclick", multiselectNodeWrapper); el.addEventListener("dblclick", multiselectNodeWrapper);
@ -1021,7 +1017,7 @@ HackingMission.prototype.initJsPlumb = function() {
} }
// Clicking a connection drops it // Clicking a connection drops it
instance.bind("click", (conn, originalEvent) => { instance.bind("click", (conn) => {
// Cannot drop enemy's connections // Cannot drop enemy's connections
const sourceNode = this.getNodeFromElement(conn.source); const sourceNode = this.getNodeFromElement(conn.source);
if (sourceNode.enmyCtrl) { return; } if (sourceNode.enmyCtrl) { return; }
@ -1051,7 +1047,7 @@ HackingMission.prototype.initJsPlumb = function() {
}); });
// Detach Connection events // Detach Connection events
instance.bind("connectionDetached", (info, originalEvent) => { instance.bind("connectionDetached", (info) => {
var sourceNode = this.getNodeFromElement(info.source); var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = null; sourceNode.conn = null;
var targetNode = this.getNodeFromElement(info.target); var targetNode = this.getNodeFromElement(info.target);

@ -32,6 +32,7 @@ export class Environment {
* Finds the scope where the variable with the given name is defined * Finds the scope where the variable with the given name is defined
*/ */
lookup(name: string): Environment | null { lookup(name: string): Environment | null {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let scope: Environment | null = this; let scope: Environment | null = this;
while (scope) { while (scope) {
if (Object.prototype.hasOwnProperty.call(scope.vars, name)) { if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
@ -53,7 +54,8 @@ export class Environment {
} }
//Sets the value of a variable in any scope //Sets the value of a variable in any scope
set(name: string, value: any) { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
set(name: string, value: any): any {
const scope = this.lookup(name); const scope = this.lookup(name);
//If scope has a value, then this variable is already set in a higher scope, so //If scope has a value, then this variable is already set in a higher scope, so
@ -66,7 +68,8 @@ export class Environment {
} }
//Creates (or overwrites) a variable in the current scope //Creates (or overwrites) a variable in the current scope
def(name: string, value: any) { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
def(name: string, value: any): any {
return this.vars[name] = value; return this.vars[name] = value;
} }
} }

@ -106,7 +106,7 @@ export class WorkerScript {
*/ */
serverIp: string; serverIp: string;
constructor(runningScriptObj: RunningScript, pid: number, nsFuncsGenerator?: (ws: WorkerScript) => object) { constructor(runningScriptObj: RunningScript, pid: number, nsFuncsGenerator?: (ws: WorkerScript) => any) {
this.name = runningScriptObj.filename; this.name = runningScriptObj.filename;
this.serverIp = runningScriptObj.server; this.serverIp = runningScriptObj.server;
@ -146,8 +146,10 @@ export class WorkerScript {
/** /**
* Returns the Server on which this script is running * Returns the Server on which this script is running
*/ */
getServer() { getServer(): BaseServer {
return AllServers[this.serverIp]; const server = AllServers[this.serverIp];
if(server == null) throw new Error(`Script ${this.name} pid ${this.pid} is running on non-existent server?`);
return server;
} }
/** /**

@ -124,7 +124,7 @@ function removeWorkerScript(workerScript: WorkerScript, rerenderUi=true): void {
* timed, blocked operation (like hack(), sleep(), etc.). This allows scripts to * 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 * be killed immediately even if they're in the middle of one of those long operations
*/ */
function killNetscriptDelay(workerScript: WorkerScript) { function killNetscriptDelay(workerScript: WorkerScript): void {
if (workerScript instanceof WorkerScript) { if (workerScript instanceof WorkerScript) {
if (workerScript.delay) { if (workerScript.delay) {
clearTimeout(workerScript.delay); clearTimeout(workerScript.delay);

Some files were not shown because too many files have changed in this diff Show More