diff --git a/src/Achievements/Achievements.ts b/src/Achievements/Achievements.ts index 2085a031e..acbf35dd8 100644 --- a/src/Achievements/Achievements.ts +++ b/src/Achievements/Achievements.ts @@ -347,18 +347,18 @@ export const achievements: IMap = { FIRST_HACKNET_NODE: { ...achievementData["FIRST_HACKNET_NODE"], Icon: "node", - Condition: () => !hasHacknetServers(Player) && Player.hacknetNodes.length > 0, + Condition: () => !hasHacknetServers() && Player.hacknetNodes.length > 0, }, "30_HACKNET_NODE": { ...achievementData["30_HACKNET_NODE"], Icon: "hacknet-all", - Condition: () => !hasHacknetServers(Player) && Player.hacknetNodes.length >= 30, + Condition: () => !hasHacknetServers() && Player.hacknetNodes.length >= 30, }, MAX_HACKNET_NODE: { ...achievementData["MAX_HACKNET_NODE"], Icon: "hacknet-max", Condition: (): boolean => { - if (hasHacknetServers(Player)) return false; + if (hasHacknetServers()) return false; for (const h of Player.hacknetNodes) { if (!(h instanceof HacknetNode)) return false; if ( @@ -374,7 +374,7 @@ export const achievements: IMap = { HACKNET_NODE_10M: { ...achievementData["HACKNET_NODE_10M"], Icon: "hacknet-10m", - Condition: () => !hasHacknetServers(Player) && Player.moneySourceB.hacknet >= 10e6, + Condition: () => !hasHacknetServers() && Player.moneySourceB.hacknet >= 10e6, }, REPUTATION_10M: { ...achievementData["REPUTATION_10M"], @@ -515,14 +515,14 @@ export const achievements: IMap = { ...achievementData["FIRST_HACKNET_SERVER"], Icon: "HASHNET", Visible: () => hasAccessToSF(Player, 9), - Condition: () => hasHacknetServers(Player) && Player.hacknetNodes.length > 0, + Condition: () => hasHacknetServers() && Player.hacknetNodes.length > 0, AdditionalUnlock: [achievementData.FIRST_HACKNET_NODE.ID], }, ALL_HACKNET_SERVER: { ...achievementData["ALL_HACKNET_SERVER"], Icon: "HASHNETALL", Visible: () => hasAccessToSF(Player, 9), - Condition: () => hasHacknetServers(Player) && Player.hacknetNodes.length === HacknetServerConstants.MaxServers, + Condition: () => hasHacknetServers() && Player.hacknetNodes.length === HacknetServerConstants.MaxServers, AdditionalUnlock: [achievementData["30_HACKNET_NODE"].ID], }, MAX_HACKNET_SERVER: { @@ -530,7 +530,7 @@ export const achievements: IMap = { Icon: "HASHNETALL", Visible: () => hasAccessToSF(Player, 9), Condition: (): boolean => { - if (!hasHacknetServers(Player)) return false; + if (!hasHacknetServers()) return false; for (const h of Player.hacknetNodes) { if (typeof h !== "string") return false; const hs = GetServer(h); @@ -551,7 +551,7 @@ export const achievements: IMap = { ...achievementData["HACKNET_SERVER_1B"], Icon: "HASHNETMONEY", Visible: () => hasAccessToSF(Player, 9), - Condition: () => hasHacknetServers(Player) && Player.moneySourceB.hacknet >= 1e9, + Condition: () => hasHacknetServers() && Player.moneySourceB.hacknet >= 1e9, AdditionalUnlock: [achievementData.HACKNET_NODE_10M.ID], }, MAX_CACHE: { @@ -559,7 +559,7 @@ export const achievements: IMap = { Icon: "HASHNETCAP", Visible: () => hasAccessToSF(Player, 9), Condition: () => - hasHacknetServers(Player) && + hasHacknetServers() && Player.hashManager.hashes === Player.hashManager.capacity && Player.hashManager.capacity > 0, }, diff --git a/src/Augmentation/Augmentation.tsx b/src/Augmentation/Augmentation.tsx index e1154bb5c..9dafe06e0 100644 --- a/src/Augmentation/Augmentation.tsx +++ b/src/Augmentation/Augmentation.tsx @@ -8,7 +8,7 @@ import { Money } from "../ui/React/Money"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../utils/JSONReviver"; import { FactionNames } from "../Faction/data/FactionNames"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { AugmentationNames } from "./data/AugmentationNames"; import { CONSTANTS } from "../Constants"; import { StaticAugmentations } from "./StaticAugmentations"; @@ -531,26 +531,26 @@ export class Augmentation { } } - getCost(player: IPlayer): AugmentationCosts { + getCost(): AugmentationCosts { const augmentationReference = StaticAugmentations[this.name]; let moneyCost = augmentationReference.baseCost; let repCost = augmentationReference.baseRepRequirement; if (augmentationReference.name === AugmentationNames.NeuroFluxGovernor) { - let nextLevel = this.getLevel(player); + let nextLevel = this.getLevel(); --nextLevel; const multiplier = Math.pow(CONSTANTS.NeuroFluxGovernorLevelMult, nextLevel); repCost = augmentationReference.baseRepRequirement * multiplier * BitNodeMultipliers.AugmentationRepCost; moneyCost = augmentationReference.baseCost * multiplier * BitNodeMultipliers.AugmentationMoneyCost; - for (let i = 0; i < player.queuedAugmentations.length; ++i) { + for (let i = 0; i < Player.queuedAugmentations.length; ++i) { moneyCost *= getBaseAugmentationPriceMultiplier(); } } else if (augmentationReference.factions.includes(FactionNames.ShadowsOfAnarchy)) { const soaAugmentationNames = initSoAAugmentations().map((augmentation) => augmentation.name); const soaMultiplier = Math.pow( CONSTANTS.SoACostMult, - soaAugmentationNames.filter((augmentationName) => player.hasAugmentation(augmentationName)).length, + soaAugmentationNames.filter((augmentationName) => Player.hasAugmentation(augmentationName)).length, ); moneyCost = augmentationReference.baseCost * soaMultiplier; if (soaAugmentationNames.find((augmentationName) => augmentationName === augmentationReference.name)) { @@ -566,19 +566,19 @@ export class Augmentation { return { moneyCost, repCost }; } - getLevel(player: IPlayer): number { + getLevel(): number { // Get current Neuroflux level based on Player's augmentations if (this.name === AugmentationNames.NeuroFluxGovernor) { let currLevel = 0; - for (let i = 0; i < player.augmentations.length; ++i) { - if (player.augmentations[i].name === AugmentationNames.NeuroFluxGovernor) { - currLevel = player.augmentations[i].level; + for (let i = 0; i < Player.augmentations.length; ++i) { + if (Player.augmentations[i].name === AugmentationNames.NeuroFluxGovernor) { + currLevel = Player.augmentations[i].level; } } // Account for purchased but uninstalled Augmentations - for (let i = 0; i < player.queuedAugmentations.length; ++i) { - if (player.queuedAugmentations[i].name == AugmentationNames.NeuroFluxGovernor) { + for (let i = 0; i < Player.queuedAugmentations.length; ++i) { + if (Player.queuedAugmentations[i].name == AugmentationNames.NeuroFluxGovernor) { ++currLevel; } } diff --git a/src/Augmentation/ui/AugmentationsRoot.tsx b/src/Augmentation/ui/AugmentationsRoot.tsx index 033ac95d6..f5d024c86 100644 --- a/src/Augmentation/ui/AugmentationsRoot.tsx +++ b/src/Augmentation/ui/AugmentationsRoot.tsx @@ -20,7 +20,7 @@ import Paper from "@mui/material/Paper"; import Container from "@mui/material/Container"; import { Settings } from "../../Settings/Settings"; import { ConfirmationModal } from "../../ui/React/ConfirmationModal"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { AugmentationNames } from "../data/AugmentationNames"; import { StaticAugmentations } from "../StaticAugmentations"; import { CONSTANTS } from "../../Constants"; @@ -29,12 +29,8 @@ import { Info } from "@mui/icons-material"; import { Link } from "@mui/material"; import { AlertEvents } from "../../ui/React/AlertManager"; -interface NFGDisplayProps { - player: IPlayer; -} - -const NeuroFluxDisplay = ({ player }: NFGDisplayProps): React.ReactElement => { - const level = player.augmentations.find((e) => e.name === AugmentationNames.NeuroFluxGovernor)?.level ?? 0; +const NeuroFluxDisplay = (): React.ReactElement => { + const level = Player.augmentations.find((e) => e.name === AugmentationNames.NeuroFluxGovernor)?.level ?? 0; const openBloodDonation = () => { AlertEvents.emit( @@ -67,18 +63,14 @@ const NeuroFluxDisplay = ({ player }: NFGDisplayProps): React.ReactElement => { ); }; -interface EntropyDisplayProps { - player: IPlayer; -} - -const EntropyDisplay = ({ player }: EntropyDisplayProps): React.ReactElement => { - return player.entropy > 0 ? ( +const EntropyDisplay = (): React.ReactElement => { + return Player.entropy > 0 ? ( - Entropy Virus - Level {player.entropy} + Entropy Virus - Level {Player.entropy} - All multipliers decreased by: {formatNumber((1 - CONSTANTS.EntropyEffect ** player.entropy) * 100, 3)}% + All multipliers decreased by: {formatNumber((1 - CONSTANTS.EntropyEffect ** Player.entropy) * 100, 3)}% (multiplicative) @@ -222,8 +214,8 @@ export function AugmentationsRoot(props: IProps): React.ReactElement { gap: 1, }} > - - + + diff --git a/src/Augmentation/ui/PurchasableAugmentations.tsx b/src/Augmentation/ui/PurchasableAugmentations.tsx index 27a8f927b..4b97c261e 100644 --- a/src/Augmentation/ui/PurchasableAugmentations.tsx +++ b/src/Augmentation/ui/PurchasableAugmentations.tsx @@ -6,7 +6,7 @@ import { CheckBox, CheckBoxOutlineBlank, CheckCircle, NewReleases, Report } from import { Box, Button, Container, Paper, Tooltip, Typography } from "@mui/material"; import React, { useState } from "react"; import { Faction } from "../../Faction/Faction"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Settings } from "../../Settings/Settings"; import { numeralWrapper } from "../../ui/numeralFormat"; import { Augmentation } from "../Augmentation"; @@ -15,12 +15,11 @@ import { StaticAugmentations } from "../StaticAugmentations"; import { PurchaseAugmentationModal } from "./PurchaseAugmentationModal"; interface IPreReqsProps { - player: IPlayer; aug: Augmentation; } const PreReqs = (props: IPreReqsProps): React.ReactElement => { - const ownedPreReqs = props.aug.prereqs.filter((aug) => props.player.hasAugmentation(aug)); + const ownedPreReqs = props.aug.prereqs.filter((aug) => Player.hasAugmentation(aug)); const hasPreReqs = props.aug.prereqs.length > 0 && ownedPreReqs.length === props.aug.prereqs.length; return ( @@ -32,7 +31,7 @@ const PreReqs = (props: IPreReqsProps): React.ReactElement => { {props.aug.prereqs.map((preAug) => ( { }; interface IExclusiveProps { - player: IPlayer; aug: Augmentation; } @@ -85,12 +83,12 @@ const Exclusive = (props: IExclusiveProps): React.ReactElement => {
  • {props.aug.factions[0]} faction
  • - {props.player.isAwareOfGang() && !props.aug.isSpecial && ( + {Player.isAwareOfGang() && !props.aug.isSpecial && (
  • Certain gangs
  • )} - {props.player.canAccessGrafting() && + {Player.canAccessGrafting() && !props.aug.isSpecial && props.aug.name !== AugmentationNames.TheRedPill && (
  • @@ -130,10 +128,9 @@ const Requirement = (props: IReqProps): React.ReactElement => { interface IPurchasableAugsProps { augNames: string[]; ownedAugNames: string[]; - player: IPlayer; - canPurchase: (player: IPlayer, aug: Augmentation) => boolean; - purchaseAugmentation: (player: IPlayer, aug: Augmentation, showModal: (open: boolean) => void) => void; + canPurchase: (aug: Augmentation) => boolean; + purchaseAugmentation: (aug: Augmentation, showModal: (open: boolean) => void) => void; rep?: number; sleeveAugs?: boolean; @@ -167,7 +164,7 @@ export function PurchasableAugmentation(props: IPurchasableAugProps): React.Reac const [open, setOpen] = useState(false); const aug = StaticAugmentations[props.augName]; - const augCosts = aug.getCost(props.parent.player); + const augCosts = aug.getCost(); const cost = props.parent.sleeveAugs ? aug.baseCost : augCosts.moneyCost; const repCost = augCosts.repCost; const info = typeof aug.info === "string" ? {aug.info} : aug.info; @@ -195,11 +192,11 @@ export function PurchasableAugmentation(props: IPurchasableAugProps): React.Reac ) : ( - + )} ); diff --git a/src/Bladeburner/ui/BladeburnerRoot.tsx b/src/Bladeburner/ui/BladeburnerRoot.tsx index 593874a62..ca19f4c93 100644 --- a/src/Bladeburner/ui/BladeburnerRoot.tsx +++ b/src/Bladeburner/ui/BladeburnerRoot.tsx @@ -24,11 +24,11 @@ export function BladeburnerRoot(): React.ReactElement { return ( - - + + - + ); } diff --git a/src/Bladeburner/ui/Console.tsx b/src/Bladeburner/ui/Console.tsx index 8a6a82935..bcc07b447 100644 --- a/src/Bladeburner/ui/Console.tsx +++ b/src/Bladeburner/ui/Console.tsx @@ -2,7 +2,6 @@ import React, { useState, useRef, useEffect } from "react"; import { IBladeburner } from "../IBladeburner"; import { KEY } from "../../utils/helpers/keyCodes"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import Paper from "@mui/material/Paper"; import List from "@mui/material/List"; import ListItem from "@mui/material/ListItem"; @@ -50,7 +49,6 @@ function Line(props: ILineProps): React.ReactElement { interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function Console(props: IProps): React.ReactElement { @@ -81,7 +79,7 @@ export function Console(props: IProps): React.ReactElement { event.preventDefault(); if (command.length > 0) { props.bladeburner.postToConsole("> " + command); - props.bladeburner.executeConsoleCommands(props.player, command); + props.bladeburner.executeConsoleCommands(command); setConsoleHistoryIndex(props.bladeburner.consoleHistory.length); setCommand(""); } diff --git a/src/Bladeburner/ui/ContractElem.tsx b/src/Bladeburner/ui/ContractElem.tsx index 5edf04842..376236ca7 100644 --- a/src/Bladeburner/ui/ContractElem.tsx +++ b/src/Bladeburner/ui/ContractElem.tsx @@ -5,7 +5,7 @@ import { formatNumber, convertTimeMsToTimeElapsedString } from "../../utils/Stri import { Contracts } from "../data/Contracts"; import { IBladeburner } from "../IBladeburner"; import { IAction } from "../IAction"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { SuccessChance } from "./SuccessChance"; import { CopyableText } from "../../ui/React/CopyableText"; import { ActionLevel } from "./ActionLevel"; @@ -17,7 +17,6 @@ import Paper from "@mui/material/Paper"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; action: IAction; } @@ -32,7 +31,7 @@ export function ContractElem(props: IProps): React.ReactElement { props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete, ); - const actionTime = props.action.getActionTime(props.bladeburner, props.player); + const actionTime = props.action.getActionTime(props.bladeburner, Player); const actionData = Contracts[props.action.name]; if (actionData === undefined) { diff --git a/src/Bladeburner/ui/ContractList.tsx b/src/Bladeburner/ui/ContractList.tsx index 7bd24c53b..499a437fe 100644 --- a/src/Bladeburner/ui/ContractList.tsx +++ b/src/Bladeburner/ui/ContractList.tsx @@ -1,11 +1,9 @@ import React from "react"; import { ContractElem } from "./ContractElem"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function ContractList(props: IProps): React.ReactElement { @@ -14,7 +12,7 @@ export function ContractList(props: IProps): React.ReactElement { return ( <> {names.map((name: string) => ( - + ))} ); diff --git a/src/Bladeburner/ui/ContractPage.tsx b/src/Bladeburner/ui/ContractPage.tsx index 9a3e96a6d..0af07e41c 100644 --- a/src/Bladeburner/ui/ContractPage.tsx +++ b/src/Bladeburner/ui/ContractPage.tsx @@ -1,12 +1,10 @@ import * as React from "react"; import { ContractList } from "./ContractList"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import Typography from "@mui/material/Typography"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function ContractPage(props: IProps): React.ReactElement { @@ -20,7 +18,7 @@ export function ContractPage(props: IProps): React.ReactElement { You can unlock higher-level contracts by successfully completing them. Higher-level contracts are more difficult, but grant more rank, experience, and money. - + ); } diff --git a/src/Bladeburner/ui/GeneralActionElem.tsx b/src/Bladeburner/ui/GeneralActionElem.tsx index b064b298d..09b1de249 100644 --- a/src/Bladeburner/ui/GeneralActionElem.tsx +++ b/src/Bladeburner/ui/GeneralActionElem.tsx @@ -5,7 +5,7 @@ import { formatNumber, convertTimeMsToTimeElapsedString } from "../../utils/Stri import { IBladeburner } from "../IBladeburner"; import { IAction } from "../IAction"; import { GeneralActions } from "../data/GeneralActions"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { CopyableText } from "../../ui/React/CopyableText"; import { StartButton } from "./StartButton"; @@ -16,7 +16,6 @@ import Paper from "@mui/material/Paper"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; action: IAction; } @@ -40,13 +39,13 @@ export function GeneralActionElem(props: IProps): React.ReactElement { case "Incite Violence": return 60; case "Recruitment": - return props.bladeburner.getRecruitmentTime(props.player); + return props.bladeburner.getRecruitmentTime(Player); } return -1; // dead code })(); const successChance = props.action.name === "Recruitment" - ? Math.max(0, Math.min(props.bladeburner.getRecruitmentSuccessChance(props.player), 1)) + ? Math.max(0, Math.min(props.bladeburner.getRecruitmentSuccessChance(Player), 1)) : -1; const actionData = GeneralActions[props.action.name]; diff --git a/src/Bladeburner/ui/GeneralActionList.tsx b/src/Bladeburner/ui/GeneralActionList.tsx index 5693d4925..27e52fbc9 100644 --- a/src/Bladeburner/ui/GeneralActionList.tsx +++ b/src/Bladeburner/ui/GeneralActionList.tsx @@ -3,11 +3,9 @@ import { GeneralActionElem } from "./GeneralActionElem"; import { Action } from "../Action"; import { GeneralActions } from "../GeneralActions"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function GeneralActionList(props: IProps): React.ReactElement { @@ -20,7 +18,7 @@ export function GeneralActionList(props: IProps): React.ReactElement { return ( <> {actions.map((action: Action) => ( - + ))} ); diff --git a/src/Bladeburner/ui/GeneralActionPage.tsx b/src/Bladeburner/ui/GeneralActionPage.tsx index 9893f210c..10d27a86d 100644 --- a/src/Bladeburner/ui/GeneralActionPage.tsx +++ b/src/Bladeburner/ui/GeneralActionPage.tsx @@ -1,19 +1,17 @@ import * as React from "react"; import { GeneralActionList } from "./GeneralActionList"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import Typography from "@mui/material/Typography"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function GeneralActionPage(props: IProps): React.ReactElement { return ( <> These are generic actions that will assist you in your Bladeburner duties. - + ); } diff --git a/src/Bladeburner/ui/OperationElem.tsx b/src/Bladeburner/ui/OperationElem.tsx index e217e4225..ea39d68d6 100644 --- a/src/Bladeburner/ui/OperationElem.tsx +++ b/src/Bladeburner/ui/OperationElem.tsx @@ -10,7 +10,7 @@ import { TeamSizeButton } from "./TeamSizeButton"; import { IBladeburner } from "../IBladeburner"; import { Operation } from "../Operation"; import { Operations } from "../data/Operations"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { CopyableText } from "../../ui/React/CopyableText"; import Typography from "@mui/material/Typography"; @@ -18,7 +18,6 @@ import Paper from "@mui/material/Paper"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; action: Operation; } @@ -33,7 +32,7 @@ export function OperationElem(props: IProps): React.ReactElement { props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete, ); - const actionTime = props.action.getActionTime(props.bladeburner, props.player); + const actionTime = props.action.getActionTime(props.bladeburner, Player); const actionData = Operations[props.action.name]; if (actionData === undefined) { diff --git a/src/Bladeburner/ui/OperationList.tsx b/src/Bladeburner/ui/OperationList.tsx index e18b8cdc4..eacb779bc 100644 --- a/src/Bladeburner/ui/OperationList.tsx +++ b/src/Bladeburner/ui/OperationList.tsx @@ -1,11 +1,9 @@ import React from "react"; import { OperationElem } from "./OperationElem"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function OperationList(props: IProps): React.ReactElement { @@ -14,7 +12,7 @@ export function OperationList(props: IProps): React.ReactElement { return ( <> {names.map((name: string) => ( - + ))} ); diff --git a/src/Bladeburner/ui/OperationPage.tsx b/src/Bladeburner/ui/OperationPage.tsx index 4b5b0a261..3557a8867 100644 --- a/src/Bladeburner/ui/OperationPage.tsx +++ b/src/Bladeburner/ui/OperationPage.tsx @@ -1,12 +1,10 @@ import * as React from "react"; import { OperationList } from "./OperationList"; import { IBladeburner } from "../IBladeburner"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import Typography from "@mui/material/Typography"; interface IProps { bladeburner: IBladeburner; - player: IPlayer; } export function OperationPage(props: IProps): React.ReactElement { @@ -29,7 +27,7 @@ export function OperationPage(props: IProps): React.ReactElement { You can unlock higher-level operations by successfully completing them. Higher-level operations are more difficult, but grant more rank and experience. - + ); } diff --git a/src/Bladeburner/ui/StartButton.tsx b/src/Bladeburner/ui/StartButton.tsx index 18f30b869..2bbedb947 100644 --- a/src/Bladeburner/ui/StartButton.tsx +++ b/src/Bladeburner/ui/StartButton.tsx @@ -34,7 +34,7 @@ export function StartButton(props: IProps): React.ReactElement { props.bladeburner.action.type = props.type; props.bladeburner.action.name = props.name; if (!player.hasAugmentation(AugmentationNames.BladesSimulacrum, true)) player.finishWork(true); - props.bladeburner.startAction(player, props.bladeburner.action); + props.bladeburner.startAction(props.bladeburner.action); props.rerender(); } diff --git a/src/Bladeburner/ui/Stats.tsx b/src/Bladeburner/ui/Stats.tsx index 477852b61..a9d1d0930 100644 --- a/src/Bladeburner/ui/Stats.tsx +++ b/src/Bladeburner/ui/Stats.tsx @@ -1,11 +1,11 @@ import React, { useState, useEffect } from "react"; import { formatNumber, convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFunctions"; import { BladeburnerConstants } from "../data/Constants"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Money } from "../../ui/React/Money"; import { numeralWrapper } from "../../ui/numeralFormat"; import { Factions } from "../../Faction/Factions"; -import { IRouter } from "../../ui/Router"; +import { Router } from "../../ui/GameRoot"; import { joinFaction } from "../../Faction/FactionHelpers"; import { IBladeburner } from "../IBladeburner"; @@ -19,8 +19,6 @@ import { FactionNames } from "../../Faction/data/FactionNames"; interface IProps { bladeburner: IBladeburner; - router: IRouter; - player: IPlayer; } export function Stats(props: IProps): React.ReactElement { @@ -40,7 +38,7 @@ export function Stats(props: IProps): React.ReactElement { joinFaction(faction); } - props.router.toFaction(faction); + Router.toFaction(faction); } return ( @@ -170,13 +168,13 @@ export function Stats(props: IProps): React.ReactElement { Skill Points: {formatNumber(props.bladeburner.skillPoints, 0)}
    - Aug. Success Chance mult: {formatNumber(props.player.mults.bladeburner_success_chance * 100, 1)}% + Aug. Success Chance mult: {formatNumber(Player.mults.bladeburner_success_chance * 100, 1)}%
    - Aug. Max Stamina mult: {formatNumber(props.player.mults.bladeburner_max_stamina * 100, 1)}% + Aug. Max Stamina mult: {formatNumber(Player.mults.bladeburner_max_stamina * 100, 1)}%
    - Aug. Stamina Gain mult: {formatNumber(props.player.mults.bladeburner_stamina_gain * 100, 1)}% + Aug. Stamina Gain mult: {formatNumber(Player.mults.bladeburner_stamina_gain * 100, 1)}%
    - Aug. Field Analysis mult: {formatNumber(props.player.mults.bladeburner_analysis * 100, 1)}% + Aug. Field Analysis mult: {formatNumber(Player.mults.bladeburner_analysis * 100, 1)}%
    diff --git a/src/Casino/Blackjack.tsx b/src/Casino/Blackjack.tsx index 542989e0d..54eb13b85 100644 --- a/src/Casino/Blackjack.tsx +++ b/src/Casino/Blackjack.tsx @@ -1,8 +1,8 @@ import * as React from "react"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { Money } from "../ui/React/Money"; -import { Game, reachedLimit } from "./Game"; +import { win, reachedLimit } from "./Game"; import { Deck } from "./CardDeck/Deck"; import { Hand } from "./CardDeck/Hand"; import { InputAdornment } from "@mui/material"; @@ -24,10 +24,6 @@ enum Result { Tie = "Push! (Tie)", } -type Props = { - p: IPlayer; -}; - type State = { playerHand: Hand; dealerHand: Hand; @@ -40,11 +36,11 @@ type State = { wagerInvalidHelperText: string; }; -export class Blackjack extends Game { +export class Blackjack extends React.Component<{},State> { deck: Deck; - constructor(props: Props) { - super(props); + constructor() { + super({}); this.deck = new Deck(DECK_COUNT); @@ -64,20 +60,19 @@ export class Blackjack extends Game { } canStartGame = (): boolean => { - const { p } = this.props; const { bet } = this.state; - return p.canAfford(bet); + return Player.canAfford(bet); }; startGame = (): void => { - if (!this.canStartGame() || reachedLimit(this.props.p)) { + if (!this.canStartGame() || reachedLimit()) { return; } // Take money from player right away so that player's dont just "leave" to avoid the loss (I mean they could // always reload without saving but w.e) TODO: Save/Restore the RNG state to limit the value of save-scumming. - this.props.p.loseMoney(this.state.bet, "casino"); + win(-this.state.bet); const playerHand = new Hand([this.deck.safeDrawCard(), this.deck.safeDrawCard()]); const dealerHand = new Hand([this.deck.safeDrawCard(), this.deck.safeDrawCard()]); @@ -230,7 +225,7 @@ export class Blackjack extends Game { : (() => { throw new Error(`Unexpected result: ${result}`); })(); // This can't happen, right? - this.win(this.props.p, gains); + win(gains); this.setState({ gameInProgress: false, result, @@ -239,7 +234,6 @@ export class Blackjack extends Game { }; wagerOnChange = (event: React.ChangeEvent): void => { - const { p } = this.props; const betInput = event.target.value; const wager = Math.round(parseFloat(betInput)); if (isNaN(wager)) { @@ -263,7 +257,7 @@ export class Blackjack extends Game { wagerInvalid: true, wagerInvalidHelperText: "Exceeds max bet", }); - } else if (!p.canAfford(wager)) { + } else if (!Player.canAfford(wager)) { this.setState({ bet: 0, betInput, diff --git a/src/Casino/CoinFlip.tsx b/src/Casino/CoinFlip.tsx index 17b09488c..32fdae274 100644 --- a/src/Casino/CoinFlip.tsx +++ b/src/Casino/CoinFlip.tsx @@ -5,7 +5,6 @@ */ import React, { useState } from "react"; -import { IPlayer } from "../PersonObjects/IPlayer"; import { BadRNG } from "./RNG"; import { win, reachedLimit } from "./Game"; import { trusted } from "./utils"; @@ -15,14 +14,10 @@ import TextField from "@mui/material/TextField"; import Button from "@mui/material/Button"; import Box from "@mui/material/Box"; -type IProps = { - p: IPlayer; -}; - const minPlay = 0; const maxPlay = 10e3; -export function CoinFlip(props: IProps): React.ReactElement { +export function CoinFlip(): React.ReactElement { const [investment, setInvestment] = useState(1000); const [result, setResult] = useState( ); const [status, setStatus] = useState(""); @@ -43,7 +38,7 @@ export function CoinFlip(props: IProps): React.ReactElement { } function play(guess: string): void { - if (reachedLimit(props.p)) return; + if (reachedLimit()) return; const v = BadRNG.random(); let letter: string; if (v < 0.5) { @@ -65,11 +60,11 @@ export function CoinFlip(props: IProps): React.ReactElement { setTimeout(() => setPlayLock(false), 250); if (correct) { - win(props.p, investment); + win(investment); } else { - win(props.p, -investment); + win(-investment); } - if (reachedLimit(props.p)) return; + if (reachedLimit()) return; } return ( diff --git a/src/Casino/Game.ts b/src/Casino/Game.ts new file mode 100644 index 000000000..378f4f0cd --- /dev/null +++ b/src/Casino/Game.ts @@ -0,0 +1,16 @@ +import { Player } from "../Player"; +import { dialogBoxCreate } from "../ui/React/DialogBox"; + +const gainLimit = 10e9; + +export function win(n: number): void { + Player.gainMoney(n, "casino"); +} + +export function reachedLimit(): boolean { + const reached = Player.getCasinoWinnings() > gainLimit; + if (reached) { + dialogBoxCreate("Alright cheater get out of here. You're not allowed here anymore."); + } + return reached; +} \ No newline at end of file diff --git a/src/Casino/Game.tsx b/src/Casino/Game.tsx deleted file mode 100644 index b20eda813..000000000 --- a/src/Casino/Game.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import * as React from "react"; -import { IPlayer } from "../PersonObjects/IPlayer"; -import { dialogBoxCreate } from "../ui/React/DialogBox"; - -const gainLimit = 10e9; - -export function win(p: IPlayer, n: number): void { - p.gainMoney(n, "casino"); -} - -export function reachedLimit(p: IPlayer): boolean { - const reached = p.getCasinoWinnings() > gainLimit; - if (reached) { - dialogBoxCreate("Alright cheater get out of here. You're not allowed here anymore."); - } - return reached; -} - -export class Game extends React.Component { - win(p: IPlayer, n: number): void { - p.gainMoney(n, "casino"); - } - - reachedLimit(p: IPlayer): boolean { - const reached = p.getCasinoWinnings() > gainLimit; - if (reached) { - dialogBoxCreate("Alright cheater get out of here. You're not allowed here anymore."); - } - return reached; - } -} diff --git a/src/Casino/Roulette.tsx b/src/Casino/Roulette.tsx index da1dd59d2..f45af1cb3 100644 --- a/src/Casino/Roulette.tsx +++ b/src/Casino/Roulette.tsx @@ -1,6 +1,5 @@ import React, { useState, useEffect } from "react"; -import { IPlayer } from "../PersonObjects/IPlayer"; import { Money } from "../ui/React/Money"; import { win, reachedLimit } from "./Game"; import { WHRNG } from "./RNG"; @@ -9,10 +8,6 @@ import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import TextField from "@mui/material/TextField"; -type IProps = { - p: IPlayer; -}; - const minPlay = 0; const maxPlay = 1e7; @@ -111,7 +106,7 @@ function Single(s: number): Strategy { }; } -export function Roulette(props: IProps): React.ReactElement { +export function Roulette(): React.ReactElement { const [rng] = useState(new WHRNG(new Date().getTime())); const [investment, setInvestment] = useState(1000); const [canPlay, setCanPlay] = useState(true); @@ -151,7 +146,7 @@ export function Roulette(props: IProps): React.ReactElement { } function play(strategy: Strategy): void { - if (reachedLimit(props.p)) return; + if (reachedLimit()) return; setCanPlay(false); setLock(false); @@ -184,14 +179,14 @@ export function Roulette(props: IProps): React.ReactElement { ); } - win(props.p, gain); + win(gain); setCanPlay(true); setLock(true); setStatus(status); setN(n); - reachedLimit(props.p); + reachedLimit(); }, 1600); } diff --git a/src/Casino/SlotMachine.tsx b/src/Casino/SlotMachine.tsx index a7fdbd083..6655f041b 100644 --- a/src/Casino/SlotMachine.tsx +++ b/src/Casino/SlotMachine.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from "react"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { Money } from "../ui/React/Money"; import { WHRNG } from "./RNG"; import { win, reachedLimit } from "./Game"; @@ -9,10 +9,6 @@ import Typography from "@mui/material/Typography"; import TextField from "@mui/material/TextField"; import Button from "@mui/material/Button"; -type IProps = { - p: IPlayer; -}; - // statically shuffled array of symbols. const symbols = [ "D", @@ -141,8 +137,8 @@ const payLines = [ const minPlay = 0; const maxPlay = 1e6; -export function SlotMachine(props: IProps): React.ReactElement { - const [rng] = useState(new WHRNG(props.p.totalPlaytime)); +export function SlotMachine(): React.ReactElement { + const [rng] = useState(new WHRNG(Player.totalPlaytime)); const [index, setIndex] = useState([0, 0, 0, 0, 0]); const [locks, setLocks] = useState([0, 0, 0, 0, 0]); const [investment, setInvestment] = useState(1000); @@ -191,9 +187,9 @@ export function SlotMachine(props: IProps): React.ReactElement { } function play(): void { - if (reachedLimit(props.p)) return; + if (reachedLimit()) return; setStatus("playing"); - win(props.p, -investment); + win(-investment); if (!canPlay) return; unlock(); setTimeout(lock, rng.random() * 2000 + 1000); @@ -235,7 +231,7 @@ export function SlotMachine(props: IProps): React.ReactElement { if (count < 3) continue; const payout = getPayout(data[0], count - 3); gains += investment * payout; - win(props.p, investment * payout); + win(investment * payout); } setStatus( @@ -244,7 +240,7 @@ export function SlotMachine(props: IProps): React.ReactElement { , ); setCanPlay(true); - if (reachedLimit(props.p)) return; + if (reachedLimit()) return; } function unlock(): void { diff --git a/src/Corporation/Actions.ts b/src/Corporation/Actions.ts index bf53d1e2f..07e475b6f 100644 --- a/src/Corporation/Actions.ts +++ b/src/Corporation/Actions.ts @@ -1,5 +1,4 @@ import { Player } from "../Player"; -import { IPlayer } from "src/PersonObjects/IPlayer"; import { MaterialSizes } from "./MaterialSizes"; import { ICorporation } from "./ICorporation"; import { Corporation } from "./Corporation"; @@ -271,7 +270,7 @@ export function BulkPurchase(corp: ICorporation, warehouse: Warehouse, material: } } -export function SellShares(corporation: ICorporation, player: IPlayer, numShares: number): number { +export function SellShares(corporation: ICorporation, numShares: number): number { if (isNaN(numShares)) throw new Error("Invalid value for number of shares"); if (numShares < 0) throw new Error("Invalid value for number of shares"); if (numShares > corporation.numShares) throw new Error("You don't have that many shares to sell!"); @@ -287,20 +286,20 @@ export function SellShares(corporation: ICorporation, player: IPlayer, numShares corporation.sharePrice = newSharePrice; corporation.shareSalesUntilPriceUpdate = newSharesUntilUpdate; corporation.shareSaleCooldown = CorporationConstants.SellSharesCooldown; - player.gainMoney(profit, "corporation"); + Player.gainMoney(profit, "corporation"); return profit; } -export function BuyBackShares(corporation: ICorporation, player: IPlayer, numShares: number): boolean { +export function BuyBackShares(corporation: ICorporation, numShares: number): boolean { if (isNaN(numShares)) throw new Error("Invalid value for number of shares"); if (numShares < 0) throw new Error("Invalid value for number of shares"); if (numShares > corporation.issuedShares) throw new Error("You don't have that many shares to buy!"); if (!corporation.public) throw new Error("You haven't gone public!"); const buybackPrice = corporation.sharePrice * 1.1; - if (player.money < numShares * buybackPrice) throw new Error("You cant afford that many shares!"); + if (Player.money < numShares * buybackPrice) throw new Error("You cant afford that many shares!"); corporation.numShares += numShares; corporation.issuedShares -= numShares; - player.loseMoney(numShares * buybackPrice, "corporation"); + Player.loseMoney(numShares * buybackPrice, "corporation"); return true; } diff --git a/src/Corporation/Corporation.tsx b/src/Corporation/Corporation.tsx index d9643eddf..edb3314e0 100644 --- a/src/Corporation/Corporation.tsx +++ b/src/Corporation/Corporation.tsx @@ -8,7 +8,7 @@ import { Industry } from "./Industry"; import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { showLiterature } from "../Literature/LiteratureHelpers"; import { LiteratureNames } from "../Literature/data/LiteratureNames"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { dialogBoxCreate } from "../ui/React/DialogBox"; import { Reviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver"; @@ -76,7 +76,7 @@ export class Corporation { this.storedCycles += numCycles; } - process(player: IPlayer): void { + process(): void { if (this.storedCycles >= CorporationConstants.CyclesPerIndustryStateCycle) { const state = this.getState(); const marketCycles = 1; @@ -139,7 +139,7 @@ export class Corporation { } else { const totalDividends = this.dividendRate * cycleProfit; const retainedEarnings = cycleProfit - totalDividends; - player.gainMoney(this.getCycleDividends(), "corporation"); + Player.gainMoney(this.getCycleDividends(), "corporation"); this.addFunds(retainedEarnings); } } else { @@ -428,9 +428,9 @@ export class Corporation { // Adds the Corporation Handbook (Starter Guide) to the player's home computer. // This is a lit file that gives introductory info to the player // This occurs when the player clicks the "Getting Started Guide" button on the overview panel - getStarterGuide(player: IPlayer): void { + getStarterGuide(): void { // Check if player already has Corporation Handbook - const homeComp = player.getHomeComputer(); + const homeComp = Player.getHomeComputer(); let hasHandbook = false; const handbookFn = LiteratureNames.CorporationManagementHandbook; for (let i = 0; i < homeComp.messages.length; ++i) { diff --git a/src/Corporation/ui/Industry.tsx b/src/Corporation/ui/Industry.tsx index 9c1fafadf..c02643db8 100644 --- a/src/Corporation/ui/Industry.tsx +++ b/src/Corporation/ui/Industry.tsx @@ -31,7 +31,6 @@ export function Industry(props: IProps): React.ReactElement { void; } diff --git a/src/Corporation/ui/modals/BuybackSharesModal.tsx b/src/Corporation/ui/modals/BuybackSharesModal.tsx index 5d6b33e49..2e92cdcd9 100644 --- a/src/Corporation/ui/modals/BuybackSharesModal.tsx +++ b/src/Corporation/ui/modals/BuybackSharesModal.tsx @@ -35,7 +35,7 @@ export function BuybackSharesModal(props: IProps): React.ReactElement { function buy(): void { if (disabled) return; try { - BuyBackShares(corp, player, shares); + BuyBackShares(corp, shares); } catch (err) { dialogBoxCreate(err + ""); } diff --git a/src/Corporation/ui/modals/CreateCorporationModal.tsx b/src/Corporation/ui/modals/CreateCorporationModal.tsx index 2c63baf4e..9e77fcc14 100644 --- a/src/Corporation/ui/modals/CreateCorporationModal.tsx +++ b/src/Corporation/ui/modals/CreateCorporationModal.tsx @@ -72,7 +72,7 @@ export function CreateCorporationModal(props: IProps): React.ReactElement { )} ); diff --git a/src/Corporation/ui/modals/SellSharesModal.tsx b/src/Corporation/ui/modals/SellSharesModal.tsx index 5a414d0d7..fdb178029 100644 --- a/src/Corporation/ui/modals/SellSharesModal.tsx +++ b/src/Corporation/ui/modals/SellSharesModal.tsx @@ -49,7 +49,7 @@ export function SellSharesModal(props: IProps): React.ReactElement { function sell(): void { if (disabled) return; try { - const profit = SellShares(corp, player, shares); + const profit = SellShares(corp, shares); props.onClose(); dialogBoxCreate( <> diff --git a/src/Crime/CrimeHelpers.ts b/src/Crime/CrimeHelpers.ts index dbbec2f35..56cbe7bc6 100644 --- a/src/Crime/CrimeHelpers.ts +++ b/src/Crime/CrimeHelpers.ts @@ -1,16 +1,16 @@ import { Crimes } from "./Crimes"; import { Crime } from "./Crime"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { dialogBoxCreate } from "../ui/React/DialogBox"; -export function determineCrimeSuccess(p: IPlayer, type: string): boolean { +export function determineCrimeSuccess(type: string): boolean { let chance = 0; let found = false; for (const i of Object.keys(Crimes)) { const crime = Crimes[i]; if (crime.type === type) { - chance = crime.successRate(p); + chance = crime.successRate(Player); found = true; break; } diff --git a/src/DevMenu.tsx b/src/DevMenu.tsx index 6bcb2eab3..b590fc6df 100644 --- a/src/DevMenu.tsx +++ b/src/DevMenu.tsx @@ -1,7 +1,5 @@ -import { IPlayer } from "./PersonObjects/IPlayer"; +import { Player } from "./Player"; import { Bladeburner } from "./Bladeburner/Bladeburner"; -import { IEngine } from "./IEngine"; -import { IRouter } from "./ui/Router"; import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; import React, { useEffect } from "react"; @@ -28,44 +26,38 @@ import { Entropy } from "./DevMenu/ui/Entropy"; import Typography from "@mui/material/Typography"; import { Exploit } from "./Exploits/Exploit"; -interface IProps { - player: IPlayer; - engine: IEngine; - router: IRouter; -} - -export function DevMenuRoot(props: IProps): React.ReactElement { +export function DevMenuRoot(): React.ReactElement { useEffect(() => { - props.player.giveExploit(Exploit.YoureNotMeantToAccessThis); + Player.giveExploit(Exploit.YoureNotMeantToAccessThis); }, []); return ( <> Development Menu - Only meant to be used for testing/debugging - - - - - - + + + + + + - {props.player.bladeburner instanceof Bladeburner && } + {Player.bladeburner instanceof Bladeburner && } - {props.player.inGang() && } + {Player.inGang() && } - {props.player.hasCorporation() && } + {Player.hasCorporation() && } - {props.player.hasWseAccount && } + {Player.hasWseAccount && } - {props.player.sleeves.length > 0 && } - {props.player.augmentations.some((aug) => aug.name === AugmentationNames.StaneksGift1) && } + {Player.sleeves.length > 0 && } + {Player.augmentations.some((aug) => aug.name === AugmentationNames.StaneksGift1) && } - - - + + + ); diff --git a/src/DevMenu/ui/Achievements.tsx b/src/DevMenu/ui/Achievements.tsx index 1bba149ed..3cb2bdad3 100644 --- a/src/DevMenu/ui/Achievements.tsx +++ b/src/DevMenu/ui/Achievements.tsx @@ -11,44 +11,39 @@ import { Tooltip } from "@mui/material"; import LockIcon from "@mui/icons-material/Lock"; import LockOpenIcon from "@mui/icons-material/LockOpen"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { achievements } from "../../Achievements/Achievements"; -import { IEngine } from "../../IEngine"; +import { Engine } from "../../engine"; -interface IProps { - player: IPlayer; - engine: IEngine; -} - -export function Achievements(props: IProps): React.ReactElement { - const [playerAchievement, setPlayerAchievements] = useState(props.player.achievements.map((m) => m.ID)); +export function Achievements(): React.ReactElement { + const [playerAchievement, setPlayerAchievements] = useState(Player.achievements.map((m) => m.ID)); function grantAchievement(id: string): void { - props.player.giveAchievement(id); - setPlayerAchievements(props.player.achievements.map((m) => m.ID)); + Player.giveAchievement(id); + setPlayerAchievements(Player.achievements.map((m) => m.ID)); } function grantAllAchievements(): void { - Object.values(achievements).forEach((a) => props.player.giveAchievement(a.ID)); - setPlayerAchievements(props.player.achievements.map((m) => m.ID)); + Object.values(achievements).forEach((a) => Player.giveAchievement(a.ID)); + setPlayerAchievements(Player.achievements.map((m) => m.ID)); } function removeAchievement(id: string): void { - props.player.achievements = props.player.achievements.filter((a) => a.ID !== id); - setPlayerAchievements(props.player.achievements.map((m) => m.ID)); + Player.achievements = Player.achievements.filter((a) => a.ID !== id); + setPlayerAchievements(Player.achievements.map((m) => m.ID)); } function clearAchievements(): void { - props.player.achievements = []; - setPlayerAchievements(props.player.achievements.map((m) => m.ID)); + Player.achievements = []; + setPlayerAchievements(Player.achievements.map((m) => m.ID)); } function disableEngine(): void { - props.engine.Counters.achievementsCounter = Number.MAX_VALUE; + Engine.Counters.achievementsCounter = Number.MAX_VALUE; } function enableEngine(): void { - props.engine.Counters.achievementsCounter = 0; + Engine.Counters.achievementsCounter = 0; } return ( diff --git a/src/DevMenu/ui/Augmentations.tsx b/src/DevMenu/ui/Augmentations.tsx index 7f129495c..caa174bd6 100644 --- a/src/DevMenu/ui/Augmentations.tsx +++ b/src/DevMenu/ui/Augmentations.tsx @@ -12,34 +12,30 @@ import { } from "@mui/material"; import React, { useState } from "react"; import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; -interface IProps { - player: IPlayer; -} - -export function Augmentations(props: IProps): React.ReactElement { +export function Augmentations(): React.ReactElement { const [augmentation, setAugmentation] = useState("Augmented Targeting I"); function setAugmentationDropdown(event: SelectChangeEvent): void { setAugmentation(event.target.value); } function queueAug(): void { - props.player.queueAugmentation(augmentation); + Player.queueAugmentation(augmentation); } function queueAllAugs(): void { for (const augName of Object.values(AugmentationNames)) { - props.player.queueAugmentation(augName); + Player.queueAugmentation(augName); } } function clearAugs(): void { - props.player.augmentations = []; + Player.augmentations = []; } function clearQueuedAugs(): void { - props.player.queuedAugmentations = []; + Player.queuedAugmentations = []; } return ( diff --git a/src/DevMenu/ui/Bladeburner.tsx b/src/DevMenu/ui/Bladeburner.tsx index 6726167a3..538fe8a78 100644 --- a/src/DevMenu/ui/Bladeburner.tsx +++ b/src/DevMenu/ui/Bladeburner.tsx @@ -7,21 +7,17 @@ import AccordionDetails from "@mui/material/AccordionDetails"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import { Adjuster } from "./Adjuster"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; const bigNumber = 1e27; -interface IProps { - player: IPlayer; -} - -export function Bladeburner(props: IProps): React.ReactElement { - const bladeburner = props.player.bladeburner; +export function Bladeburner(): React.ReactElement { + const bladeburner = Player.bladeburner; if (bladeburner === null) return <>; function modifyBladeburnerRank(modify: number): (x: number) => void { return function (rank: number): void { if (!bladeburner) return; - bladeburner.changeRank(props.player, rank * modify); + bladeburner.changeRank(Player, rank * modify); }; } @@ -34,7 +30,7 @@ export function Bladeburner(props: IProps): React.ReactElement { function addTonsBladeburnerRank(): void { if (!bladeburner) return; - bladeburner.changeRank(props.player, bigNumber); + bladeburner.changeRank(Player, bigNumber); } function modifyBladeburnerCycles(modify: number): (x: number) => void { diff --git a/src/DevMenu/ui/Corporation.tsx b/src/DevMenu/ui/Corporation.tsx index ce4250a91..9dbd3ac9b 100644 --- a/src/DevMenu/ui/Corporation.tsx +++ b/src/DevMenu/ui/Corporation.tsx @@ -8,58 +8,54 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import { Adjuster } from "./Adjuster"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; const bigNumber = 1e27; -interface IProps { - player: IPlayer; -} - -export function Corporation(props: IProps): React.ReactElement { +export function Corporation(): React.ReactElement { function addTonsCorporationFunds(): void { - if (props.player.corporation) { - props.player.corporation.funds = props.player.corporation.funds + bigNumber; + if (Player.corporation) { + Player.corporation.funds = Player.corporation.funds + bigNumber; } } function modifyCorporationFunds(modify: number): (x: number) => void { return function (funds: number): void { - if (props.player.corporation) { - props.player.corporation.funds += funds * modify; + if (Player.corporation) { + Player.corporation.funds += funds * modify; } }; } function resetCorporationFunds(): void { - if (props.player.corporation) { - props.player.corporation.funds = props.player.corporation.funds - props.player.corporation.funds; + if (Player.corporation) { + Player.corporation.funds = Player.corporation.funds - Player.corporation.funds; } } function addTonsCorporationCycles(): void { - if (props.player.corporation) { - props.player.corporation.storedCycles = bigNumber; + if (Player.corporation) { + Player.corporation.storedCycles = bigNumber; } } function modifyCorporationCycles(modify: number): (x: number) => void { return function (cycles: number): void { - if (props.player.corporation) { - props.player.corporation.storedCycles += cycles * modify; + if (Player.corporation) { + Player.corporation.storedCycles += cycles * modify; } }; } function resetCorporationCycles(): void { - if (props.player.corporation) { - props.player.corporation.storedCycles = 0; + if (Player.corporation) { + Player.corporation.storedCycles = 0; } } function finishCorporationProducts(): void { - if (!props.player.corporation) return; - props.player.corporation.divisions.forEach((div) => { + if (!Player.corporation) return; + Player.corporation.divisions.forEach((div) => { Object.keys(div.products).forEach((prod) => { const product = div.products[prod]; if (product === undefined) throw new Error("Impossible product undefined"); @@ -69,8 +65,8 @@ export function Corporation(props: IProps): React.ReactElement { } function addCorporationResearch(): void { - if (!props.player.corporation) return; - props.player.corporation.divisions.forEach((div) => { + if (!Player.corporation) return; + Player.corporation.divisions.forEach((div) => { div.sciResearch.qty += 1e10; }); } diff --git a/src/DevMenu/ui/Entropy.tsx b/src/DevMenu/ui/Entropy.tsx index acac53af0..47d90d9a6 100644 --- a/src/DevMenu/ui/Entropy.tsx +++ b/src/DevMenu/ui/Entropy.tsx @@ -6,18 +6,12 @@ import AccordionDetails from "@mui/material/AccordionDetails"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Adjuster } from "./Adjuster"; -import { IEngine } from "../../IEngine"; // Update as additional BitNodes get implemented -interface IProps { - player: IPlayer; - engine: IEngine; -} - -export function Entropy(props: IProps): React.ReactElement { +export function Entropy(): React.ReactElement { return ( }> @@ -28,20 +22,20 @@ export function Entropy(props: IProps): React.ReactElement { label="Set entropy" placeholder="entropy" add={(num) => { - props.player.entropy += num; - props.player.applyEntropy(props.player.entropy); + Player.entropy += num; + Player.applyEntropy(Player.entropy); }} subtract={(num) => { - props.player.entropy -= num; - props.player.applyEntropy(props.player.entropy); + Player.entropy -= num; + Player.applyEntropy(Player.entropy); }} tons={() => { - props.player.entropy += 1e12; - props.player.applyEntropy(props.player.entropy); + Player.entropy += 1e12; + Player.applyEntropy(Player.entropy); }} reset={() => { - props.player.entropy = 0; - props.player.applyEntropy(props.player.entropy); + Player.entropy = 0; + Player.applyEntropy(Player.entropy); }} /> diff --git a/src/DevMenu/ui/Factions.tsx b/src/DevMenu/ui/Factions.tsx index 6f1453ac1..d305c672c 100644 --- a/src/DevMenu/ui/Factions.tsx +++ b/src/DevMenu/ui/Factions.tsx @@ -9,7 +9,7 @@ import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import Select, { SelectChangeEvent } from "@mui/material/Select"; import { Adjuster } from "./Adjuster"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Factions as AllFaction } from "../../Faction/Factions"; import FormControl from "@mui/material/FormControl"; import MenuItem from "@mui/material/MenuItem"; @@ -21,11 +21,7 @@ import { FactionNames } from "../../Faction/data/FactionNames"; const bigNumber = 1e12; -interface IProps { - player: IPlayer; -} - -export function Factions(props: IProps): React.ReactElement { +export function Factions(): React.ReactElement { const [faction, setFaction] = useState(FactionNames.Illuminati as string); function setFactionDropdown(event: SelectChangeEvent): void { @@ -33,11 +29,11 @@ export function Factions(props: IProps): React.ReactElement { } function receiveInvite(): void { - props.player.receiveInvite(faction); + Player.receiveInvite(faction); } function receiveAllInvites(): void { - Object.values(FactionNames).forEach((faction) => props.player.receiveInvite(faction)); + Object.values(FactionNames).forEach((faction) => Player.receiveInvite(faction)); } function modifyFactionRep(modifier: number): (x: number) => void { diff --git a/src/DevMenu/ui/Gang.tsx b/src/DevMenu/ui/Gang.tsx index cef6bd24d..3b0566738 100644 --- a/src/DevMenu/ui/Gang.tsx +++ b/src/DevMenu/ui/Gang.tsx @@ -7,32 +7,28 @@ import AccordionDetails from "@mui/material/AccordionDetails"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import { Adjuster } from "./Adjuster"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; const bigNumber = 1e27; -interface IProps { - player: IPlayer; -} - -export function Gang(props: IProps): React.ReactElement { +export function Gang(): React.ReactElement { function addTonsGangCycles(): void { - if (props.player.gang) { - props.player.gang.storedCycles = bigNumber; + if (Player.gang) { + Player.gang.storedCycles = bigNumber; } } function modifyGangCycles(modify: number): (x: number) => void { return function (cycles: number): void { - if (props.player.gang) { - props.player.gang.storedCycles += cycles * modify; + if (Player.gang) { + Player.gang.storedCycles += cycles * modify; } }; } function resetGangCycles(): void { - if (props.player.gang) { - props.player.gang.storedCycles = 0; + if (Player.gang) { + Player.gang.storedCycles = 0; } } diff --git a/src/DevMenu/ui/General.tsx b/src/DevMenu/ui/General.tsx index 9b96e8326..2c0b39902 100644 --- a/src/DevMenu/ui/General.tsx +++ b/src/DevMenu/ui/General.tsx @@ -8,61 +8,56 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import { Money } from "../../ui/React/Money"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { IRouter } from "../../ui/Router"; +import { Player } from "../../Player"; +import { Router } from "../../ui/GameRoot"; import { MenuItem, SelectChangeEvent, TextField, Select } from "@mui/material"; import { Bladeburner } from "../../Bladeburner/Bladeburner"; import { GangConstants } from "../../Gang/data/Constants"; import { FactionNames } from "../../Faction/data/FactionNames"; import { checkForMessagesToSend } from "../../Message/MessageHelpers"; -interface IProps { - player: IPlayer; - router: IRouter; -} - -export function General(props: IProps): React.ReactElement { +export function General(): React.ReactElement { const [error, setError] = useState(false); const [corporationName, setCorporationName] = useState(""); const [gangFaction, setGangFaction] = useState(""); function addMoney(n: number) { return function () { - props.player.gainMoney(n, "other"); + Player.gainMoney(n, "other"); }; } function upgradeRam(): void { - props.player.getHomeComputer().maxRam *= 2; + Player.getHomeComputer().maxRam *= 2; } function quickB1tFlum3(): void { - props.router.toBitVerse(true, true); + Router.toBitVerse(true, true); } function b1tflum3(): void { - props.router.toBitVerse(true, false); + Router.toBitVerse(true, false); } function quickHackW0r1dD43m0n(): void { - props.router.toBitVerse(false, true); + Router.toBitVerse(false, true); } function hackW0r1dD43m0n(): void { - props.router.toBitVerse(false, false); + Router.toBitVerse(false, false); } function createCorporation(): void { - props.player.startCorporation(corporationName); + Player.startCorporation(corporationName); } function joinBladeburner(): void { - props.player.bladeburner = new Bladeburner(props.player); + Player.bladeburner = new Bladeburner(); } function startGang(): void { const isHacking = gangFaction === FactionNames.NiteSec || gangFaction === FactionNames.TheBlackHand; - props.player.startGang(gangFaction, isHacking); + Player.startGang(gangFaction, isHacking); } function setGangFactionDropdown(event: SelectChangeEvent): void { diff --git a/src/DevMenu/ui/Programs.tsx b/src/DevMenu/ui/Programs.tsx index 830a99b2e..b32f5e870 100644 --- a/src/DevMenu/ui/Programs.tsx +++ b/src/DevMenu/ui/Programs.tsx @@ -8,29 +8,25 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import Select, { SelectChangeEvent } from "@mui/material/Select"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Programs as AllPrograms } from "../../Programs/Programs"; import MenuItem from "@mui/material/MenuItem"; -interface IProps { - player: IPlayer; -} - -export function Programs(props: IProps): React.ReactElement { +export function Programs(): React.ReactElement { const [program, setProgram] = useState("NUKE.exe"); function setProgramDropdown(event: SelectChangeEvent): void { setProgram(event.target.value); } function addProgram(): void { - if (!props.player.hasProgram(program)) { - props.player.getHomeComputer().programs.push(program); + if (!Player.hasProgram(program)) { + Player.getHomeComputer().programs.push(program); } } function addAllPrograms(): void { for (const i of Object.keys(AllPrograms)) { - if (!props.player.hasProgram(AllPrograms[i].name)) { - props.player.getHomeComputer().programs.push(AllPrograms[i].name); + if (!Player.hasProgram(AllPrograms[i].name)) { + Player.getHomeComputer().programs.push(AllPrograms[i].name); } } } diff --git a/src/DevMenu/ui/Sleeves.tsx b/src/DevMenu/ui/Sleeves.tsx index 5dcbcf455..fa1941ed6 100644 --- a/src/DevMenu/ui/Sleeves.tsx +++ b/src/DevMenu/ui/Sleeves.tsx @@ -7,41 +7,37 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Adjuster } from "./Adjuster"; -interface IProps { - player: IPlayer; -} - -export function Sleeves(props: IProps): React.ReactElement { +export function Sleeves(): React.ReactElement { function sleeveMaxAllShock(): void { - for (let i = 0; i < props.player.sleeves.length; ++i) { - props.player.sleeves[i].shock = 0; + for (let i = 0; i < Player.sleeves.length; ++i) { + Player.sleeves[i].shock = 0; } } function sleeveClearAllShock(): void { - for (let i = 0; i < props.player.sleeves.length; ++i) { - props.player.sleeves[i].shock = 100; + for (let i = 0; i < Player.sleeves.length; ++i) { + Player.sleeves[i].shock = 100; } } function sleeveSyncMaxAll(): void { - for (let i = 0; i < props.player.sleeves.length; ++i) { - props.player.sleeves[i].sync = 100; + for (let i = 0; i < Player.sleeves.length; ++i) { + Player.sleeves[i].sync = 100; } } function sleeveSyncClearAll(): void { - for (let i = 0; i < props.player.sleeves.length; ++i) { - props.player.sleeves[i].sync = 0; + for (let i = 0; i < Player.sleeves.length; ++i) { + Player.sleeves[i].sync = 0; } } function sleeveSetStoredCycles(cycles: number): void { - for (let i = 0; i < props.player.sleeves.length; ++i) { - props.player.sleeves[i].storedCycles = cycles; + for (let i = 0; i < Player.sleeves.length; ++i) { + Player.sleeves[i].storedCycles = cycles; } } diff --git a/src/DevMenu/ui/SourceFiles.tsx b/src/DevMenu/ui/SourceFiles.tsx index cab4440a6..fa4576135 100644 --- a/src/DevMenu/ui/SourceFiles.tsx +++ b/src/DevMenu/ui/SourceFiles.tsx @@ -8,35 +8,31 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import { PlayerOwnedSourceFile } from "../../SourceFile/PlayerOwnedSourceFile"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import ButtonGroup from "@mui/material/ButtonGroup"; // Update as additional BitNodes get implemented const validSFN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; -interface IProps { - player: IPlayer; -} - -export function SourceFiles(props: IProps): React.ReactElement { +export function SourceFiles(): React.ReactElement { function setSF(sfN: number, sfLvl: number) { return function () { if (sfN === 9) { - props.player.hacknetNodes = []; + Player.hacknetNodes = []; } if (sfLvl === 0) { - props.player.sourceFiles = props.player.sourceFiles.filter((sf) => sf.n !== sfN); + Player.sourceFiles = Player.sourceFiles.filter((sf) => sf.n !== sfN); return; } - if (!props.player.sourceFiles.some((sf) => sf.n === sfN)) { - props.player.sourceFiles.push(new PlayerOwnedSourceFile(sfN, sfLvl)); + if (!Player.sourceFiles.some((sf) => sf.n === sfN)) { + Player.sourceFiles.push(new PlayerOwnedSourceFile(sfN, sfLvl)); return; } - for (let i = 0; i < props.player.sourceFiles.length; i++) { - if (props.player.sourceFiles[i].n === sfN) { - props.player.sourceFiles[i].lvl = sfLvl; + for (let i = 0; i < Player.sourceFiles.length; i++) { + if (Player.sourceFiles[i].n === sfN) { + Player.sourceFiles[i].lvl = sfLvl; } } }; @@ -51,7 +47,7 @@ export function SourceFiles(props: IProps): React.ReactElement { } function clearExploits(): void { - props.player.exploits = []; + Player.exploits = []; } return ( diff --git a/src/DevMenu/ui/Stats.tsx b/src/DevMenu/ui/Stats.tsx index a664214cf..c9a1c0966 100644 --- a/src/DevMenu/ui/Stats.tsx +++ b/src/DevMenu/ui/Stats.tsx @@ -8,132 +8,128 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import { Adjuster } from "./Adjuster"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; const bigNumber = 1e27; -interface IProps { - player: IPlayer; -} - -export function Stats(props: IProps): React.ReactElement { +export function Stats(): React.ReactElement { function modifyExp(stat: string, modifier: number) { return function (exp: number) { switch (stat) { case "hacking": if (exp) { - props.player.gainHackingExp(exp * modifier); + Player.gainHackingExp(exp * modifier); } break; case "strength": if (exp) { - props.player.gainStrengthExp(exp * modifier); + Player.gainStrengthExp(exp * modifier); } break; case "defense": if (exp) { - props.player.gainDefenseExp(exp * modifier); + Player.gainDefenseExp(exp * modifier); } break; case "dexterity": if (exp) { - props.player.gainDexterityExp(exp * modifier); + Player.gainDexterityExp(exp * modifier); } break; case "agility": if (exp) { - props.player.gainAgilityExp(exp * modifier); + Player.gainAgilityExp(exp * modifier); } break; case "charisma": if (exp) { - props.player.gainCharismaExp(exp * modifier); + Player.gainCharismaExp(exp * modifier); } break; case "intelligence": if (exp) { - props.player.gainIntelligenceExp(exp * modifier); + Player.gainIntelligenceExp(exp * modifier); } break; } - props.player.updateSkillLevels(); + Player.updateSkillLevels(); }; } function modifyKarma(modifier: number) { return function (amt: number) { - props.player.karma += amt * modifier; + Player.karma += amt * modifier; }; } function tonsOfExp(): void { - props.player.gainHackingExp(bigNumber); - props.player.gainStrengthExp(bigNumber); - props.player.gainDefenseExp(bigNumber); - props.player.gainDexterityExp(bigNumber); - props.player.gainAgilityExp(bigNumber); - props.player.gainCharismaExp(bigNumber); - props.player.gainIntelligenceExp(bigNumber); - props.player.updateSkillLevels(); + Player.gainHackingExp(bigNumber); + Player.gainStrengthExp(bigNumber); + Player.gainDefenseExp(bigNumber); + Player.gainDexterityExp(bigNumber); + Player.gainAgilityExp(bigNumber); + Player.gainCharismaExp(bigNumber); + Player.gainIntelligenceExp(bigNumber); + Player.updateSkillLevels(); } function resetAllExp(): void { - props.player.exp.hacking = 0; - props.player.exp.strength = 0; - props.player.exp.defense = 0; - props.player.exp.dexterity = 0; - props.player.exp.agility = 0; - props.player.exp.charisma = 0; - props.player.exp.intelligence = 0; - props.player.updateSkillLevels(); + Player.exp.hacking = 0; + Player.exp.strength = 0; + Player.exp.defense = 0; + Player.exp.dexterity = 0; + Player.exp.agility = 0; + Player.exp.charisma = 0; + Player.exp.intelligence = 0; + Player.updateSkillLevels(); } function resetExperience(stat: string): () => void { return function () { switch (stat) { case "hacking": - props.player.exp.hacking = 0; + Player.exp.hacking = 0; break; case "strength": - props.player.exp.strength = 0; + Player.exp.strength = 0; break; case "defense": - props.player.exp.defense = 0; + Player.exp.defense = 0; break; case "dexterity": - props.player.exp.dexterity = 0; + Player.exp.dexterity = 0; break; case "agility": - props.player.exp.agility = 0; + Player.exp.agility = 0; break; case "charisma": - props.player.exp.charisma = 0; + Player.exp.charisma = 0; break; case "intelligence": - props.player.exp.intelligence = 0; + Player.exp.intelligence = 0; break; } - props.player.updateSkillLevels(); + Player.updateSkillLevels(); }; } function resetKarma(): () => void { return function () { - props.player.karma = 0; + Player.karma = 0; }; } function enableIntelligence(): void { - if (props.player.skills.intelligence === 0) { - props.player.skills.intelligence = 1; - props.player.updateSkillLevels(); + if (Player.skills.intelligence === 0) { + Player.skills.intelligence = 1; + Player.updateSkillLevels(); } } function disableIntelligence(): void { - props.player.exp.intelligence = 0; - props.player.skills.intelligence = 0; - props.player.updateSkillLevels(); + Player.exp.intelligence = 0; + Player.skills.intelligence = 0; + Player.updateSkillLevels(); } return ( diff --git a/src/DevMenu/ui/TimeSkip.tsx b/src/DevMenu/ui/TimeSkip.tsx index f44f65a6d..b8da48b02 100644 --- a/src/DevMenu/ui/TimeSkip.tsx +++ b/src/DevMenu/ui/TimeSkip.tsx @@ -7,22 +7,17 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { saveObject } from "../../SaveObject"; -import { IEngine } from "../../IEngine"; +import { Engine } from "../../engine"; // Update as additional BitNodes get implemented -interface IProps { - player: IPlayer; - engine: IEngine; -} - -export function TimeSkip(props: IProps): React.ReactElement { +export function TimeSkip(): React.ReactElement { function timeskip(time: number) { return () => { - props.player.lastUpdate -= time; - props.engine._lastUpdate -= time; + Player.lastUpdate -= time; + Engine._lastUpdate -= time; saveObject.saveGame(); setTimeout(() => location.reload(), 1000); }; diff --git a/src/ExportBonus.tsx b/src/ExportBonus.tsx index c75bce683..f4a0a404d 100644 --- a/src/ExportBonus.tsx +++ b/src/ExportBonus.tsx @@ -1,5 +1,5 @@ import { Factions } from "./Faction/Factions"; -import { IPlayer } from "./PersonObjects/IPlayer"; +import { Player } from "./Player"; export let LastExportBonus = 0; @@ -9,9 +9,9 @@ export function canGetBonus(): boolean { return now - LastExportBonus > bonusTimer; } -export function onExport(p: IPlayer): void { +export function onExport(): void { if (!canGetBonus()) return; - for (const facName of p.factions) { + for (const facName of Player.factions) { Factions[facName].favor++; } LastExportBonus = new Date().getTime(); diff --git a/src/Faction/FactionHelpers.tsx b/src/Faction/FactionHelpers.tsx index 6e7d9509b..c5cea74ae 100644 --- a/src/Faction/FactionHelpers.tsx +++ b/src/Faction/FactionHelpers.tsx @@ -7,7 +7,6 @@ import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { Faction } from "./Faction"; import { Factions } from "./Factions"; import { Player } from "../Player"; -import { IPlayer } from "../PersonObjects/IPlayer"; import { Settings } from "../Settings/Settings"; import { getHackingWorkRepGain, @@ -59,7 +58,7 @@ export function hasAugmentationPrereqs(aug: Augmentation): boolean { export function purchaseAugmentation(aug: Augmentation, fac: Faction, sing = false): string { const hasPrereqs = hasAugmentationPrereqs(aug); - const augCosts = aug.getCost(Player); + const augCosts = aug.getCost(); if (!hasPrereqs) { const txt = `You must first purchase or install ${aug.prereqs .filter((req) => !Player.hasAugmentation(req)) @@ -84,7 +83,7 @@ export function purchaseAugmentation(aug: Augmentation, fac: Faction, sing = fal } else if (augCosts.moneyCost === 0 || Player.money >= augCosts.moneyCost) { const queuedAugmentation = new PlayerOwnedAugmentation(aug.name); if (aug.name == AugmentationNames.NeuroFluxGovernor) { - queuedAugmentation.level = aug.getLevel(Player); + queuedAugmentation.level = aug.getLevel(); } Player.queuedAugmentations.push(queuedAugmentation); @@ -134,20 +133,20 @@ export function processPassiveFactionRepGain(numCycles: number): void { } } -export const getFactionAugmentationsFiltered = (player: IPlayer, faction: Faction): string[] => { +export const getFactionAugmentationsFiltered = (faction: Faction): string[] => { // If player has a gang with this faction, return (almost) all augmentations - if (player.hasGangWith(faction.name)) { + if (Player.hasGangWith(faction.name)) { let augs = Object.values(StaticAugmentations); // Remove special augs augs = augs.filter((a) => !a.isSpecial && a.name !== AugmentationNames.CongruityImplant); - if (player.bitNodeN === 2) { + if (Player.bitNodeN === 2) { // TRP is not available outside of BN2 for Gangs augs.push(StaticAugmentations[AugmentationNames.TheRedPill]); } - const rng = SFC32RNG(`BN${player.bitNodeN}.${player.sourceFileLvl(player.bitNodeN)}`); + const rng = SFC32RNG(`BN${Player.bitNodeN}.${Player.sourceFileLvl(Player.bitNodeN)}`); // Remove faction-unique augs that don't belong to this faction const uniqueFilter = (a: Augmentation): boolean => { // Keep all the non-unique one diff --git a/src/Faction/formulas/donation.ts b/src/Faction/formulas/donation.ts index ea0e99b11..0bcd8c645 100644 --- a/src/Faction/formulas/donation.ts +++ b/src/Faction/formulas/donation.ts @@ -1,6 +1,6 @@ import { CONSTANTS } from "../../Constants"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { IPerson } from "../../PersonObjects/IPerson"; -export function repFromDonation(amt: number, player: IPlayer): number { - return (amt / CONSTANTS.DonateMoneyToRepDivisor) * player.mults.faction_rep; +export function repFromDonation(amt: number, person: IPerson): number { + return (amt / CONSTANTS.DonateMoneyToRepDivisor) * person.mults.faction_rep; } diff --git a/src/Faction/ui/AugmentationsPage.tsx b/src/Faction/ui/AugmentationsPage.tsx index cb3b8cc45..939ad8e0e 100644 --- a/src/Faction/ui/AugmentationsPage.tsx +++ b/src/Faction/ui/AugmentationsPage.tsx @@ -10,7 +10,7 @@ import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { PurchasableAugmentations } from "../../Augmentation/ui/PurchasableAugmentations"; import { PurchaseAugmentationsOrderSetting } from "../../Settings/SettingEnums"; import { Settings } from "../../Settings/Settings"; -import { use } from "../../ui/Context"; +import { Player } from "../../Player"; import { numeralWrapper } from "../../ui/numeralFormat"; import { Favor } from "../../ui/React/Favor"; import { Reputation } from "../../ui/React/Reputation"; @@ -24,8 +24,6 @@ type IProps = { }; export function AugmentationsPage(props: IProps): React.ReactElement { - const player = use.Player(); - const setRerender = useState(false)[1]; function rerender(): void { @@ -33,7 +31,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { } function getAugs(): string[] { - return getFactionAugmentationsFiltered(player, props.faction); + return getFactionAugmentationsFiltered(props.faction); } function getAugsSorted(): string[] { @@ -61,7 +59,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { throw new Error("Invalid Augmentation Names"); } - return aug1.getCost(player).moneyCost - aug2.getCost(player).moneyCost; + return aug1.getCost().moneyCost - aug2.getCost().moneyCost; }); return augs; @@ -71,11 +69,11 @@ export function AugmentationsPage(props: IProps): React.ReactElement { const augs = getAugs(); function canBuy(augName: string): boolean { const aug = StaticAugmentations[augName]; - const augCosts = aug.getCost(player); + const augCosts = aug.getCost(); const repCost = augCosts.repCost; const hasReq = props.faction.playerReputation >= repCost; const hasRep = hasAugmentationPrereqs(aug); - const hasCost = augCosts.moneyCost !== 0 && player.money > augCosts.moneyCost; + const hasCost = augCosts.moneyCost !== 0 && Player.money > augCosts.moneyCost; return hasCost && hasReq && hasRep; } const buy = augs.filter(canBuy).sort((augName1, augName2) => { @@ -85,7 +83,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { throw new Error("Invalid Augmentation Names"); } - return aug1.getCost(player).moneyCost - aug2.getCost(player).moneyCost; + return aug1.getCost().moneyCost - aug2.getCost().moneyCost; }); const cantBuy = augs .filter((aug) => !canBuy(aug)) @@ -95,7 +93,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { if (aug1 == null || aug2 == null) { throw new Error("Invalid Augmentation Names"); } - return aug1.getCost(player).repCost - aug2.getCost(player).repCost; + return aug1.getCost().repCost - aug2.getCost().repCost; }); return buy.concat(cantBuy); @@ -109,7 +107,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { if (aug1 == null || aug2 == null) { throw new Error("Invalid Augmentation Names"); } - return aug1.getCost(player).repCost - aug2.getCost(player).repCost; + return aug1.getCost().repCost - aug2.getCost().repCost; }); return augs; @@ -128,7 +126,7 @@ export function AugmentationsPage(props: IProps): React.ReactElement { const purchasable = augs.filter( (aug: string) => aug === AugmentationNames.NeuroFluxGovernor || - (!player.augmentations.some((a) => a.name === aug) && !player.queuedAugmentations.some((a) => a.name === aug)), + (!Player.augmentations.some((a) => a.name === aug) && !Player.queuedAugmentations.some((a) => a.name === aug)), ); const owned = augs.filter((aug: string) => !purchasable.includes(aug)); @@ -195,16 +193,15 @@ export function AugmentationsPage(props: IProps): React.ReactElement { { - const costs = aug.getCost(player); + canPurchase={(aug) => { + const costs = aug.getCost(); return ( hasAugmentationPrereqs(aug) && props.faction.playerReputation >= costs.repCost && - (costs.moneyCost === 0 || player.money > costs.moneyCost) + (costs.moneyCost === 0 || Player.money > costs.moneyCost) ); }} - purchaseAugmentation={(player, aug, showModal) => { + purchaseAugmentation={(aug, showModal) => { if (!Settings.SuppressBuyAugmentationConfirmation) { showModal(true); } else { diff --git a/src/Faction/ui/DonateOption.tsx b/src/Faction/ui/DonateOption.tsx index afd840dbb..052b7d397 100644 --- a/src/Faction/ui/DonateOption.tsx +++ b/src/Faction/ui/DonateOption.tsx @@ -5,7 +5,7 @@ import React, { useState } from "react"; import { CONSTANTS } from "../../Constants"; import { Faction } from "../Faction"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { repFromDonation } from "../formulas/donation"; import { Favor } from "../../ui/React/Favor"; @@ -24,7 +24,6 @@ type IProps = { faction: Faction; disabled: boolean; favorToDonate: number; - p: IPlayer; rerender: () => void; }; @@ -35,7 +34,7 @@ export function DonateOption(props: IProps): React.ReactElement { function canDonate(): boolean { if (isNaN(donateAmt)) return false; if (isNaN(donateAmt) || donateAmt <= 0) return false; - if (props.p.money < donateAmt) return false; + if (Player.money < donateAmt) return false; return true; } @@ -44,8 +43,8 @@ export function DonateOption(props: IProps): React.ReactElement { const amt = donateAmt; if (isNaN(amt)) return; if (!canDonate()) return; - props.p.loseMoney(amt, "other"); - const repGain = repFromDonation(amt, props.p); + Player.loseMoney(amt, "other"); + const repGain = repFromDonation(amt, Player); props.faction.playerReputation += repGain; dialogBoxCreate( <> @@ -58,12 +57,12 @@ export function DonateOption(props: IProps): React.ReactElement { function Status(): React.ReactElement { if (isNaN(donateAmt)) return <>; if (!canDonate()) { - if (props.p.money < donateAmt) return Insufficient funds; + if (Player.money < donateAmt) return Insufficient funds; return Invalid donate amount entered!; } return ( - This donation will result in reputation gain + This donation will result in reputation gain ); } diff --git a/src/Faction/ui/FactionRoot.tsx b/src/Faction/ui/FactionRoot.tsx index ef5ad72fd..7e633b2d9 100644 --- a/src/Faction/ui/FactionRoot.tsx +++ b/src/Faction/ui/FactionRoot.tsx @@ -15,7 +15,8 @@ import { CONSTANTS } from "../../Constants"; import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers"; import { Faction } from "../Faction"; -import { use } from "../../ui/Context"; +import { Router } from "../../ui/GameRoot"; +import { Player } from "../../Player"; import { Typography, Button } from "@mui/material"; import { CovenantPurchasesRoot } from "../../PersonObjects/Sleeve/ui/CovenantPurchasesRoot"; @@ -58,18 +59,16 @@ interface IMainProps { } function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.ReactElement { - const player = use.Player(); - const router = use.Router(); const [sleevesOpen, setSleevesOpen] = useState(false); const factionInfo = faction.getInfo(); function startWork(): void { - player.startFocusing(); - router.toWork(); + Player.startFocusing(); + Router.toWork(); } function startFieldWork(faction: Faction): void { - player.startWork( + Player.startWork( new FactionWork({ singularity: false, faction: faction.name, @@ -80,7 +79,7 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea } function startHackingContracts(faction: Faction): void { - player.startWork( + Player.startWork( new FactionWork({ singularity: false, faction: faction.name, @@ -91,7 +90,7 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea } function startSecurityWork(faction: Faction): void { - player.startWork( + Player.startWork( new FactionWork({ singularity: false, faction: faction.name, @@ -103,18 +102,18 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea // We have a special flag for whether the player this faction is the player's // gang faction because if the player has a gang, they cannot do any other action - const isPlayersGang = player.inGang() && player.getGangName() === faction.name; + const isPlayersGang = Player.inGang() && Player.getGangName() === faction.name; // Flags for whether special options (gang, sleeve purchases, donate, etc.) // should be shown const favorToDonate = Math.floor(CONSTANTS.BaseFavorToDonate * BitNodeMultipliers.RepToDonateToFaction); const canDonate = faction.favor >= favorToDonate; - const canPurchaseSleeves = faction.name === FactionNames.TheCovenant && player.bitNodeN === 10; + const canPurchaseSleeves = faction.name === FactionNames.TheCovenant && Player.bitNodeN === 10; return ( <> - + {faction.name} @@ -134,13 +133,7 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea - {getGraftingAvailableAugs(player).length > 0 ? ( + {getGraftingAvailableAugs().length > 0 ? ( {getAugsSorted().map((k, i) => ( setSelectedAug(k)} selected={selectedAug === k}> { @@ -158,21 +153,20 @@ export const GraftingRoot = (): React.ReactElement => { open={graftOpen} onClose={() => setGraftOpen(false)} onConfirm={() => { - player.startWork( + Player.startWork( new GraftingWork({ augmentation: selectedAug, singularity: false, - player: player, }), ); - player.startFocusing(); - router.toWork(); + Player.startFocusing(); + Router.toWork(); }} confirmationText={ <> Cancelling grafting will not save grafting progress, and the money you spend will not{" "} be returned. - {!player.hasAugmentation(AugmentationNames.CongruityImplant) && ( + {!Player.hasAugmentation(AugmentationNames.CongruityImplant) && ( <>

    @@ -186,14 +180,12 @@ export const GraftingRoot = (): React.ReactElement => { Time to Graft:{" "} {convertTimeMsToTimeElapsedString( - calculateGraftingTimeWithBonus(player, graftableAugmentations[selectedAug]), + calculateGraftingTimeWithBonus(graftableAugmentations[selectedAug]), )} {/* Use formula so the displayed creation time is accurate to player bonus */} - {selectedAugmentation.prereqs.length > 0 && ( - - )} + {selectedAugmentation.prereqs.length > 0 && }
    @@ -229,10 +221,10 @@ export const GraftingRoot = (): React.ReactElement => { - Entropy strength: {player.entropy} + Entropy strength: {Player.entropy}
    All multipliers decreased by:{" "} - {formatNumber((1 - CONSTANTS.EntropyEffect ** player.entropy) * 100, 3)}% (multiplicative) + {formatNumber((1 - CONSTANTS.EntropyEffect ** Player.entropy) * 100, 3)}% (multiplicative)
    diff --git a/src/PersonObjects/Player/PlayerObjectAugmentationMethods.ts b/src/PersonObjects/Player/PlayerObjectAugmentationMethods.ts index 58accbe73..d7cd35177 100644 --- a/src/PersonObjects/Player/PlayerObjectAugmentationMethods.ts +++ b/src/PersonObjects/Player/PlayerObjectAugmentationMethods.ts @@ -32,5 +32,5 @@ export function applyEntropy(this: IPlayer, stacks = 1): void { this.reapplyAllAugmentations(); this.reapplyAllSourceFiles(); - this.mults = calculateEntropy(this, stacks); + this.mults = calculateEntropy(stacks); } diff --git a/src/PersonObjects/Player/PlayerObjectBladeburnerMethods.ts b/src/PersonObjects/Player/PlayerObjectBladeburnerMethods.ts index ee0d9e8e9..cf8d9e2ce 100644 --- a/src/PersonObjects/Player/PlayerObjectBladeburnerMethods.ts +++ b/src/PersonObjects/Player/PlayerObjectBladeburnerMethods.ts @@ -13,5 +13,5 @@ export function inBladeburner(this: IPlayer): boolean { } export function startBladeburner(this: IPlayer): void { - this.bladeburner = new Bladeburner(this); + this.bladeburner = new Bladeburner(); } diff --git a/src/PersonObjects/Player/PlayerObjectGeneralMethods.ts b/src/PersonObjects/Player/PlayerObjectGeneralMethods.ts index fed24e61d..dc13eb4d7 100644 --- a/src/PersonObjects/Player/PlayerObjectGeneralMethods.ts +++ b/src/PersonObjects/Player/PlayerObjectGeneralMethods.ts @@ -112,15 +112,15 @@ export function prestigeAugmentation(this: PlayerObject): void { const numSleeves = Math.min(3, this.sourceFileLvl(10) + (this.bitNodeN === 10 ? 1 : 0)) + this.sleevesFromCovenant; if (this.sleeves.length > numSleeves) this.sleeves.length = numSleeves; for (let i = this.sleeves.length; i < numSleeves; i++) { - this.sleeves.push(new Sleeve(this)); + this.sleeves.push(new Sleeve()); } for (let i = 0; i < this.sleeves.length; ++i) { if (this.sleeves[i] instanceof Sleeve) { if (this.sleeves[i].shock >= 100) { - this.sleeves[i].synchronize(this); + this.sleeves[i].synchronize(); } else { - this.sleeves[i].shockRecovery(this); + this.sleeves[i].shockRecovery(); } } } @@ -149,9 +149,9 @@ export function prestigeSourceFile(this: IPlayer): void { // Duplicate sleeves are reset to level 1 every Bit Node (but the number of sleeves you have persists) for (let i = 0; i < this.sleeves.length; ++i) { if (this.sleeves[i] instanceof Sleeve) { - this.sleeves[i].prestige(this); + this.sleeves[i].prestige(); } else { - this.sleeves[i] = new Sleeve(this); + this.sleeves[i] = new Sleeve(); } } @@ -490,7 +490,7 @@ export function regenerateHp(this: IPerson, amt: number): void { } export function hospitalize(this: IPlayer): number { - const cost = getHospitalizationCost(this); + const cost = getHospitalizationCost(); SnackbarEvents.emit(`You've been Hospitalized for ${numeralWrapper.formatMoney(cost)}`, ToastVariant.WARNING, 2000); this.loseMoney(cost, "hospitalization"); @@ -596,7 +596,7 @@ export function quitJob(this: IPlayer, company: string): void { } for (const sleeve of this.sleeves) { if (isSleeveCompanyWork(sleeve.currentWork) && sleeve.currentWork.companyName === company) { - sleeve.stopWork(this); + sleeve.stopWork(); dialogBoxCreate(`You quit ${company} while one of your sleeves was working there. The sleeve is now idle.`); } } diff --git a/src/PersonObjects/Player/PlayerObjectWorkMethods.ts b/src/PersonObjects/Player/PlayerObjectWorkMethods.ts index 949e1774f..c2c306db5 100644 --- a/src/PersonObjects/Player/PlayerObjectWorkMethods.ts +++ b/src/PersonObjects/Player/PlayerObjectWorkMethods.ts @@ -3,20 +3,20 @@ import { IPlayer } from "../IPlayer"; export function start(this: IPlayer, w: Work): void { if (this.currentWork !== null) { - this.currentWork.finish(this, true); + this.currentWork.finish(true); } this.currentWork = w; } export function process(this: IPlayer, cycles = 1): void { if (this.currentWork === null) return; - const finished = this.currentWork.process(this, cycles); + const finished = this.currentWork.process(cycles); if (finished) { this.finishWork(false); } } export function finish(this: IPlayer, cancelled: boolean): void { if (this.currentWork === null) return; - this.currentWork.finish(this, cancelled); + this.currentWork.finish(cancelled); this.currentWork = null; this.focus = false; } diff --git a/src/PersonObjects/Sleeve/Sleeve.ts b/src/PersonObjects/Sleeve/Sleeve.ts index 693aa0d20..189496e75 100644 --- a/src/PersonObjects/Sleeve/Sleeve.ts +++ b/src/PersonObjects/Sleeve/Sleeve.ts @@ -7,7 +7,7 @@ * Sleeves are unlocked in BitNode-10. */ -import { IPlayer } from "../IPlayer"; +import { Player } from "../../Player"; import { Person } from "../Person"; import { Augmentation } from "../../Augmentation/Augmentation"; @@ -74,11 +74,9 @@ export class Sleeve extends Person { */ sync = 1; - constructor(p: IPlayer | null = null) { + constructor() { super(); - if (p != null) { - this.shockRecovery(p); - } + this.shockRecovery(); } shockBonus(): number { @@ -89,26 +87,26 @@ export class Sleeve extends Person { return this.sync / 100; } - startWork(player: IPlayer, w: Work): void { - if (this.currentWork) this.currentWork.finish(player); + startWork(w: Work): void { + if (this.currentWork) this.currentWork.finish(); this.currentWork = w; } - stopWork(player: IPlayer): void { - if (this.currentWork) this.currentWork.finish(player); + stopWork(): void { + if (this.currentWork) this.currentWork.finish(); this.currentWork = null; } /** * Commit crimes */ - commitCrime(p: IPlayer, crimeKey: string): boolean { + commitCrime(crimeKey: string): boolean { const crime: Crime | null = Crimes[crimeKey] || Object.values(Crimes).find((crime) => crime.name === crimeKey); if (!crime) { return false; } - this.startWork(p, new SleeveCrimeWork(crime.type)); + this.startWork(new SleeveCrimeWork(crime.type)); return true; } @@ -152,7 +150,7 @@ export class Sleeve extends Person { /** * Called on every sleeve for a Source File Prestige */ - prestige(p: IPlayer): void { + prestige(): void { // Reset exp this.exp.hacking = 0; this.exp.strength = 0; @@ -164,8 +162,8 @@ export class Sleeve extends Person { this.hp.current = this.hp.max; // Reset task-related stuff - this.stopWork(p); - this.shockRecovery(p); + this.stopWork(); + this.shockRecovery(); // Reset augs and multipliers this.augmentations = []; @@ -186,7 +184,7 @@ export class Sleeve extends Person { * Returns an object containing the amount of experience that should be * transferred to all other sleeves */ - process(p: IPlayer, numCycles = 1): void { + process(numCycles = 1): void { // Only process once every second (5 cycles) const CyclesPerSecond = 1000 / CONSTANTS.MilliPerCycle; this.storedCycles += numCycles; @@ -196,24 +194,24 @@ export class Sleeve extends Person { cyclesUsed = Math.min(cyclesUsed, 15); this.shock = Math.min(100, this.shock + 0.0001 * cyclesUsed); if (!this.currentWork) return; - this.currentWork.process(p, this, cyclesUsed); + this.currentWork.process(this, cyclesUsed); this.storedCycles -= cyclesUsed; } - shockRecovery(p: IPlayer): boolean { - this.startWork(p, new SleeveRecoveryWork()); + shockRecovery(): boolean { + this.startWork(new SleeveRecoveryWork()); return true; } - synchronize(p: IPlayer): boolean { - this.startWork(p, new SleeveSynchroWork()); + synchronize(): boolean { + this.startWork(new SleeveSynchroWork()); return true; } /** * Take a course at a university */ - takeUniversityCourse(p: IPlayer, universityName: string, className: string): boolean { + takeUniversityCourse(universityName: string, className: string): boolean { // Set exp/money multipliers based on which university. // Also check that the sleeve is in the right city let loc: LocationName | undefined; @@ -261,7 +259,6 @@ export class Sleeve extends Person { if (!classType) return false; this.startWork( - p, new SleeveClassWork({ classType: classType, location: loc, @@ -273,8 +270,8 @@ export class Sleeve extends Person { /** * Travel to another City. Costs money from player */ - travel(p: IPlayer, newCity: CityName): boolean { - p.loseMoney(CONSTANTS.TravelCost, "sleeves"); + travel(newCity: CityName): boolean { + Player.loseMoney(CONSTANTS.TravelCost, "sleeves"); this.city = newCity; return true; @@ -284,13 +281,15 @@ export class Sleeve extends Person { return this.augmentations.some((a) => a.name === aug); } - tryBuyAugmentation(p: IPlayer, aug: Augmentation): boolean { - if (!p.canAfford(aug.baseCost)) return false; + tryBuyAugmentation(aug: Augmentation): boolean { + if (!Player.canAfford(aug.baseCost)) { + return false; + } // Verify that this sleeve does not already have that augmentation. if (this.hasAugmentation(aug.name)) return false; - p.loseMoney(aug.baseCost, "sleeves"); + Player.loseMoney(aug.baseCost, "sleeves"); this.installAugmentation(aug); return true; } @@ -303,17 +302,17 @@ export class Sleeve extends Person { * Start work for one of the player's companies * Returns boolean indicating success */ - workForCompany(p: IPlayer, companyName: string): boolean { - if (!(Companies[companyName] instanceof Company) || p.jobs[companyName] == null) { + workForCompany(companyName: string): boolean { + if (!(Companies[companyName] instanceof Company) || Player.jobs[companyName] == null) { return false; } const company: Company | null = Companies[companyName]; - const companyPosition: CompanyPosition | null = CompanyPositions[p.jobs[companyName]]; + const companyPosition: CompanyPosition | null = CompanyPositions[Player.jobs[companyName]]; if (company == null) return false; if (companyPosition == null) return false; - this.startWork(p, new SleeveCompanyWork({ companyName: companyName })); + this.startWork(new SleeveCompanyWork({ companyName: companyName })); return true; } @@ -322,9 +321,9 @@ export class Sleeve extends Person { * Start work for one of the player's factions * Returns boolean indicating success */ - workForFaction(p: IPlayer, factionName: string, workType: string): boolean { + workForFaction(factionName: string, workType: string): boolean { const faction = Factions[factionName]; - if (factionName === "" || !faction || !(faction instanceof Faction) || !p.factions.includes(factionName)) { + if (factionName === "" || !faction || !(faction instanceof Faction) || !Player.factions.includes(factionName)) { return false; } @@ -347,7 +346,6 @@ export class Sleeve extends Person { } this.startWork( - p, new SleeveFactionWork({ factionWorkType: factionWorkType, factionName: faction.name, @@ -360,7 +358,7 @@ export class Sleeve extends Person { /** * Begin a gym workout task */ - workoutAtGym(p: IPlayer, gymName: string, stat: string): boolean { + workoutAtGym(gymName: string, stat: string): boolean { // Set exp/money multipliers based on which university. // Also check that the sleeve is in the right city let loc: LocationName | undefined; @@ -414,7 +412,6 @@ export class Sleeve extends Person { if (!classType) return false; this.startWork( - p, new SleeveClassWork({ classType: classType, location: loc, @@ -427,41 +424,41 @@ export class Sleeve extends Person { /** * Begin a bladeburner task */ - bladeburner(p: IPlayer, action: string, contract: string): boolean { + bladeburner(action: string, contract: string): boolean { switch (action) { case "Field analysis": - this.startWork(p, new SleeveBladeburnerWork({ type: "General", name: "Field Analysis" })); + this.startWork(new SleeveBladeburnerWork({ type: "General", name: "Field Analysis" })); return true; case "Recruitment": - this.startWork(p, new SleeveBladeburnerWork({ type: "General", name: "Recruitment" })); + this.startWork(new SleeveBladeburnerWork({ type: "General", name: "Recruitment" })); return true; case "Diplomacy": - this.startWork(p, new SleeveBladeburnerWork({ type: "General", name: "Diplomacy" })); + this.startWork(new SleeveBladeburnerWork({ type: "General", name: "Diplomacy" })); return true; case "Hyperbolic Regeneration Chamber": - this.startWork(p, new SleeveBladeburnerWork({ type: "General", name: "Hyperbolic Regeneration Chamber" })); + this.startWork(new SleeveBladeburnerWork({ type: "General", name: "Hyperbolic Regeneration Chamber" })); return true; case "Infiltrate synthoids": - this.startWork(p, new SleeveInfiltrateWork()); + this.startWork(new SleeveInfiltrateWork()); return true; case "Support main sleeve": - this.startWork(p, new SleeveSupportWork(p)); + this.startWork(new SleeveSupportWork()); return true; case "Take on contracts": if (!Contracts[contract]) return false; - this.startWork(p, new SleeveBladeburnerWork({ type: "Contracts", name: contract })); + this.startWork(new SleeveBladeburnerWork({ type: "Contracts", name: contract })); return true; } return false; } - recruitmentSuccessChance(p: IPlayer): number { - return Math.max(0, Math.min(1, p.bladeburner?.getRecruitmentSuccessChance(this) ?? 0)); + recruitmentSuccessChance(): number { + return Math.max(0, Math.min(1, Player.bladeburner?.getRecruitmentSuccessChance(this) ?? 0)); } - contractSuccessChance(p: IPlayer, type: string, name: string): string { - const bb = p.bladeburner; + contractSuccessChance(type: string, name: string): string { + const bb = Player.bladeburner; if (bb === null) { const errorLogText = `bladeburner is null`; console.error(`Function: sleeves.contractSuccessChance; Message: '${errorLogText}'`); diff --git a/src/PersonObjects/Sleeve/SleeveHelpers.ts b/src/PersonObjects/Sleeve/SleeveHelpers.ts index 3aa4aefc8..87460fe4c 100644 --- a/src/PersonObjects/Sleeve/SleeveHelpers.ts +++ b/src/PersonObjects/Sleeve/SleeveHelpers.ts @@ -1,7 +1,6 @@ import { FactionNames } from "../../Faction/data/FactionNames"; import { Sleeve } from "./Sleeve"; -import { IPlayer } from "../IPlayer"; import { Player } from "../../Player"; import { Augmentation } from "../../Augmentation/Augmentation"; @@ -11,7 +10,7 @@ import { Multipliers } from "../Multipliers"; import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { getFactionAugmentationsFiltered } from "../../Faction/FactionHelpers"; -export function findSleevePurchasableAugs(sleeve: Sleeve, p: IPlayer): Augmentation[] { +export function findSleevePurchasableAugs(sleeve: Sleeve): Augmentation[] { // You can only purchase Augmentations that are actually available from // your factions. I.e. you must be in a faction that has the Augmentation // and you must also have enough rep in that faction in order to purchase it. @@ -55,21 +54,21 @@ export function findSleevePurchasableAugs(sleeve: Sleeve, p: IPlayer): Augmentat // If player is in a gang, then we return all augs that the player // has enough reputation for (since that gang offers all augs) - if (p.inGang()) { - const fac = p.getGangFaction(); - const gangAugs = getFactionAugmentationsFiltered(Player, fac); + if (Player.inGang()) { + const fac = Player.getGangFaction(); + const gangAugs = getFactionAugmentationsFiltered(fac); for (const augName of gangAugs) { const aug = StaticAugmentations[augName]; if (!isAvailableForSleeve(aug)) continue; - if (fac.playerReputation > aug.getCost(p).repCost) { + if (fac.playerReputation > aug.getCost().repCost) { availableAugs.push(aug); } } } - for (const facName of p.factions) { + for (const facName of Player.factions) { if (facName === FactionNames.Bladeburners) continue; if (facName === FactionNames.Netburners) continue; const fac = Factions[facName]; @@ -79,7 +78,7 @@ export function findSleevePurchasableAugs(sleeve: Sleeve, p: IPlayer): Augmentat const aug = StaticAugmentations[augName]; if (!isAvailableForSleeve(aug)) continue; - if (fac.playerReputation > aug.getCost(p).repCost) { + if (fac.playerReputation > aug.getCost().repCost) { availableAugs.push(aug); } } diff --git a/src/PersonObjects/Sleeve/Work/SleeveBladeburnerWork.ts b/src/PersonObjects/Sleeve/Work/SleeveBladeburnerWork.ts index 198357a98..cd4de69de 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveBladeburnerWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveBladeburnerWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { applySleeveGains, Work, WorkType } from "./Work"; @@ -25,45 +25,45 @@ export class SleeveBladeburnerWork extends Work { this.actionName = params?.name ?? "Field analysis"; } - cyclesNeeded(player: IPlayer, sleeve: Sleeve): number { - const ret = player.bladeburner?.getActionTimeNetscriptFn(sleeve, this.actionType, this.actionName); + cyclesNeeded(sleeve: Sleeve): number { + const ret = Player.bladeburner?.getActionTimeNetscriptFn(sleeve, this.actionType, this.actionName); if (!ret || typeof ret === "string") throw new Error(`Error querying ${this.actionName} time`); return ret / CONSTANTS._idleSpeed; } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { - if (!player.bladeburner) throw new Error("sleeve doing blade work without being a member"); + process(sleeve: Sleeve, cycles: number): number { + if (!Player.bladeburner) throw new Error("sleeve doing blade work without being a member"); this.cyclesWorked += cycles; - const actionIdent = player.bladeburner.getActionIdFromTypeAndName(this.actionType, this.actionName); + const actionIdent = Player.bladeburner.getActionIdFromTypeAndName(this.actionType, this.actionName); if (!actionIdent) throw new Error(`Error getting ${this.actionName} action`); if (this.actionType === "Contracts") { - const action = player.bladeburner.getActionObject(actionIdent); + const action = Player.bladeburner.getActionObject(actionIdent); if (!action) throw new Error(`Error getting ${this.actionName} action object`); if (action.count <= 0) { - sleeve.stopWork(player); + sleeve.stopWork(); return 0; } } - while (this.cyclesWorked > this.cyclesNeeded(player, sleeve)) { + while (this.cyclesWorked > this.cyclesNeeded(sleeve)) { if (this.actionType === "Contracts") { - const action = player.bladeburner.getActionObject(actionIdent); + const action = Player.bladeburner.getActionObject(actionIdent); if (!action) throw new Error(`Error getting ${this.actionName} action object`); if (action.count <= 0) { - sleeve.stopWork(player); + sleeve.stopWork(); return 0; } } - const retValue = player.bladeburner.completeAction(player, sleeve, actionIdent, false); + const retValue = Player.bladeburner.completeAction(sleeve, actionIdent, false); let exp: WorkStats | undefined; if (this.actionType === "General") { exp = GeneralActions[this.actionName]?.exp; if (!exp) throw new Error(`Somehow there was no exp for action ${this.actionType} ${this.actionName}`); - applySleeveGains(player, sleeve, exp, 1); + applySleeveGains(sleeve, exp, 1); } - player.gainMoney(retValue.money, "sleeves"); - player.gainStats(retValue); - this.cyclesWorked -= this.cyclesNeeded(player, sleeve); + Player.gainMoney(retValue.money, "sleeves"); + Player.gainStats(retValue); + this.cyclesWorked -= this.cyclesNeeded(sleeve); } return 0; } diff --git a/src/PersonObjects/Sleeve/Work/SleeveClassWork.ts b/src/PersonObjects/Sleeve/Work/SleeveClassWork.ts index ee498fd49..8d8213c6f 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveClassWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveClassWork.ts @@ -24,9 +24,9 @@ export class SleeveClassWork extends Work { this.location = params?.location ?? LocationName.Sector12RothmanUniversity; } - calculateRates(player: IPlayer, sleeve: Sleeve): WorkStats { + calculateRates(sleeve: Sleeve): WorkStats { return scaleWorkStats( - calculateClassEarnings(player, sleeve, this.classType, this.location), + calculateClassEarnings(sleeve, this.classType, this.location), sleeve.shockBonus(), false, ); @@ -38,9 +38,9 @@ export class SleeveClassWork extends Work { ); } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { - const rate = this.calculateRates(player, sleeve); - applySleeveGains(player, sleeve, rate, cycles); + process(sleeve: Sleeve, cycles: number): number { + const rate = this.calculateRates(sleeve); + applySleeveGains(sleeve, rate, cycles); return 0; } APICopy(): Record { diff --git a/src/PersonObjects/Sleeve/Work/SleeveCompanyWork.ts b/src/PersonObjects/Sleeve/Work/SleeveCompanyWork.ts index 70a80216f..795f3d451 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveCompanyWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveCompanyWork.ts @@ -30,14 +30,14 @@ export class SleeveCompanyWork extends Work { return c; } - getGainRates(player: IPlayer, sleeve: Sleeve): WorkStats { - return calculateCompanyWorkStats(player, sleeve, this.getCompany()); + getGainRates(sleeve: Sleeve): WorkStats { + return calculateCompanyWorkStats(sleeve, this.getCompany()); } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { + process(sleeve: Sleeve, cycles: number): number { const company = this.getCompany(); - const gains = this.getGainRates(player, sleeve); - applySleeveGains(player, sleeve, gains, cycles); + const gains = this.getGainRates(sleeve); + applySleeveGains(sleeve, gains, cycles); company.playerReputation += gains.reputation * cycles; influenceStockThroughCompanyWork(company, gains.reputation, cycles); return 0; diff --git a/src/PersonObjects/Sleeve/Work/SleeveCrimeWork.ts b/src/PersonObjects/Sleeve/Work/SleeveCrimeWork.ts index 30aa8c847..75d315452 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveCrimeWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveCrimeWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { applySleeveGains, Work, WorkType } from "./Work"; @@ -43,19 +43,19 @@ export class SleeveCrimeWork extends Work { return this.getCrime().time / CONSTANTS._idleSpeed; } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { + process(sleeve: Sleeve, cycles: number): number { this.cyclesWorked += cycles; const crime = this.getCrime(); let gains = this.getExp(); if (this.cyclesWorked >= this.cyclesNeeded()) { if (Math.random() < crime.successRate(sleeve)) { - player.karma -= crime.karma * sleeve.syncBonus(); + Player.karma -= crime.karma * sleeve.syncBonus(); } else { gains.money = 0; gains = scaleWorkStats(gains, 0.25); } - applySleeveGains(player, sleeve, gains, cycles); + applySleeveGains(sleeve, gains, cycles); this.cyclesWorked -= this.cyclesNeeded(); } return 0; diff --git a/src/PersonObjects/Sleeve/Work/SleeveFactionWork.ts b/src/PersonObjects/Sleeve/Work/SleeveFactionWork.ts index 398374f37..d4df44ba5 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveFactionWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveFactionWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { applySleeveGains, Work, WorkType } from "./Work"; @@ -57,16 +57,14 @@ export class SleeveFactionWork extends Work { return f; } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { - if (player.gang) { - if (this.factionName === player.gang.facName) { - sleeve.stopWork(player); - return 0; - } + process(sleeve: Sleeve, cycles: number): number { + if (this.factionName === Player.gang?.facName) { + sleeve.stopWork(); + return 0; } const exp = this.getExpRates(sleeve); - applySleeveGains(player, sleeve, exp, cycles); + applySleeveGains(sleeve, exp, cycles); const rep = this.getReputationRate(sleeve); this.getFaction().playerReputation += rep; return 0; diff --git a/src/PersonObjects/Sleeve/Work/SleeveInfiltrateWork.ts b/src/PersonObjects/Sleeve/Work/SleeveInfiltrateWork.ts index 1ad321e92..d0cf4f217 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveInfiltrateWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveInfiltrateWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { Work, WorkType } from "./Work"; @@ -20,12 +20,12 @@ export class SleeveInfiltrateWork extends Work { return infiltrateCycles; } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { - if (!player.bladeburner) throw new Error("sleeve doing blade work without being a member"); + process(_sleeve: Sleeve, cycles: number): number { + if (!Player.bladeburner) throw new Error("sleeve doing blade work without being a member"); this.cyclesWorked += cycles; if (this.cyclesWorked > this.cyclesNeeded()) { this.cyclesWorked -= this.cyclesNeeded(); - player.bladeburner.infiltrateSynthoidCommunities(player); + Player.bladeburner.infiltrateSynthoidCommunities(); } return 0; } diff --git a/src/PersonObjects/Sleeve/Work/SleeveRecoveryWork.ts b/src/PersonObjects/Sleeve/Work/SleeveRecoveryWork.ts index 5f0de0a5d..98707b6fc 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveRecoveryWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveRecoveryWork.ts @@ -1,4 +1,3 @@ -import { IPlayer } from "../../IPlayer"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { Work, WorkType } from "./Work"; @@ -11,9 +10,9 @@ export class SleeveRecoveryWork extends Work { super(WorkType.RECOVERY); } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { + process(sleeve: Sleeve, cycles: number): number { sleeve.shock = Math.min(100, sleeve.shock + 0.0002 * cycles); - if (sleeve.shock >= 100) sleeve.stopWork(player); + if (sleeve.shock >= 100) sleeve.stopWork(); return 0; } diff --git a/src/PersonObjects/Sleeve/Work/SleeveSupportWork.ts b/src/PersonObjects/Sleeve/Work/SleeveSupportWork.ts index 5dfa02b7c..86d34184a 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveSupportWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveSupportWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../../PersonObjects/IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Work, WorkType } from "./Work"; @@ -6,17 +6,17 @@ export const isSleeveSupportWork = (w: Work | null): w is SleeveSupportWork => w !== null && w.type === WorkType.SUPPORT; export class SleeveSupportWork extends Work { - constructor(player?: IPlayer) { + constructor() { super(WorkType.SUPPORT); - if (player) player.bladeburner?.sleeveSupport(true); + Player.bladeburner?.sleeveSupport(true); } process(): number { return 0; } - finish(player: IPlayer): void { - player.bladeburner?.sleeveSupport(false); + finish(): void { + Player.bladeburner?.sleeveSupport(false); } APICopy(): Record { diff --git a/src/PersonObjects/Sleeve/Work/SleeveSynchroWork.ts b/src/PersonObjects/Sleeve/Work/SleeveSynchroWork.ts index 09b5584d3..54d52fe56 100644 --- a/src/PersonObjects/Sleeve/Work/SleeveSynchroWork.ts +++ b/src/PersonObjects/Sleeve/Work/SleeveSynchroWork.ts @@ -1,4 +1,4 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, Reviver } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { Work, WorkType } from "./Work"; @@ -11,9 +11,9 @@ export class SleeveSynchroWork extends Work { super(WorkType.SYNCHRO); } - process(player: IPlayer, sleeve: Sleeve, cycles: number): number { - sleeve.sync = Math.min(100, sleeve.sync + player.getIntelligenceBonus(0.5) * 0.0002 * cycles); - if (sleeve.sync >= 100) sleeve.stopWork(player); + process(sleeve: Sleeve, cycles: number): number { + sleeve.sync = Math.min(100, sleeve.sync + Player.getIntelligenceBonus(0.5) * 0.0002 * cycles); + if (sleeve.sync >= 100) sleeve.stopWork(); return 0; } diff --git a/src/PersonObjects/Sleeve/Work/Work.ts b/src/PersonObjects/Sleeve/Work/Work.ts index 201b73015..b588a99bd 100644 --- a/src/PersonObjects/Sleeve/Work/Work.ts +++ b/src/PersonObjects/Sleeve/Work/Work.ts @@ -1,14 +1,14 @@ -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { IReviverValue } from "../../../utils/JSONReviver"; import { Sleeve } from "../Sleeve"; import { applyWorkStats, applyWorkStatsExp, scaleWorkStats, WorkStats } from "../../../Work/WorkStats"; -export const applySleeveGains = (player: IPlayer, sleeve: Sleeve, rawStats: WorkStats, cycles = 1): void => { +export const applySleeveGains = (sleeve: Sleeve, rawStats: WorkStats, cycles = 1): void => { const shockedStats = scaleWorkStats(rawStats, sleeve.shockBonus(), rawStats.money > 0); applyWorkStatsExp(sleeve, shockedStats, cycles); const syncStats = scaleWorkStats(shockedStats, sleeve.syncBonus(), rawStats.money > 0); - applyWorkStats(player, player, syncStats, cycles, "sleeves"); - player.sleeves.filter((s) => s != sleeve).forEach((s) => applyWorkStatsExp(s, syncStats, cycles)); + applyWorkStats(Player, syncStats, cycles, "sleeves"); + Player.sleeves.filter((s) => s !== sleeve).forEach((s) => applyWorkStatsExp(s, syncStats, cycles)); }; export abstract class Work { @@ -18,10 +18,10 @@ export abstract class Work { this.type = type; } - abstract process(player: IPlayer, sleeve: Sleeve, cycles: number): number; + abstract process(sleeve: Sleeve, cycles: number): number; abstract APICopy(): Record; abstract toJSON(): IReviverValue; - finish(__player: IPlayer): void { + finish(): void { /* left for children to implement */ } } diff --git a/src/PersonObjects/Sleeve/ui/CovenantPurchasesRoot.tsx b/src/PersonObjects/Sleeve/ui/CovenantPurchasesRoot.tsx index 10278017b..0fb597bc9 100644 --- a/src/PersonObjects/Sleeve/ui/CovenantPurchasesRoot.tsx +++ b/src/PersonObjects/Sleeve/ui/CovenantPurchasesRoot.tsx @@ -56,7 +56,7 @@ export function CovenantPurchasesRoot(props: IProps): React.ReactElement { if (player.canAfford(purchaseCost())) { player.loseMoney(purchaseCost(), "sleeves"); player.sleevesFromCovenant += 1; - player.sleeves.push(new Sleeve(player)); + player.sleeves.push(new Sleeve()); rerender(); } else { dialogBoxCreate(`You cannot afford to purchase a Duplicate Sleeve`); @@ -67,7 +67,7 @@ export function CovenantPurchasesRoot(props: IProps): React.ReactElement { const upgradePanels = []; for (let i = 0; i < player.sleeves.length; ++i) { const sleeve = player.sleeves[i]; - upgradePanels.push(); + upgradePanels.push(); } return ( @@ -81,7 +81,7 @@ export function CovenantPurchasesRoot(props: IProps): React.ReactElement {
    )} diff --git a/src/PersonObjects/Sleeve/ui/CovenantSleeveMemoryUpgrade.tsx b/src/PersonObjects/Sleeve/ui/CovenantSleeveMemoryUpgrade.tsx index ce1d81317..79219d993 100644 --- a/src/PersonObjects/Sleeve/ui/CovenantSleeveMemoryUpgrade.tsx +++ b/src/PersonObjects/Sleeve/ui/CovenantSleeveMemoryUpgrade.tsx @@ -5,7 +5,7 @@ import React, { useState } from "react"; import { Sleeve } from "../Sleeve"; -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { numeralWrapper } from "../../../ui/numeralFormat"; import { Money } from "../../../ui/React/Money"; @@ -18,7 +18,6 @@ import Paper from "@mui/material/Paper"; interface IProps { index: number; - p: IPlayer; rerender: () => void; sleeve: Sleeve; } @@ -52,16 +51,16 @@ export function CovenantSleeveMemoryUpgrade(props: IProps): React.ReactElement { function purchaseMemory(): void { const cost = getPurchaseCost(); - if (props.p.canAfford(cost)) { + if (Player.canAfford(cost)) { props.sleeve.upgradeMemory(amt); - props.p.loseMoney(cost, "sleeves"); + Player.loseMoney(cost, "sleeves"); props.rerender(); } } // Purchase button props const cost = getPurchaseCost(); - const purchaseBtnDisabled = !props.p.canAfford(cost); + const purchaseBtnDisabled = !Player.canAfford(cost); let purchaseBtnContent = <>; if (isNaN(amt)) { purchaseBtnContent = <>Invalid value; @@ -69,7 +68,7 @@ export function CovenantSleeveMemoryUpgrade(props: IProps): React.ReactElement { purchaseBtnContent = ( <> Purchase {amt} memory -  - + ); } diff --git a/src/PersonObjects/Sleeve/ui/SleeveAugmentationsModal.tsx b/src/PersonObjects/Sleeve/ui/SleeveAugmentationsModal.tsx index 582ba3df5..76e5c73a3 100644 --- a/src/PersonObjects/Sleeve/ui/SleeveAugmentationsModal.tsx +++ b/src/PersonObjects/Sleeve/ui/SleeveAugmentationsModal.tsx @@ -1,7 +1,7 @@ import { Container, Typography, Paper } from "@mui/material"; import React, { useEffect, useState } from "react"; import { PurchasableAugmentations } from "../../../Augmentation/ui/PurchasableAugmentations"; -import { use } from "../../../ui/Context"; +import { Player } from "../../../Player"; import { Modal } from "../../../ui/React/Modal"; import { Sleeve } from "../Sleeve"; import { findSleevePurchasableAugs } from "../SleeveHelpers"; @@ -13,7 +13,6 @@ interface IProps { } export function SleeveAugmentationsModal(props: IProps): React.ReactElement { - const player = use.Player(); const setRerender = useState(false)[1]; function rerender(): void { setRerender((old) => !old); @@ -30,7 +29,7 @@ export function SleeveAugmentationsModal(props: IProps): React.ReactElement { // You can only purchase Augmentations that are actually available from // your factions. I.e. you must be in a faction that has the Augmentation // and you must also have enough rep in that faction in order to purchase it. - const availableAugs = findSleevePurchasableAugs(props.sleeve, player); + const availableAugs = findSleevePurchasableAugs(props.sleeve); return ( @@ -50,12 +49,11 @@ export function SleeveAugmentationsModal(props: IProps): React.ReactElement { aug.name)} ownedAugNames={ownedAugNames} - player={player} - canPurchase={(player, aug) => { - return player.money > aug.baseCost; + canPurchase={(aug) => { + return Player.money > aug.baseCost; }} - purchaseAugmentation={(player, aug) => { - props.sleeve.tryBuyAugmentation(player, aug); + purchaseAugmentation={(aug) => { + props.sleeve.tryBuyAugmentation(aug); rerender(); }} sleeveAugs diff --git a/src/PersonObjects/Sleeve/ui/SleeveElem.tsx b/src/PersonObjects/Sleeve/ui/SleeveElem.tsx index 93aaf55d0..4d76044c9 100644 --- a/src/PersonObjects/Sleeve/ui/SleeveElem.tsx +++ b/src/PersonObjects/Sleeve/ui/SleeveElem.tsx @@ -2,7 +2,7 @@ import { Box, Button, Paper, Tooltip, Typography } from "@mui/material"; import React, { useState } from "react"; import { FactionWorkType } from "../../../Work/data/FactionWorkType"; import { CONSTANTS } from "../../../Constants"; -import { use } from "../../../ui/Context"; +import { Player } from "../../../Player"; import { numeralWrapper } from "../../../ui/numeralFormat"; import { ProgressBar } from "../../../ui/React/Progress"; import { Sleeve } from "../Sleeve"; @@ -27,7 +27,6 @@ interface IProps { } export function SleeveElem(props: IProps): React.ReactElement { - const player = use.Player(); const [statsOpen, setStatsOpen] = useState(false); const [travelOpen, setTravelOpen] = useState(false); const [augmentationsOpen, setAugmentationsOpen] = useState(false); @@ -39,28 +38,28 @@ export function SleeveElem(props: IProps): React.ReactElement { case "------": break; case "Work for Company": - props.sleeve.workForCompany(player, abc[1]); + props.sleeve.workForCompany(abc[1]); break; case "Work for Faction": - props.sleeve.workForFaction(player, abc[1], abc[2]); + props.sleeve.workForFaction(abc[1], abc[2]); break; case "Commit Crime": - props.sleeve.commitCrime(player, abc[1]); + props.sleeve.commitCrime(abc[1]); break; case "Take University Course": - props.sleeve.takeUniversityCourse(player, abc[2], abc[1]); + props.sleeve.takeUniversityCourse(abc[2], abc[1]); break; case "Workout at Gym": - props.sleeve.workoutAtGym(player, abc[2], abc[1]); + props.sleeve.workoutAtGym(abc[2], abc[1]); break; case "Perform Bladeburner Actions": - props.sleeve.bladeburner(player, abc[1], abc[2]); + props.sleeve.bladeburner(abc[1], abc[2]); break; case "Shock Recovery": - props.sleeve.shockRecovery(player); + props.sleeve.shockRecovery(); break; case "Synchronize": - props.sleeve.synchronize(player); + props.sleeve.synchronize(); break; default: console.error(`Invalid/Unrecognized taskValue in setSleeveTask(): ${abc[0]}`); @@ -130,7 +129,7 @@ export function SleeveElem(props: IProps): React.ReactElement { desc = ( <> This sleeve is currently attempting to perform {w.actionName}. ( - {((100 * w.cyclesWorked) / w.cyclesNeeded(player, props.sleeve)).toFixed(2)}%) + {((100 * w.cyclesWorked) / w.cyclesNeeded(props.sleeve)).toFixed(2)}%) ); } @@ -156,11 +155,11 @@ export function SleeveElem(props: IProps): React.ReactElement { - Insufficient funds : ""}> + Insufficient funds : ""}> @@ -202,7 +201,7 @@ export function SleeveElem(props: IProps): React.ReactElement { variant="determinate" value={ (props.sleeve.currentWork.cyclesWorked / - props.sleeve.currentWork.cyclesNeeded(player, props.sleeve)) * + props.sleeve.currentWork.cyclesNeeded(props.sleeve)) * 100 } color="primary" diff --git a/src/PersonObjects/Sleeve/ui/StatsElement.tsx b/src/PersonObjects/Sleeve/ui/StatsElement.tsx index 542988092..b257491fc 100644 --- a/src/PersonObjects/Sleeve/ui/StatsElement.tsx +++ b/src/PersonObjects/Sleeve/ui/StatsElement.tsx @@ -9,7 +9,6 @@ import { characterOverviewStyles as useStyles } from "../../../ui/React/Characte import { Money } from "../../../ui/React/Money"; import { MoneyRate } from "../../../ui/React/MoneyRate"; import { ReputationRate } from "../../../ui/React/ReputationRate"; -import { use } from "../../../ui/Context"; import { Sleeve } from "../Sleeve"; import { isSleeveClassWork } from "../Work/SleeveClassWork"; @@ -95,7 +94,6 @@ export function StatsElement(props: IProps): React.ReactElement { export function EarningsElement(props: IProps): React.ReactElement { const classes = useStyles(); - const player = use.Player(); let data: (string | JSX.Element)[][] = []; if (isSleeveCrimeWork(props.sleeve.currentWork)) { @@ -111,7 +109,7 @@ export function EarningsElement(props: IProps): React.ReactElement { ]; } if (isSleeveClassWork(props.sleeve.currentWork)) { - const rates = props.sleeve.currentWork.calculateRates(player, props.sleeve); + const rates = props.sleeve.currentWork.calculateRates(props.sleeve); data = [ [`Money:`, ], [`Hacking Exp:`, `${numeralWrapper.formatExp(5 * rates.hackExp)} / sec`], @@ -137,7 +135,7 @@ export function EarningsElement(props: IProps): React.ReactElement { } if (isSleeveCompanyWork(props.sleeve.currentWork)) { - const rates = props.sleeve.currentWork.getGainRates(player, props.sleeve); + const rates = props.sleeve.currentWork.getGainRates(props.sleeve); data = [ [`Money:`, ], [`Hacking Exp:`, `${numeralWrapper.formatExp(5 * rates.hackExp)} / sec`], diff --git a/src/PersonObjects/Sleeve/ui/TaskSelector.tsx b/src/PersonObjects/Sleeve/ui/TaskSelector.tsx index 8df94de47..e6dde19ad 100644 --- a/src/PersonObjects/Sleeve/ui/TaskSelector.tsx +++ b/src/PersonObjects/Sleeve/ui/TaskSelector.tsx @@ -1,6 +1,6 @@ import React, { useState } from "react"; import { Sleeve } from "../Sleeve"; -import { IPlayer } from "../../IPlayer"; +import { Player } from "../../../Player"; import { Crimes } from "../../../Crime/Crimes"; import { LocationName } from "../../../Locations/data/LocationNames"; import { CityName } from "../../../Locations/data/CityNames"; @@ -43,7 +43,6 @@ const bladeburnerSelectorOptions: string[] = [ interface IProps { sleeve: Sleeve; - player: IPlayer; setABC: (abc: string[]) => void; } @@ -52,10 +51,10 @@ interface ITaskDetails { second: (s1: string) => string[]; } -function possibleJobs(player: IPlayer, sleeve: Sleeve): string[] { +function possibleJobs(sleeve: Sleeve): string[] { // Array of all companies that other sleeves are working at const forbiddenCompanies: string[] = []; - for (const otherSleeve of player.sleeves) { + for (const otherSleeve of Player.sleeves) { if (sleeve === otherSleeve) { continue; } @@ -63,18 +62,18 @@ function possibleJobs(player: IPlayer, sleeve: Sleeve): string[] { forbiddenCompanies.push(otherSleeve.currentWork.companyName); } } - const allJobs: string[] = Object.keys(player.jobs); + const allJobs: string[] = Object.keys(Player.jobs); return allJobs.filter((company) => !forbiddenCompanies.includes(company)); } -function possibleFactions(player: IPlayer, sleeve: Sleeve): string[] { +function possibleFactions(sleeve: Sleeve): string[] { // Array of all factions that other sleeves are working for const forbiddenFactions = [FactionNames.Bladeburners as string, FactionNames.ShadowsOfAnarchy as string]; - if (player.gang) { - forbiddenFactions.push(player.gang.facName); + if (Player.gang) { + forbiddenFactions.push(Player.gang.facName); } - for (const otherSleeve of player.sleeves) { + for (const otherSleeve of Player.sleeves) { if (sleeve === otherSleeve) { continue; } @@ -84,7 +83,7 @@ function possibleFactions(player: IPlayer, sleeve: Sleeve): string[] { } const factions = []; - for (const fac of player.factions) { + for (const fac of Player.factions) { if (!forbiddenFactions.includes(fac)) { factions.push(fac); } @@ -98,13 +97,13 @@ function possibleFactions(player: IPlayer, sleeve: Sleeve): string[] { }); } -function possibleContracts(player: IPlayer, sleeve: Sleeve): string[] { - const bb = player.bladeburner; +function possibleContracts(sleeve: Sleeve): string[] { + const bb = Player.bladeburner; if (bb === null) { return ["------"]; } let contracts = bb.getContractNamesNetscriptFn(); - for (const otherSleeve of player.sleeves) { + for (const otherSleeve of Player.sleeves) { if (sleeve === otherSleeve) { continue; } @@ -120,28 +119,28 @@ function possibleContracts(player: IPlayer, sleeve: Sleeve): string[] { } const tasks: { - [key: string]: undefined | ((player: IPlayer, sleeve: Sleeve) => ITaskDetails); - ["------"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Work for Company"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Work for Faction"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Commit Crime"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Take University Course"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Workout at Gym"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Perform Bladeburner Actions"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Shock Recovery"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; - ["Synchronize"]: (player: IPlayer, sleeve: Sleeve) => ITaskDetails; + [key: string]: undefined | ((sleeve: Sleeve) => ITaskDetails); + ["------"]: (sleeve: Sleeve) => ITaskDetails; + ["Work for Company"]: (sleeve: Sleeve) => ITaskDetails; + ["Work for Faction"]: (sleeve: Sleeve) => ITaskDetails; + ["Commit Crime"]: (sleeve: Sleeve) => ITaskDetails; + ["Take University Course"]: (sleeve: Sleeve) => ITaskDetails; + ["Workout at Gym"]: (sleeve: Sleeve) => ITaskDetails; + ["Perform Bladeburner Actions"]: (sleeve: Sleeve) => ITaskDetails; + ["Shock Recovery"]: (sleeve: Sleeve) => ITaskDetails; + ["Synchronize"]: (sleeve: Sleeve) => ITaskDetails; } = { "------": (): ITaskDetails => { return { first: ["------"], second: () => ["------"] }; }, - "Work for Company": (player: IPlayer, sleeve: Sleeve): ITaskDetails => { - let jobs = possibleJobs(player, sleeve); + "Work for Company": (sleeve: Sleeve): ITaskDetails => { + let jobs = possibleJobs(sleeve); if (jobs.length === 0) jobs = ["------"]; return { first: jobs, second: () => ["------"] }; }, - "Work for Faction": (player: IPlayer, sleeve: Sleeve): ITaskDetails => { - let factions = possibleFactions(player, sleeve); + "Work for Faction": (sleeve: Sleeve): ITaskDetails => { + let factions = possibleFactions(sleeve); if (factions.length === 0) factions = ["------"]; return { @@ -168,7 +167,7 @@ const tasks: { "Commit Crime": (): ITaskDetails => { return { first: Object.values(Crimes).map((crime) => crime.name), second: () => ["------"] }; }, - "Take University Course": (player: IPlayer, sleeve: Sleeve): ITaskDetails => { + "Take University Course": (sleeve: Sleeve): ITaskDetails => { let universities: string[] = []; switch (sleeve.city) { case CityName.Aevum: @@ -187,7 +186,7 @@ const tasks: { return { first: universitySelectorOptions, second: () => universities }; }, - "Workout at Gym": (player: IPlayer, sleeve: Sleeve): ITaskDetails => { + "Workout at Gym": (sleeve: Sleeve): ITaskDetails => { let gyms: string[] = []; switch (sleeve.city) { case CityName.Aevum: @@ -206,12 +205,12 @@ const tasks: { return { first: gymSelectorOptions, second: () => gyms }; }, - "Perform Bladeburner Actions": (player: IPlayer, sleeve: Sleeve): ITaskDetails => { + "Perform Bladeburner Actions": (sleeve: Sleeve): ITaskDetails => { return { first: bladeburnerSelectorOptions, second: (s1: string) => { if (s1 === "Take on contracts") { - return possibleContracts(player, sleeve); + return possibleContracts(sleeve); } else { return ["------"]; } @@ -227,28 +226,28 @@ const tasks: { }; const canDo: { - [key: string]: undefined | ((player: IPlayer, sleeve: Sleeve) => boolean); - ["------"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Work for Company"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Work for Faction"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Commit Crime"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Take University Course"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Workout at Gym"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Perform Bladeburner Actions"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Shock Recovery"]: (player: IPlayer, sleeve: Sleeve) => boolean; - ["Synchronize"]: (player: IPlayer, sleeve: Sleeve) => boolean; + [key: string]: undefined | ((sleeve: Sleeve) => boolean); + ["------"]: (sleeve: Sleeve) => boolean; + ["Work for Company"]: (sleeve: Sleeve) => boolean; + ["Work for Faction"]: (sleeve: Sleeve) => boolean; + ["Commit Crime"]: (sleeve: Sleeve) => boolean; + ["Take University Course"]: (sleeve: Sleeve) => boolean; + ["Workout at Gym"]: (sleeve: Sleeve) => boolean; + ["Perform Bladeburner Actions"]: (sleeve: Sleeve) => boolean; + ["Shock Recovery"]: (sleeve: Sleeve) => boolean; + ["Synchronize"]: (sleeve: Sleeve) => boolean; } = { "------": () => true, - "Work for Company": (player: IPlayer, sleeve: Sleeve) => possibleJobs(player, sleeve).length > 0, - "Work for Faction": (player: IPlayer, sleeve: Sleeve) => possibleFactions(player, sleeve).length > 0, + "Work for Company": (sleeve: Sleeve) => possibleJobs(sleeve).length > 0, + "Work for Faction": (sleeve: Sleeve) => possibleFactions(sleeve).length > 0, "Commit Crime": () => true, - "Take University Course": (player: IPlayer, sleeve: Sleeve) => + "Take University Course": (sleeve: Sleeve) => [CityName.Aevum, CityName.Sector12, CityName.Volhaven].includes(sleeve.city), - "Workout at Gym": (player: IPlayer, sleeve: Sleeve) => + "Workout at Gym": (sleeve: Sleeve) => [CityName.Aevum, CityName.Sector12, CityName.Volhaven].includes(sleeve.city), - "Perform Bladeburner Actions": (player: IPlayer) => player.inBladeburner(), - "Shock Recovery": (player: IPlayer, sleeve: Sleeve) => sleeve.shock < 100, - Synchronize: (player: IPlayer, sleeve: Sleeve) => sleeve.sync < 100, + "Perform Bladeburner Actions": () => Player.inBladeburner(), + "Shock Recovery": (sleeve: Sleeve) => sleeve.shock < 100, + Synchronize: (sleeve: Sleeve) => sleeve.sync < 100, }; function getABC(sleeve: Sleeve): [string, string, string] { @@ -345,12 +344,12 @@ export function TaskSelector(props: IProps): React.ReactElement { const [s2, setS2] = useState(abc[2]); const validActions = Object.keys(canDo).filter((k) => - (canDo[k] as (player: IPlayer, sleeve: Sleeve) => boolean)(props.player, props.sleeve), + (canDo[k] as (sleeve: Sleeve) => boolean)(props.sleeve), ); const detailsF = tasks[s0]; if (detailsF === undefined) throw new Error(`No function for task '${s0}'`); - const details = detailsF(props.player, props.sleeve); + const details = detailsF(props.sleeve); const details2 = details.second(s1); if (details.first.length > 0 && !details.first.includes(s1)) { @@ -366,7 +365,7 @@ export function TaskSelector(props: IProps): React.ReactElement { const n = event.target.value; const detailsF = tasks[n]; if (detailsF === undefined) throw new Error(`No function for task '${s0}'`); - const details = detailsF(props.player, props.sleeve); + const details = detailsF(props.sleeve); const details2 = details.second(details.first[0]) ?? ["------"]; setS2(details2[0]); setS1(details.first[0]); diff --git a/src/PersonObjects/Sleeve/ui/TravelModal.tsx b/src/PersonObjects/Sleeve/ui/TravelModal.tsx index 83ea6f663..27a715297 100644 --- a/src/PersonObjects/Sleeve/ui/TravelModal.tsx +++ b/src/PersonObjects/Sleeve/ui/TravelModal.tsx @@ -6,7 +6,7 @@ import { WorldMap } from "../../../ui/React/WorldMap"; import { CityName } from "../../../Locations/data/CityNames"; import { Settings } from "../../../Settings/Settings"; import { dialogBoxCreate } from "../../../ui/React/DialogBox"; -import { use } from "../../../ui/Context"; +import { Player } from "../../../Player"; import { Modal } from "../../../ui/React/Modal"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; @@ -19,14 +19,13 @@ interface IProps { } export function TravelModal(props: IProps): React.ReactElement { - const player = use.Player(); function travel(city: string): void { - if (!player.canAfford(CONSTANTS.TravelCost)) { + if (!Player.canAfford(CONSTANTS.TravelCost)) { dialogBoxCreate("You cannot afford to have this sleeve travel to another city"); } props.sleeve.city = city as CityName; - player.loseMoney(CONSTANTS.TravelCost, "sleeve"); - props.sleeve.stopWork(player); + Player.loseMoney(CONSTANTS.TravelCost, "sleeve"); + props.sleeve.stopWork(); props.rerender(); props.onClose(); } @@ -36,7 +35,7 @@ export function TravelModal(props: IProps): React.ReactElement { <> Have this sleeve travel to a different city. This affects the gyms and universities at which this sleeve can - study. Traveling to a different city costs . It will + study. Traveling to a different city costs . It will also set your current sleeve task to idle. {Settings.DisableASCIIArt ? ( diff --git a/src/Prestige.ts b/src/Prestige.ts index b526946fe..1c919d549 100755 --- a/src/Prestige.ts +++ b/src/Prestige.ts @@ -37,7 +37,7 @@ const BitNode8StartingMoney = 250e6; // Prestige by purchasing augmentation export function prestigeAugmentation(): void { - initBitNodeMultipliers(Player); + initBitNodeMultipliers(); const maintainMembership = Player.factions.concat(Player.factionInvitations).filter(function (faction) { return Factions[faction].getInfo().keep; @@ -91,7 +91,7 @@ export function prestigeAugmentation(): void { // Stop a Terminal action if there is one. if (Terminal.action !== null) { - Terminal.finishAction(Router, Player, true); + Terminal.finishAction(true); } Terminal.clear(); LogBoxClearEvents.emit(); @@ -176,7 +176,7 @@ export function prestigeAugmentation(): void { // Prestige by destroying Bit Node and gaining a Source File export function prestigeSourceFile(flume: boolean): void { - initBitNodeMultipliers(Player); + initBitNodeMultipliers(); Player.prestigeSourceFile(); prestigeWorkerScripts(); // Delete all Worker Scripts objects @@ -185,7 +185,7 @@ export function prestigeSourceFile(flume: boolean): void { // Stop a Terminal action if there is one. if (Terminal.action !== null) { - Terminal.finishAction(Router, Player, true); + Terminal.finishAction(true); } Terminal.clear(); LogBoxClearEvents.emit(); @@ -225,7 +225,7 @@ export function prestigeSourceFile(flume: boolean): void { // Stop a Terminal action if there is one if (Terminal.action !== null) { - Terminal.finishAction(Router, Player, true); + Terminal.finishAction(true); } // Delete all Augmentations @@ -302,7 +302,7 @@ export function prestigeSourceFile(flume: boolean): void { hserver.cache = 5; hserver.updateHashRate(Player.mults.hacknet_node_money); hserver.updateHashCapacity(); - updateHashManagerCapacity(Player); + updateHashManagerCapacity(); } if (Player.bitNodeN === 13) { diff --git a/src/Programs/Program.ts b/src/Programs/Program.ts index 1b63e27ec..e05ecff3a 100644 --- a/src/Programs/Program.ts +++ b/src/Programs/Program.ts @@ -1,11 +1,8 @@ import { BaseServer } from "../Server/BaseServer"; -import { ITerminal } from "../Terminal/ITerminal"; -import { IPlayer } from "../PersonObjects/IPlayer"; -import { IRouter } from "../ui/Router"; export interface IProgramCreate { level: number; - req(p: IPlayer): boolean; // Function that indicates whether player meets requirements + req(): boolean; // Function that indicates whether player meets requirements time: number; tooltip: string; } @@ -13,12 +10,12 @@ export interface IProgramCreate { export class Program { name = ""; create: IProgramCreate | null; - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer, args: string[]) => void; + run: (args: string[], server: BaseServer) => void; constructor( name: string, create: IProgramCreate | null, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer, args: string[]) => void, + run: (args: string[], server: BaseServer) => void, ) { this.name = name; this.create = create; diff --git a/src/Programs/ProgramHelpers.ts b/src/Programs/ProgramHelpers.ts index abb8b5049..ce0433c4b 100644 --- a/src/Programs/ProgramHelpers.ts +++ b/src/Programs/ProgramHelpers.ts @@ -1,10 +1,10 @@ import { Programs } from "./Programs"; import { Program } from "./Program"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; //Returns the programs this player can create. -export function getAvailableCreatePrograms(player: IPlayer): Program[] { +export function getAvailableCreatePrograms(): Program[] { const programs: Program[] = []; for (const key of Object.keys(Programs)) { // Non-creatable program @@ -12,10 +12,10 @@ export function getAvailableCreatePrograms(player: IPlayer): Program[] { if (create == null) continue; // Already has program - if (player.hasProgram(Programs[key].name)) continue; + if (Player.hasProgram(Programs[key].name)) continue; // Does not meet requirements - if (!create.req(player)) continue; + if (!create.req()) continue; programs.push(Programs[key]); } diff --git a/src/Programs/data/ProgramsMetadata.ts b/src/Programs/data/ProgramsMetadata.ts index 28c700c5f..a0369c569 100644 --- a/src/Programs/data/ProgramsMetadata.ts +++ b/src/Programs/data/ProgramsMetadata.ts @@ -2,9 +2,8 @@ import { IProgramCreate } from "../Program"; import { CONSTANTS } from "../../Constants"; import { BaseServer } from "../../Server/BaseServer"; import { Server } from "../../Server/Server"; -import { ITerminal } from "../../Terminal/ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFunctions"; import { GetServer } from "../../Server/AllServers"; import { numeralWrapper } from "../../ui/numeralFormat"; @@ -14,14 +13,14 @@ import { calculateHackingTime, calculateGrowTime, calculateWeakenTime } from ".. import { FactionNames } from "../../Faction/data/FactionNames"; function requireHackingLevel(lvl: number) { - return function (p: IPlayer) { - return p.skills.hacking + p.skills.intelligence / 2 >= lvl; + return function () { + return Player.skills.hacking + Player.skills.intelligence / 2 >= lvl; }; } function bitFlumeRequirements() { - return function (p: IPlayer) { - return p.sourceFiles.length > 0 && p.skills.hacking >= 1; + return function () { + return Player.sourceFiles.length > 0 && Player.skills.hacking >= 1; }; } @@ -29,7 +28,7 @@ interface IProgramCreationParams { key: string; name: string; create: IProgramCreate | null; - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer, args: string[]) => void; + run: (args: string[], server: BaseServer) => void; } export const programsMetadata: IProgramCreationParams[] = [ @@ -42,24 +41,24 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(1), time: CONSTANTS.MillisecondsPerFiveMinutes, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot nuke this kind of server."); + Terminal.error("Cannot nuke this kind of server."); return; } if (server.hasAdminRights) { - terminal.print("You already have root access to this computer. There is no reason to run NUKE.exe"); - terminal.print("You can now run scripts on this server."); + Terminal.print("You already have root access to this computer. There is no reason to run NUKE.exe"); + Terminal.print("You can now run scripts on this server."); return; } if (server.openPortCount >= server.numOpenPortsRequired) { server.hasAdminRights = true; - terminal.print("NUKE successful! Gained root access to " + server.hostname); - terminal.print("You can now run scripts on this server."); + Terminal.print("NUKE successful! Gained root access to " + server.hostname); + Terminal.print("You can now run scripts on this server."); return; } - terminal.print("NUKE unsuccessful. Not enough ports have been opened"); + Terminal.print("NUKE unsuccessful. Not enough ports have been opened"); }, }, { @@ -71,18 +70,18 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(50), time: CONSTANTS.MillisecondsPerFiveMinutes * 2, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot run BruteSSH.exe on this kind of server."); + Terminal.error("Cannot run BruteSSH.exe on this kind of server."); return; } if (server.sshPortOpen) { - terminal.print("SSH Port (22) is already open!"); + Terminal.print("SSH Port (22) is already open!"); return; } server.sshPortOpen = true; - terminal.print("Opened SSH Port(22)!"); + Terminal.print("Opened SSH Port(22)!"); server.openPortCount++; }, }, @@ -95,18 +94,18 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(100), time: CONSTANTS.MillisecondsPerHalfHour, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot run FTPCrack.exe on this kind of server."); + Terminal.error("Cannot run FTPCrack.exe on this kind of server."); return; } if (server.ftpPortOpen) { - terminal.print("FTP Port (21) is already open!"); + Terminal.print("FTP Port (21) is already open!"); return; } server.ftpPortOpen = true; - terminal.print("Opened FTP Port (21)!"); + Terminal.print("Opened FTP Port (21)!"); server.openPortCount++; }, }, @@ -119,18 +118,18 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(250), time: CONSTANTS.MillisecondsPer2Hours, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot run relaySMTP.exe on this kind of server."); + Terminal.error("Cannot run relaySMTP.exe on this kind of server."); return; } if (server.smtpPortOpen) { - terminal.print("SMTP Port (25) is already open!"); + Terminal.print("SMTP Port (25) is already open!"); return; } server.smtpPortOpen = true; - terminal.print("Opened SMTP Port (25)!"); + Terminal.print("Opened SMTP Port (25)!"); server.openPortCount++; }, }, @@ -143,18 +142,18 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(500), time: CONSTANTS.MillisecondsPer4Hours, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot run HTTPWorm.exe on this kind of server."); + Terminal.error("Cannot run HTTPWorm.exe on this kind of server."); return; } if (server.httpPortOpen) { - terminal.print("HTTP Port (80) is already open!"); + Terminal.print("HTTP Port (80) is already open!"); return; } server.httpPortOpen = true; - terminal.print("Opened HTTP Port (80)!"); + Terminal.print("Opened HTTP Port (80)!"); server.openPortCount++; }, }, @@ -167,18 +166,18 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(750), time: CONSTANTS.MillisecondsPer8Hours, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer): void => { + run: (_args:string[], server: BaseServer): void => { if (!(server instanceof Server)) { - terminal.error("Cannot run SQLInject.exe on this kind of server."); + Terminal.error("Cannot run SQLInject.exe on this kind of server."); return; } if (server.sqlPortOpen) { - terminal.print("SQL Port (1433) is already open!"); + Terminal.print("SQL Port (1433) is already open!"); return; } server.sqlPortOpen = true; - terminal.print("Opened SQL Port (1433)!"); + Terminal.print("Opened SQL Port (1433)!"); server.openPortCount++; }, }, @@ -191,9 +190,9 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(75), time: CONSTANTS.MillisecondsPerQuarterHour, }, - run: (router: IRouter, terminal: ITerminal): void => { - terminal.print("This executable cannot be run."); - terminal.print("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5."); + run: (): void => { + Terminal.print("This executable cannot be run."); + Terminal.print("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5."); }, }, { @@ -205,9 +204,9 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(400), time: CONSTANTS.MillisecondsPer2Hours, }, - run: (router: IRouter, terminal: ITerminal): void => { - terminal.print("This executable cannot be run."); - terminal.print("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10."); + run: (): void => { + Terminal.print("This executable cannot be run."); + Terminal.print("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10."); }, }, { @@ -219,42 +218,42 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(75), time: CONSTANTS.MillisecondsPerHalfHour, }, - run: (router: IRouter, terminal: ITerminal, player: IPlayer, server: BaseServer, args: string[]): void => { + run: (args: string[]): void => { if (args.length !== 1) { - terminal.error("Must pass a server hostname or IP as an argument for ServerProfiler.exe"); + Terminal.error("Must pass a server hostname or IP as an argument for ServerProfiler.exe"); return; } const targetServer = GetServer(args[0]); if (targetServer == null) { - terminal.error("Invalid server IP/hostname"); + Terminal.error("Invalid server IP/hostname"); return; } if (!(targetServer instanceof Server)) { - terminal.error(`ServerProfiler.exe can only be run on normal servers.`); + Terminal.error(`ServerProfiler.exe can only be run on normal servers.`); return; } - terminal.print(targetServer.hostname + ":"); - terminal.print("Server base security level: " + targetServer.baseDifficulty); - terminal.print("Server current security level: " + targetServer.hackDifficulty); - terminal.print("Server growth rate: " + targetServer.serverGrowth); - terminal.print( + Terminal.print(targetServer.hostname + ":"); + Terminal.print("Server base security level: " + targetServer.baseDifficulty); + Terminal.print("Server current security level: " + targetServer.hackDifficulty); + Terminal.print("Server growth rate: " + targetServer.serverGrowth); + Terminal.print( `Netscript hack() execution time: ${convertTimeMsToTimeElapsedString( - calculateHackingTime(targetServer, player) * 1000, + calculateHackingTime(targetServer, Player) * 1000, true, )}`, ); - terminal.print( + Terminal.print( `Netscript grow() execution time: ${convertTimeMsToTimeElapsedString( - calculateGrowTime(targetServer, player) * 1000, + calculateGrowTime(targetServer, Player) * 1000, true, )}`, ); - terminal.print( + Terminal.print( `Netscript weaken() execution time: ${convertTimeMsToTimeElapsedString( - calculateWeakenTime(targetServer, player) * 1000, + calculateWeakenTime(targetServer, Player) * 1000, true, )}`, ); @@ -269,10 +268,10 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(25), time: CONSTANTS.MillisecondsPerQuarterHour, }, - run: (router: IRouter, terminal: ITerminal): void => { - terminal.print("This executable cannot be run."); - terminal.print("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'."); - terminal.print("When using scan-analyze, click on a server's hostname to connect to it."); + run: (): void => { + Terminal.print("This executable cannot be run."); + Terminal.print("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'."); + Terminal.print("When using scan-analyze, click on a server's hostname to connect to it."); }, }, { @@ -284,9 +283,9 @@ export const programsMetadata: IProgramCreationParams[] = [ req: requireHackingLevel(1000), time: CONSTANTS.MillisecondsPer4Hours, }, - run: (router: IRouter, terminal: ITerminal): void => { - terminal.print("This executable cannot be run."); - terminal.print("Formulas.exe lets you use the formulas API."); + run: (): void => { + Terminal.print("This executable cannot be run."); + Terminal.print("Formulas.exe lets you use the formulas API."); }, }, { @@ -306,19 +305,19 @@ export const programsMetadata: IProgramCreationParams[] = [ key: "Flight", name: "fl1ght.exe", create: null, - run: (router: IRouter, terminal: ITerminal, player: IPlayer): void => { + run: (): void => { const numAugReq = BitNodeMultipliers.DaedalusAugsRequirement; const fulfilled = - player.augmentations.length >= numAugReq && player.money > 1e11 && player.skills.hacking >= 2500; + Player.augmentations.length >= numAugReq && Player.money > 1e11 && Player.skills.hacking >= 2500; if (!fulfilled) { - terminal.print(`Augmentations: ${player.augmentations.length} / ${numAugReq}`); - terminal.print(`Money: ${numeralWrapper.formatMoney(player.money)} / $100b`); - terminal.print(`Hacking skill: ${player.skills.hacking} / 2500`); + Terminal.print(`Augmentations: ${Player.augmentations.length} / ${numAugReq}`); + Terminal.print(`Money: ${numeralWrapper.formatMoney(Player.money)} / $100b`); + Terminal.print(`Hacking skill: ${Player.skills.hacking} / 2500`); return; } - terminal.print("We will contact you."); - terminal.print(`-- ${FactionNames.Daedalus} --`); + Terminal.print("We will contact you."); + Terminal.print(`-- ${FactionNames.Daedalus} --`); }, }, ]; diff --git a/src/Programs/ui/ProgramsRoot.tsx b/src/Programs/ui/ProgramsRoot.tsx index a8638ab4a..767d6dda5 100644 --- a/src/Programs/ui/ProgramsRoot.tsx +++ b/src/Programs/ui/ProgramsRoot.tsx @@ -4,7 +4,8 @@ import { find } from "lodash"; import { Box, Typography, Button, Container, Paper } from "@mui/material"; import { Check, Lock, Create } from "@mui/icons-material"; -import { use } from "../../ui/Context"; +import { Router } from "../../ui/GameRoot"; +import { Player } from "../../Player"; import { Settings } from "../../Settings/Settings"; import { Programs } from "../Programs"; @@ -13,8 +14,6 @@ import { CreateProgramWork } from "../../Work/CreateProgramWork"; export const ProgramsSeen: string[] = []; export function ProgramsRoot(): React.ReactElement { - const player = use.Player(); - const router = use.Router(); const setRerender = useState(false)[1]; function rerender(): void { setRerender((old) => !old); @@ -25,13 +24,13 @@ export function ProgramsRoot(): React.ReactElement { const create = prog.create; if (create === null) return false; if (prog.name === "b1t_flum3.exe") { - return create.req(player); + return create.req(); } return true; }) .sort((a, b) => { - if (player.hasProgram(a.name)) return 1; - if (player.hasProgram(b.name)) return -1; + if (Player.hasProgram(a.name)) return 1; + if (Player.hasProgram(b.name)) return -1; return (a.create?.level ?? 0) - (b.create?.level ?? 0); }); @@ -48,11 +47,11 @@ export function ProgramsRoot(): React.ReactElement { }, []); const getHackingLevelRemaining = (lvl: number): number => { - return Math.ceil(Math.max(lvl - (player.skills.hacking + player.skills.intelligence / 2), 0)); + return Math.ceil(Math.max(lvl - (Player.skills.hacking + Player.skills.intelligence / 2), 0)); }; const getProgCompletion = (name: string): number => { - const programFile = find(player.getHomeComputer().programs, (p) => { + const programFile = find(Player.getHomeComputer().programs, (p) => { return p.startsWith(name) && p.endsWith("%-INC"); }); if (!programFile) return -1; @@ -84,31 +83,31 @@ export function ProgramsRoot(): React.ReactElement { return ( <> - {(player.hasProgram(program.name) && ) || - (create.req(player) && ) || } + {(Player.hasProgram(program.name) && ) || + (create.req() && ) || } {program.name} - {!player.hasProgram(program.name) && create.req(player) && ( + {!Player.hasProgram(program.name) && create.req() && ( )} - {player.hasProgram(program.name) || getHackingLevelRemaining(create.level) === 0 || ( + {Player.hasProgram(program.name) || getHackingLevelRemaining(create.level) === 0 || ( Unlocks in: {getHackingLevelRemaining(create.level)} hacking levels diff --git a/src/ScriptEditor/ui/ScriptEditorRoot.tsx b/src/ScriptEditor/ui/ScriptEditorRoot.tsx index f6f46f21e..fc9367b63 100644 --- a/src/ScriptEditor/ui/ScriptEditorRoot.tsx +++ b/src/ScriptEditor/ui/ScriptEditorRoot.tsx @@ -7,8 +7,8 @@ type ITextModel = monaco.editor.ITextModel; import { OptionsModal } from "./OptionsModal"; import { Options } from "./Options"; import { isValidFilePath } from "../../Terminal/DirectoryHelpers"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { IRouter } from "../../ui/Router"; +import { Player } from "../../Player"; +import { Router } from "../../ui/GameRoot"; import { dialogBoxCreate } from "../../ui/React/DialogBox"; import { isScriptFilename } from "../../Script/isScriptFilename"; import { Script } from "../../Script/Script"; @@ -49,8 +49,6 @@ interface IProps { // Map of filename -> code files: Record; hostname: string; - player: IPlayer; - router: IRouter; vim: boolean; } @@ -156,7 +154,7 @@ export function Root(props: IProps): React.ReactElement { //Ctrl + b if (event.code == "KeyB" && (event.ctrlKey || event.metaKey)) { event.preventDefault(); - props.router.toTerminal(); + Router.toTerminal(); } // CTRL/CMD + S @@ -183,12 +181,12 @@ export function Root(props: IProps): React.ReactElement { save(); }); MonacoVim.VimMode.Vim.defineEx("quit", "q", function () { - props.router.toTerminal(); + Router.toTerminal(); }); const saveNQuit = (): void => { save(); - props.router.toTerminal(); + Router.toTerminal(); }; // "wqriteandquit" & "xriteandquit" are not typos, prefix must be found in full string MonacoVim.VimMode.Vim.defineEx("wqriteandquit", "wq", saveNQuit); @@ -252,7 +250,7 @@ export function Root(props: IProps): React.ReactElement { return; } const codeCopy = newCode + ""; - const ramUsage = calculateRamUsage(codeCopy, props.player.getCurrentServer().scripts); + const ramUsage = calculateRamUsage(codeCopy, Player.getCurrentServer().scripts); if (ramUsage.cost > 0) { const entries = ramUsage.entries?.sort((a, b) => b.cost - a.cost) ?? []; const entriesDisp = []; @@ -468,25 +466,25 @@ export function Root(props: IProps): React.ReactElement { server.scripts[i].saveScript( scriptToSave.fileName, scriptToSave.code, - props.player.currentServer, + Player.currentServer, server.scripts, ); if (Settings.SaveGameOnFileSave) saveObject.saveGame(); - props.router.toTerminal(); + Router.toTerminal(); return; } } //If the current script does NOT exist, create a new one const script = new Script(); - script.saveScript(scriptToSave.fileName, scriptToSave.code, props.player.currentServer, server.scripts); + script.saveScript(scriptToSave.fileName, scriptToSave.code, Player.currentServer, server.scripts); server.scripts.push(script); } else if (scriptToSave.isTxt) { for (let i = 0; i < server.textFiles.length; ++i) { if (server.textFiles[i].fn === scriptToSave.fileName) { server.textFiles[i].write(scriptToSave.code); if (Settings.SaveGameOnFileSave) saveObject.saveGame(); - props.router.toTerminal(); + Router.toTerminal(); return; } } @@ -498,7 +496,7 @@ export function Root(props: IProps): React.ReactElement { } if (Settings.SaveGameOnFileSave) saveObject.saveGame(); - props.router.toTerminal(); + Router.toTerminal(); } function save(): void { @@ -550,7 +548,7 @@ export function Root(props: IProps): React.ReactElement { server.scripts[i].saveScript( currentScript.fileName, currentScript.code, - props.player.currentServer, + Player.currentServer, server.scripts, ); if (Settings.SaveGameOnFileSave) saveObject.saveGame(); @@ -561,7 +559,7 @@ export function Root(props: IProps): React.ReactElement { //If the current script does NOT exist, create a new one const script = new Script(); - script.saveScript(currentScript.fileName, currentScript.code, props.player.currentServer, server.scripts); + script.saveScript(currentScript.fileName, currentScript.code, Player.currentServer, server.scripts); server.scripts.push(script); } else if (currentScript.isTxt) { for (let i = 0; i < server.textFiles.length; ++i) { @@ -653,7 +651,7 @@ export function Root(props: IProps): React.ReactElement { openScripts.splice(index, 1); if (openScripts.length === 0) { currentScript = null; - props.router.toTerminal(); + Router.toTerminal(); return; } @@ -905,7 +903,7 @@ export function Root(props: IProps): React.ReactElement { {ram} - diff --git a/src/Server/ServerPurchases.ts b/src/Server/ServerPurchases.ts index 3cf62635d..3811b4f58 100644 --- a/src/Server/ServerPurchases.ts +++ b/src/Server/ServerPurchases.ts @@ -7,7 +7,7 @@ import { safetlyCreateUniqueServer } from "./ServerHelpers"; import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { CONSTANTS } from "../Constants"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { dialogBoxCreate } from "../ui/React/DialogBox"; import { isPowerOfTwo } from "../utils/helpers/isPowerOfTwo"; @@ -50,15 +50,15 @@ export function getPurchaseServerMaxRam(): number { } // Manually purchase a server (NOT through Netscript) -export function purchaseServer(hostname: string, ram: number, cost: number, p: IPlayer): void { +export function purchaseServer(hostname: string, ram: number, cost: number): void { //Check if player has enough money - if (!p.canAfford(cost)) { + if (!Player.canAfford(cost)) { dialogBoxCreate("You don't have enough money to purchase this server!"); return; } //Maximum server limit - if (p.purchasedServers.length >= getPurchaseServerLimit()) { + if (Player.purchasedServers.length >= getPurchaseServerLimit()) { dialogBoxCreate( "You have reached the maximum limit of " + getPurchaseServerLimit() + @@ -87,32 +87,32 @@ export function purchaseServer(hostname: string, ram: number, cost: number, p: I AddToAllServers(newServ); // Add to Player's purchasedServers array - p.purchasedServers.push(newServ.hostname); + Player.purchasedServers.push(newServ.hostname); // Connect new server to home computer - const homeComputer = p.getHomeComputer(); + const homeComputer = Player.getHomeComputer(); homeComputer.serversOnNetwork.push(newServ.hostname); newServ.serversOnNetwork.push(homeComputer.hostname); - p.loseMoney(cost, "servers"); + Player.loseMoney(cost, "servers"); dialogBoxCreate("Server successfully purchased with hostname " + newServ.hostname); } // Manually upgrade RAM on home computer (NOT through Netscript) -export function purchaseRamForHomeComputer(p: IPlayer): void { - const cost = p.getUpgradeHomeRamCost(); - if (!p.canAfford(cost)) { +export function purchaseRamForHomeComputer(): void { + const cost = Player.getUpgradeHomeRamCost(); + if (!Player.canAfford(cost)) { dialogBoxCreate("You do not have enough money to purchase additional RAM for your home computer"); return; } - const homeComputer = p.getHomeComputer(); + const homeComputer = Player.getHomeComputer(); if (homeComputer.maxRam >= CONSTANTS.HomeComputerMaxRam) { dialogBoxCreate(`You cannot upgrade your home computer RAM because it is at its maximum possible value`); return; } homeComputer.maxRam *= 2; - p.loseMoney(cost, "servers"); + Player.loseMoney(cost, "servers"); } diff --git a/src/Sidebar/ui/SidebarRoot.tsx b/src/Sidebar/ui/SidebarRoot.tsx index 4453d2347..ebef6ceb5 100644 --- a/src/Sidebar/ui/SidebarRoot.tsx +++ b/src/Sidebar/ui/SidebarRoot.tsx @@ -45,8 +45,9 @@ import LiveHelpIcon from "@mui/icons-material/LiveHelp"; import ExpandLessIcon from "@mui/icons-material/ExpandLess"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; -import { IRouter, Page } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Router } from "../../ui/GameRoot"; +import { Page } from "../../ui/Router"; +import { Player } from "../../Player"; import { CONSTANTS } from "../../Constants"; import { iTutorialSteps, iTutorialNextStep, ITutorial } from "../../InteractiveTutorial"; import { getAvailableCreatePrograms } from "../../Programs/ProgramHelpers"; @@ -103,8 +104,6 @@ const useStyles = makeStyles((theme: Theme) => ); interface IProps { - player: IPlayer; - router: IRouter; page: Page; opened: boolean; onToggled: (newValue: boolean) => void; @@ -140,122 +139,122 @@ export function SidebarRoot(props: IProps): React.ReactElement { const flashTutorial = ITutorial.currStep === iTutorialSteps.WorldDescription; - const augmentationCount = props.player.queuedAugmentations.length; - const invitationsCount = props.player.factionInvitations.filter((f) => !InvitationsSeen.includes(f)).length; - const programCount = getAvailableCreatePrograms(props.player).length - ProgramsSeen.length; + const augmentationCount = Player.queuedAugmentations.length; + const invitationsCount = Player.factionInvitations.filter((f) => !InvitationsSeen.includes(f)).length; + const programCount = getAvailableCreatePrograms().length - ProgramsSeen.length; const canOpenFactions = - props.player.factionInvitations.length > 0 || - props.player.factions.length > 0 || - props.player.augmentations.length > 0 || - props.player.queuedAugmentations.length > 0 || - props.player.sourceFiles.length > 0; + Player.factionInvitations.length > 0 || + Player.factions.length > 0 || + Player.augmentations.length > 0 || + Player.queuedAugmentations.length > 0 || + Player.sourceFiles.length > 0; const canOpenAugmentations = - props.player.augmentations.length > 0 || - props.player.queuedAugmentations.length > 0 || - props.player.sourceFiles.length > 0; + Player.augmentations.length > 0 || + Player.queuedAugmentations.length > 0 || + Player.sourceFiles.length > 0; - const canOpenSleeves = props.player.sleeves.length > 0; + const canOpenSleeves = Player.sleeves.length > 0; - const canCorporation = !!props.player.corporation; - const canGang = !!props.player.gang; - const canJob = Object.values(props.player.jobs).length > 0; - const canStockMarket = props.player.hasWseAccount; - const canBladeburner = !!props.player.bladeburner; - const canStaneksGift = props.player.augmentations.some((aug) => aug.name === AugmentationNames.StaneksGift1); + const canCorporation = !!Player.corporation; + const canGang = !!Player.gang; + const canJob = Object.values(Player.jobs).length > 0; + const canStockMarket = Player.hasWseAccount; + const canBladeburner = !!Player.bladeburner; + const canStaneksGift = Player.augmentations.some((aug) => aug.name === AugmentationNames.StaneksGift1); function clickTerminal(): void { - props.router.toTerminal(); + Router.toTerminal(); if (flashTerminal) iTutorialNextStep(); } function clickScriptEditor(): void { - props.router.toScriptEditor(); + Router.toScriptEditor(); } function clickStats(): void { - props.router.toStats(); + Router.toStats(); if (flashStats) iTutorialNextStep(); } function clickActiveScripts(): void { - props.router.toActiveScripts(); + Router.toActiveScripts(); if (flashActiveScripts) iTutorialNextStep(); } function clickCreateProgram(): void { - props.router.toCreateProgram(); + Router.toCreateProgram(); } function clickStaneksGift(): void { - props.router.toStaneksGift(); + Router.toStaneksGift(); } function clickFactions(): void { - props.router.toFactions(); + Router.toFactions(); } function clickAugmentations(): void { - props.router.toAugmentations(); + Router.toAugmentations(); } function clickSleeves(): void { - props.router.toSleeves(); + Router.toSleeves(); } function clickHacknet(): void { - props.router.toHacknetNodes(); + Router.toHacknetNodes(); if (flashHacknet) iTutorialNextStep(); } function clickCity(): void { - props.router.toCity(); + Router.toCity(); if (flashCity) iTutorialNextStep(); } function clickTravel(): void { - props.router.toTravel(); + Router.toTravel(); } function clickJob(): void { - props.router.toJob(Locations[Object.keys(props.player.jobs)[0]]); + Router.toJob(Locations[Object.keys(Player.jobs)[0]]); } function clickStockMarket(): void { - props.router.toStockMarket(); + Router.toStockMarket(); } function clickBladeburner(): void { - props.router.toBladeburner(); + Router.toBladeburner(); } function clickCorp(): void { - props.router.toCorporation(); + Router.toCorporation(); } function clickGang(): void { - props.router.toGang(); + Router.toGang(); } function clickTutorial(): void { - props.router.toTutorial(); + Router.toTutorial(); if (flashTutorial) iTutorialNextStep(); } function clickMilestones(): void { - props.router.toMilestones(); + Router.toMilestones(); } function clickOptions(): void { - props.router.toGameOptions(); + Router.toGameOptions(); } function clickDev(): void { - props.router.toDevMenu(); + Router.toDevMenu(); } function clickAchievements(): void { - props.router.toAchievements(); + Router.toAchievements(); } useEffect(() => { @@ -277,7 +276,7 @@ export function SidebarRoot(props: IProps): React.ReactElement { // Alt-g - Gang function handleShortcuts(this: Document, event: KeyboardEvent): void { if (Settings.DisableHotkeys) return; - if ((props.player.currentWork && props.player.focus) || props.router.page() === Page.BitVerse) return; + if ((Player.currentWork && Player.focus) || Router.page() === Page.BitVerse) return; if (event.code === KEYCODE.T && event.altKey) { event.preventDefault(); clickTerminal(); @@ -321,10 +320,10 @@ export function SidebarRoot(props: IProps): React.ReactElement { } else if (event.code === KEYCODE.O && event.altKey) { event.preventDefault(); clickOptions(); - } else if (event.code === KEYCODE.B && event.altKey && props.player.bladeburner) { + } else if (event.code === KEYCODE.B && event.altKey && Player.bladeburner) { event.preventDefault(); clickBladeburner(); - } else if (event.code === KEYCODE.G && event.altKey && props.player.gang) { + } else if (event.code === KEYCODE.G && event.altKey && Player.gang) { event.preventDefault(); clickGang(); } diff --git a/src/StockMarket/ui/InfoAndPurchases.tsx b/src/StockMarket/ui/InfoAndPurchases.tsx index afa3f7293..70749ead5 100644 --- a/src/StockMarket/ui/InfoAndPurchases.tsx +++ b/src/StockMarket/ui/InfoAndPurchases.tsx @@ -8,7 +8,7 @@ import React, { useState } from "react"; import { getStockMarket4SDataCost, getStockMarket4STixApiCost } from "../StockMarketCosts"; import { CONSTANTS } from "../../Constants"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Money } from "../../ui/React/Money"; import { initStockMarket } from "../StockMarket"; @@ -23,24 +23,23 @@ import { StaticModal } from "../../ui/React/StaticModal"; import { FactionNames } from "../../Faction/data/FactionNames"; type IProps = { - p: IPlayer; rerender: () => void; }; function Purchase4SMarketDataTixApiAccessButton(props: IProps): React.ReactElement { function purchase4SMarketDataTixApiAccess(): void { - if (props.p.has4SDataTixApi) { + if (Player.has4SDataTixApi) { return; } - if (!props.p.canAfford(getStockMarket4STixApiCost())) { + if (!Player.canAfford(getStockMarket4STixApiCost())) { return; } - props.p.has4SDataTixApi = true; - props.p.loseMoney(getStockMarket4STixApiCost(), "stock"); + Player.has4SDataTixApi = true; + Player.loseMoney(getStockMarket4STixApiCost(), "stock"); props.rerender(); } - if (props.p.has4SDataTixApi) { + if (Player.has4SDataTixApi) { return ( Market Data TIX API Access @@ -51,7 +50,7 @@ function Purchase4SMarketDataTixApiAccessButton(props: IProps): React.ReactEleme return ( Requires TIX API Access ) : ( Let you access 4S Market Data through Netscript @@ -60,11 +59,11 @@ function Purchase4SMarketDataTixApiAccessButton(props: IProps): React.ReactEleme > @@ -73,7 +72,7 @@ function Purchase4SMarketDataTixApiAccessButton(props: IProps): React.ReactEleme } function PurchaseWseAccountButton(props: IProps): React.ReactElement { - if (props.p.hasWseAccount) { + if (Player.hasWseAccount) { return ( WSE Account @@ -81,15 +80,15 @@ function PurchaseWseAccountButton(props: IProps): React.ReactElement { ); } function purchaseWseAccount(): void { - if (props.p.hasWseAccount) { + if (Player.hasWseAccount) { return; } - if (!props.p.canAfford(CONSTANTS.WSEAccountCost)) { + if (!Player.canAfford(CONSTANTS.WSEAccountCost)) { return; } - props.p.hasWseAccount = true; + Player.hasWseAccount = true; initStockMarket(); - props.p.loseMoney(CONSTANTS.WSEAccountCost, "stock"); + Player.loseMoney(CONSTANTS.WSEAccountCost, "stock"); props.rerender(); } @@ -97,9 +96,9 @@ function PurchaseWseAccountButton(props: IProps): React.ReactElement { return ( <> To begin trading, you must first purchase an account: - ); @@ -107,18 +106,18 @@ function PurchaseWseAccountButton(props: IProps): React.ReactElement { function PurchaseTixApiAccessButton(props: IProps): React.ReactElement { function purchaseTixApiAccess(): void { - if (props.p.hasTixApiAccess) { + if (Player.hasTixApiAccess) { return; } - if (!props.p.canAfford(CONSTANTS.TIXAPICost)) { + if (!Player.canAfford(CONSTANTS.TIXAPICost)) { return; } - props.p.hasTixApiAccess = true; - props.p.loseMoney(CONSTANTS.TIXAPICost, "stock"); + Player.hasTixApiAccess = true; + Player.loseMoney(CONSTANTS.TIXAPICost, "stock"); props.rerender(); } - if (props.p.hasTixApiAccess) { + if (Player.hasTixApiAccess) { return ( TIX API Access @@ -127,9 +126,9 @@ function PurchaseTixApiAccessButton(props: IProps): React.ReactElement { } else { const cost = CONSTANTS.TIXAPICost; return ( - ); } @@ -137,17 +136,17 @@ function PurchaseTixApiAccessButton(props: IProps): React.ReactElement { function Purchase4SMarketDataButton(props: IProps): React.ReactElement { function purchase4SMarketData(): void { - if (props.p.has4SData) { + if (Player.has4SData) { return; } - if (!props.p.canAfford(getStockMarket4SDataCost())) { + if (!Player.canAfford(getStockMarket4SDataCost())) { return; } - props.p.has4SData = true; - props.p.loseMoney(getStockMarket4SDataCost(), "stock"); + Player.has4SData = true; + Player.loseMoney(getStockMarket4SDataCost(), "stock"); props.rerender(); } - if (props.p.has4SData) { + if (Player.has4SData) { return ( 4S Market Data Access @@ -160,9 +159,9 @@ function Purchase4SMarketDataButton(props: IProps): React.ReactElement { title={Lets you view additional pricing and volatility information about stocks} > - @@ -204,7 +203,7 @@ export function InfoAndPurchases(props: IProps): React.ReactElement { Commission Fees: Every transaction you make has a{" "} - commission fee. + commission fee.
    diff --git a/src/StockMarket/ui/StockMarketRoot.tsx b/src/StockMarket/ui/StockMarketRoot.tsx index 4f3bf7e89..a77e213ac 100644 --- a/src/StockMarket/ui/StockMarketRoot.tsx +++ b/src/StockMarket/ui/StockMarketRoot.tsx @@ -8,10 +8,9 @@ import { StockTickers } from "./StockTickers"; import { IStockMarket } from "../IStockMarket"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; type IProps = { - p: IPlayer; stockMarket: IStockMarket; }; @@ -27,8 +26,8 @@ export function StockMarketRoot(props: IProps): React.ReactElement { }, []); return ( <> - - {props.p.hasWseAccount && } + + {Player.hasWseAccount && } ); } diff --git a/src/StockMarket/ui/StockTicker.tsx b/src/StockMarket/ui/StockTicker.tsx index faf3c9abb..8f3abc596 100644 --- a/src/StockMarket/ui/StockTicker.tsx +++ b/src/StockMarket/ui/StockTicker.tsx @@ -17,7 +17,7 @@ import { PositionTypes } from "../data/PositionTypes"; import { placeOrder } from "../StockMarket"; import { buyStock, shortStock, sellStock, sellShort } from "../BuyingAndSelling"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { numeralWrapper } from "../../ui/numeralFormat"; import { Money } from "../../ui/React/Money"; @@ -42,7 +42,6 @@ enum SelectorOrderType { type IProps = { orders: Order[]; - p: IPlayer; rerenderAllTickers: () => void; stock: Stock; }; @@ -157,7 +156,7 @@ export function StockTicker(props: IProps): React.ReactElement { } function handleBuyMaxButtonClick(): void { - const playerMoney: number = props.p.money; + const playerMoney: number = Player.money; const stock = props.stock; let maxShares = calculateBuyMaxAmount(stock, position, playerMoney); @@ -274,18 +273,18 @@ export function StockTicker(props: IProps): React.ReactElement { // Whether the player has access to orders besides market orders (limit/stop) function hasOrderAccess(): boolean { - return props.p.bitNodeN === 8 || props.p.sourceFileLvl(8) >= 3; + return Player.bitNodeN === 8 || Player.sourceFileLvl(8) >= 3; } // Whether the player has access to shorting stocks function hasShortAccess(): boolean { - return props.p.bitNodeN === 8 || props.p.sourceFileLvl(8) >= 2; + return Player.bitNodeN === 8 || Player.sourceFileLvl(8) >= 2; } return ( setTicketOpen((old) => !old)}> - } /> + } /> {tickerOpen ? : } @@ -311,8 +310,8 @@ export function StockTicker(props: IProps): React.ReactElement { - - + + = 2) { + if (Player.bitNodeN === 8 || Player.sourceFileLvl(8) >= 2) { return ( <> diff --git a/src/StockMarket/ui/StockTickers.tsx b/src/StockMarket/ui/StockTickers.tsx index 12cf52165..a2a89eba7 100644 --- a/src/StockMarket/ui/StockTickers.tsx +++ b/src/StockMarket/ui/StockTickers.tsx @@ -11,10 +11,7 @@ import { StockTickersConfig, TickerDisplayMode } from "./StockTickersConfig"; import { IStockMarket } from "../IStockMarket"; import { Stock } from "../Stock"; -import { IPlayer } from "../../PersonObjects/IPlayer"; - type IProps = { - p: IPlayer; stockMarket: IStockMarket; }; @@ -67,9 +64,7 @@ export function StockTickers(props: IProps): React.ReactElement { } } - tickers.push( - , - ); + tickers.push(); } } diff --git a/src/Terminal/ITerminal.tsx b/src/Terminal/ITerminal.tsx index 6c7518096..c76e9e5b2 100644 --- a/src/Terminal/ITerminal.tsx +++ b/src/Terminal/ITerminal.tsx @@ -1,8 +1,6 @@ import React from "react"; import { TextFile } from "../TextFile"; import { Script } from "../Script/Script"; -import { IPlayer } from "../PersonObjects/IPlayer"; -import { IRouter } from "../ui/Router"; import { Settings } from "../Settings/Settings"; import { formatTime } from "../utils/helpers/formatTime"; import { BaseServer } from "../Server/BaseServer"; @@ -77,31 +75,31 @@ export interface ITerminal { warn(s: string): void; clear(): void; - startAnalyze(player: IPlayer): void; - startBackdoor(player: IPlayer): void; - startHack(player: IPlayer): void; - startGrow(player: IPlayer): void; - startWeaken(player: IPlayer): void; - finishHack(router: IRouter, player: IPlayer, server: BaseServer, cancelled?: boolean): void; - finishGrow(player: IPlayer, server: BaseServer, cancelled?: boolean): void; - finishWeaken(player: IPlayer, server: BaseServer, cancelled?: boolean): void; - finishBackdoor(router: IRouter, player: IPlayer, server: BaseServer, cancelled?: boolean): void; - finishAnalyze(player: IPlayer, server: BaseServer, cancelled?: boolean): void; - finishAction(router: IRouter, player: IPlayer, cancelled?: boolean): void; + startAnalyze(): void; + startBackdoor(): void; + startHack(): void; + startGrow(): void; + startWeaken(): void; + finishHack(server: BaseServer, cancelled?: boolean): void; + finishGrow(server: BaseServer, cancelled?: boolean): void; + finishWeaken(server: BaseServer, cancelled?: boolean): void; + finishBackdoor(server: BaseServer, cancelled?: boolean): void; + finishAnalyze(server: BaseServer, cancelled?: boolean): void; + finishAction(cancelled?: boolean): void; getFilepath(filename: string): string; - getFile(player: IPlayer, filename: string): Script | TextFile | string | null; - getScript(player: IPlayer, filename: string): Script | null; - getTextFile(player: IPlayer, filename: string): TextFile | null; - getLitFile(player: IPlayer, filename: string): string | null; + getFile(filename: string): Script | TextFile | string | null; + getScript(filename: string): Script | null; + getTextFile(filename: string): TextFile | null; + getLitFile(filename: string): string | null; cwd(): string; setcwd(dir: string): void; - runContract(player: IPlayer, name: string): void; - executeScanAnalyzeCommand(player: IPlayer, depth?: number, all?: boolean): void; - connectToServer(player: IPlayer, server: string): void; - executeCommand(router: IRouter, player: IPlayer, command: string): void; - executeCommands(router: IRouter, player: IPlayer, commands: string): void; + runContract(name: string): void; + executeScanAnalyzeCommand(depth?: number, all?: boolean): void; + connectToServer(server: string): void; + executeCommand(command: string): void; + executeCommands(commands: string): void; // If there was any changes, will return true, once. - process(router: IRouter, player: IPlayer, cycles: number): void; + process(cycles: number): void; prestige(): void; getProgressText(): string; } diff --git a/src/Terminal/Terminal.ts b/src/Terminal/Terminal.ts index cd2fb2d3f..e183eb19e 100644 --- a/src/Terminal/Terminal.ts +++ b/src/Terminal/Terminal.ts @@ -1,6 +1,6 @@ import { ITerminal, Output, Link, RawOutput, TTimer } from "./ITerminal"; -import { IRouter } from "../ui/Router"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Router } from "../ui/GameRoot"; +import { Player } from "../Player"; import { HacknetServer } from "../Hacknet/HacknetServer"; import { BaseServer } from "../Server/BaseServer"; import { Server } from "../Server/Server"; @@ -93,10 +93,10 @@ export class Terminal implements ITerminal { // Excludes the trailing forward slash currDir = "/"; - process(router: IRouter, player: IPlayer, cycles: number): void { + process(cycles: number): void { if (this.action === null) return; this.action.timeLeft -= (CONSTANTS._idleSpeed * cycles) / 1000; - if (this.action.timeLeft < 0.01) this.finishAction(router, player, false); + if (this.action.timeLeft < 0.01) this.finishAction(false); TerminalEvents.emit(); } @@ -132,50 +132,50 @@ export class Terminal implements ITerminal { this.append(new Output(s, "warn")); } - startHack(player: IPlayer): void { + startHack(): void { // Hacking through Terminal should be faster than hacking through a script - const server = player.getCurrentServer(); + const server = Player.getCurrentServer(); if (server instanceof HacknetServer) { this.error("Cannot hack this kind of server"); return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - this.startAction(calculateHackingTime(server, player) / 4, "h", server); + this.startAction(calculateHackingTime(server, Player) / 4, "h", server); } - startGrow(player: IPlayer): void { - const server = player.getCurrentServer(); + startGrow(): void { + const server = Player.getCurrentServer(); if (server instanceof HacknetServer) { this.error("Cannot grow this kind of server"); return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - this.startAction(calculateGrowTime(server, player) / 16, "g", server); + this.startAction(calculateGrowTime(server, Player) / 16, "g", server); } - startWeaken(player: IPlayer): void { - const server = player.getCurrentServer(); + startWeaken(): void { + const server = Player.getCurrentServer(); if (server instanceof HacknetServer) { this.error("Cannot weaken this kind of server"); return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - this.startAction(calculateWeakenTime(server, player) / 16, "w", server); + this.startAction(calculateWeakenTime(server, Player) / 16, "w", server); } - startBackdoor(player: IPlayer): void { + startBackdoor(): void { // Backdoor should take the same amount of time as hack - const server = player.getCurrentServer(); + const server = Player.getCurrentServer(); if (server instanceof HacknetServer) { this.error("Cannot backdoor this kind of server"); return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - this.startAction(calculateHackingTime(server, player) / 4, "b", server); + this.startAction(calculateHackingTime(server, Player) / 4, "b", server); } - startAnalyze(player: IPlayer): void { + startAnalyze(): void { this.print("Analyzing system..."); - const server = player.getCurrentServer(); + const server = Player.getCurrentServer(); this.startAction(1, "a", server); } @@ -184,7 +184,7 @@ export class Terminal implements ITerminal { } // Complete the hack/analyze command - finishHack(router: IRouter, player: IPlayer, server: BaseServer, cancelled = false): void { + finishHack(server: BaseServer, cancelled = false): void { if (cancelled) return; if (server instanceof HacknetServer) { @@ -194,18 +194,18 @@ export class Terminal implements ITerminal { if (!(server instanceof Server)) throw new Error("server should be normal server"); // Calculate whether hack was successful - const hackChance = calculateHackingChance(server, player); + const hackChance = calculateHackingChance(server, Player); const rand = Math.random(); - const expGainedOnSuccess = calculateHackingExpGain(server, player); + const expGainedOnSuccess = calculateHackingExpGain(server, Player); const expGainedOnFailure = expGainedOnSuccess / 4; if (rand < hackChance) { // Success! server.backdoorInstalled = true; if (SpecialServers.WorldDaemon === server.hostname) { - router.toBitVerse(false, false); + Router.toBitVerse(false, false); return; } - let moneyGained = calculatePercentMoneyHacked(server, player) * BitNodeMultipliers.ManualHackMoney; + let moneyGained = calculatePercentMoneyHacked(server, Player) * BitNodeMultipliers.ManualHackMoney; moneyGained = Math.floor(server.moneyAvailable * moneyGained); if (moneyGained <= 0) { @@ -213,9 +213,9 @@ export class Terminal implements ITerminal { } // Safety check server.moneyAvailable -= moneyGained; - player.gainMoney(moneyGained, "hacking"); - player.gainHackingExp(expGainedOnSuccess); - player.gainIntelligenceExp(expGainedOnSuccess / CONSTANTS.IntelligenceTerminalHackBaseExpGain); + Player.gainMoney(moneyGained, "hacking"); + Player.gainHackingExp(expGainedOnSuccess); + Player.gainIntelligenceExp(expGainedOnSuccess / CONSTANTS.IntelligenceTerminalHackBaseExpGain); const oldSec = server.hackDifficulty; server.fortify(CONSTANTS.ServerFortifyAmount); @@ -233,14 +233,14 @@ export class Terminal implements ITerminal { ); } else { // Failure - player.gainHackingExp(expGainedOnFailure); + Player.gainHackingExp(expGainedOnFailure); this.print( `Failed to hack '${server.hostname}'. Gained ${numeralWrapper.formatExp(expGainedOnFailure)} hacking exp`, ); } } - finishGrow(player: IPlayer, server: BaseServer, cancelled = false): void { + finishGrow(server: BaseServer, cancelled = false): void { if (cancelled) return; if (server instanceof HacknetServer) { @@ -248,12 +248,12 @@ export class Terminal implements ITerminal { return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - const expGain = calculateHackingExpGain(server, player); + const expGain = calculateHackingExpGain(server, Player); const oldSec = server.hackDifficulty; - const growth = processSingleServerGrowth(server, 25, player, server.cpuCores) - 1; + const growth = processSingleServerGrowth(server, 25, Player, server.cpuCores) - 1; const newSec = server.hackDifficulty; - player.gainHackingExp(expGain); + Player.gainHackingExp(expGain); this.print( `Available money on '${server.hostname}' grown by ${numeralWrapper.formatPercentage( growth, @@ -267,7 +267,7 @@ export class Terminal implements ITerminal { ); } - finishWeaken(player: IPlayer, server: BaseServer, cancelled = false): void { + finishWeaken(server: BaseServer, cancelled = false): void { if (cancelled) return; if (server instanceof HacknetServer) { @@ -275,12 +275,12 @@ export class Terminal implements ITerminal { return; } if (!(server instanceof Server)) throw new Error("server should be normal server"); - const expGain = calculateHackingExpGain(server, player); + const expGain = calculateHackingExpGain(server, Player); const oldSec = server.hackDifficulty; server.weaken(CONSTANTS.ServerWeakenAmount); const newSec = server.hackDifficulty; - player.gainHackingExp(expGain); + Player.gainHackingExp(expGain); this.print( `Security decreased on '${server.hostname}' from ${numeralWrapper.formatSecurity( oldSec, @@ -289,7 +289,7 @@ export class Terminal implements ITerminal { ); } - finishBackdoor(router: IRouter, player: IPlayer, server: BaseServer, cancelled = false): void { + finishBackdoor(server: BaseServer, cancelled = false): void { if (!cancelled) { if (server instanceof HacknetServer) { this.error("Cannot hack this kind of server"); @@ -298,17 +298,17 @@ export class Terminal implements ITerminal { if (!(server instanceof Server)) throw new Error("server should be normal server"); server.backdoorInstalled = true; if (SpecialServers.WorldDaemon === server.hostname) { - if (player.bitNodeN == null) { - player.bitNodeN = 1; + if (Player.bitNodeN == null) { + Player.bitNodeN = 1; } - router.toBitVerse(false, false); + Router.toBitVerse(false, false); return; } this.print(`Backdoor on '${server.hostname}' successful!`); } } - finishAnalyze(player: IPlayer, currServ: BaseServer, cancelled = false): void { + finishAnalyze(currServ: BaseServer, cancelled = false): void { if (!cancelled) { const isHacknet = currServ instanceof HacknetServer; this.print(currServ.hostname + ": "); @@ -325,9 +325,9 @@ export class Terminal implements ITerminal { this.print("Required hacking skill for hack() and backdoor: " + (!isHacknet ? hackingSkill : "N/A")); const security = currServ.hackDifficulty; this.print("Server security level: " + (!isHacknet ? numeralWrapper.formatServerSecurity(security) : "N/A")); - const hackingChance = calculateHackingChance(currServ, player); + const hackingChance = calculateHackingChance(currServ, Player); this.print("Chance to hack: " + (!isHacknet ? numeralWrapper.formatPercentage(hackingChance) : "N/A")); - const hackingTime = calculateHackingTime(currServ, player) * 1000; + const hackingTime = calculateHackingTime(currServ, Player) * 1000; this.print("Time to hack: " + (!isHacknet ? convertTimeMsToTimeElapsedString(hackingTime, true) : "N/A")); } this.print( @@ -347,7 +347,7 @@ export class Terminal implements ITerminal { } } - finishAction(router: IRouter, player: IPlayer, cancelled = false): void { + finishAction(cancelled = false): void { if (this.action === null) { if (!cancelled) throw new Error("Finish action called when there was no action"); return; @@ -357,15 +357,15 @@ export class Terminal implements ITerminal { this.print(this.getProgressText()); if (this.action.action === "h") { - this.finishHack(router, player, this.action.server, cancelled); + this.finishHack(this.action.server, cancelled); } else if (this.action.action === "g") { - this.finishGrow(player, this.action.server, cancelled); + this.finishGrow(this.action.server, cancelled); } else if (this.action.action === "w") { - this.finishWeaken(player, this.action.server, cancelled); + this.finishWeaken(this.action.server, cancelled); } else if (this.action.action === "b") { - this.finishBackdoor(router, player, this.action.server, cancelled); + this.finishBackdoor(this.action.server, cancelled); } else if (this.action.action === "a") { - this.finishAnalyze(player, this.action.server, cancelled); + this.finishAnalyze(this.action.server, cancelled); } if (cancelled) { @@ -375,17 +375,17 @@ export class Terminal implements ITerminal { TerminalEvents.emit(); } - getFile(player: IPlayer, filename: string): Script | TextFile | string | null { + getFile(filename: string): Script | TextFile | string | null { if (isScriptFilename(filename)) { - return this.getScript(player, filename); + return this.getScript(filename); } if (filename.endsWith(".lit")) { - return this.getLitFile(player, filename); + return this.getLitFile(filename); } if (filename.endsWith(".txt")) { - return this.getTextFile(player, filename); + return this.getTextFile(filename); } return null; @@ -404,8 +404,8 @@ export class Terminal implements ITerminal { return path; } - getScript(player: IPlayer, filename: string): Script | null { - const s = player.getCurrentServer(); + getScript(filename: string): Script | null { + const s = Player.getCurrentServer(); const filepath = this.getFilepath(filename); for (const script of s.scripts) { if (filepath === script.filename) { @@ -416,8 +416,8 @@ export class Terminal implements ITerminal { return null; } - getTextFile(player: IPlayer, filename: string): TextFile | null { - const s = player.getCurrentServer(); + getTextFile(filename: string): TextFile | null { + const s = Player.getCurrentServer(); const filepath = this.getFilepath(filename); for (const txt of s.textFiles) { if (filepath === txt.fn) { @@ -428,8 +428,8 @@ export class Terminal implements ITerminal { return null; } - getLitFile(player: IPlayer, filename: string): string | null { - const s = player.getCurrentServer(); + getLitFile(filename: string): string | null { + const s = Player.getCurrentServer(); const filepath = this.getFilepath(filename); for (const lit of s.messages) { if (typeof lit === "string" && filepath === lit) { @@ -449,13 +449,13 @@ export class Terminal implements ITerminal { TerminalEvents.emit(); } - async runContract(player: IPlayer, contractName: string): Promise { + async runContract(contractName: string): Promise { // There's already an opened contract if (this.contractOpen) { return this.error("There's already a Coding Contract in Progress"); } - const serv = player.getCurrentServer(); + const serv = Player.getCurrentServer(); const contract = serv.getContract(contractName); if (contract == null) { return this.error("No such contract"); @@ -473,7 +473,7 @@ export class Terminal implements ITerminal { switch (res) { case CodingContractResult.Success: if (contract.reward !== null) { - const reward = player.gainCodingContractReward(contract.reward, contract.getDifficulty()); + const reward = Player.gainCodingContractReward(contract.reward, contract.getDifficulty()); this.print(`Contract SUCCESS - ${reward}`); } serv.removeContract(contract); @@ -495,7 +495,7 @@ export class Terminal implements ITerminal { this.contractOpen = false; } - executeScanAnalyzeCommand(player: IPlayer, depth = 1, all = false): void { + executeScanAnalyzeCommand(depth = 1, all = false): void { // TODO Using array as stack for now, can make more efficient this.print("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~"); this.print(" "); @@ -510,7 +510,7 @@ export class Terminal implements ITerminal { const stack: BaseServer[] = []; const depthQueue: number[] = [0]; - const currServ = player.getCurrentServer(); + const currServ = Player.getCurrentServer(); stack.push(currServ); while (stack.length != 0) { const s = stack.pop(); @@ -537,7 +537,7 @@ export class Terminal implements ITerminal { continue; } // Don't print current server const titleDashes = Array((d - 1) * 4 + 1).join("-"); - if (player.hasProgram(Programs.AutoLink.name)) { + if (Player.hasProgram(Programs.AutoLink.name)) { this.append(new Link(titleDashes, s.hostname)); } else { this.print(titleDashes + s.hostname); @@ -562,23 +562,23 @@ export class Terminal implements ITerminal { } } - connectToServer(player: IPlayer, server: string): void { + connectToServer(server: string): void { const serv = GetServer(server); if (serv == null) { this.error("Invalid server. Connection failed."); return; } - player.getCurrentServer().isConnectedTo = false; - player.currentServer = serv.hostname; - player.getCurrentServer().isConnectedTo = true; + Player.getCurrentServer().isConnectedTo = false; + Player.currentServer = serv.hostname; + Player.getCurrentServer().isConnectedTo = true; this.print("Connected to " + serv.hostname); this.setcwd("/"); - if (player.getCurrentServer().hostname == "darkweb") { + if (Player.getCurrentServer().hostname == "darkweb") { checkIfConnectedToDarkweb(); // Posts a 'help' message if connecting to dark web } } - executeCommands(router: IRouter, player: IPlayer, commands: string): void { + executeCommands(commands: string): void { // Sanitize input commands = commands.trim(); commands = commands.replace(/\s\s+/g, " "); // Replace all extra whitespace in command with a single space @@ -589,13 +589,13 @@ export class Terminal implements ITerminal { if (this.commandHistory.length > 50) { this.commandHistory.splice(0, 1); } - player.terminalCommandHistory = this.commandHistory; + Player.terminalCommandHistory = this.commandHistory; } this.commandHistoryIndex = this.commandHistory.length; const allCommands = ParseCommands(commands); for (let i = 0; i < allCommands.length; i++) { - this.executeCommand(router, player, allCommands[i]); + this.executeCommand(allCommands[i]); } } @@ -610,7 +610,7 @@ export class Terminal implements ITerminal { this.clear(); } - executeCommand(router: IRouter, player: IPlayer, command: string): void { + executeCommand(command: string): void { if (this.action !== null) { this.error(`Cannot execute command (${command}) while an action is in progress`); return; @@ -624,7 +624,7 @@ export class Terminal implements ITerminal { if (commandArray.length == 0) { return; } - const s = player.getCurrentServer(); + const s = Player.getCurrentServer(); /****************** Interactive Tutorial Terminal Commands ******************/ if (ITutorial.isRunning) { const n00dlesServ = GetServer("n00dles"); @@ -785,11 +785,8 @@ export class Terminal implements ITerminal { const commands: { [key: string]: ( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ) => void; } = { "scan-analyze": scananalyze, @@ -841,7 +838,7 @@ export class Terminal implements ITerminal { return; } - f(this, router, player, s, commandArray.slice(1)); + f(commandArray.slice(1), s); } getProgressText(): string { diff --git a/src/Terminal/commands/alias.ts b/src/Terminal/commands/alias.ts index 1e908baf8..d5c7f8d37 100644 --- a/src/Terminal/commands/alias.ts +++ b/src/Terminal/commands/alias.ts @@ -1,33 +1,24 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; import { parseAliasDeclaration, printAliases } from "../../Alias"; -export function alias( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function alias(args: (string | number | boolean)[]): void { if (args.length === 0) { printAliases(); return; } if (args.length === 1) { if (parseAliasDeclaration(args[0] + "")) { - terminal.print(`Set alias ${args[0]}`); + Terminal.print(`Set alias ${args[0]}`); return; } } if (args.length === 2) { if (args[0] === "-g") { if (parseAliasDeclaration(args[1] + "", true)) { - terminal.print(`Set global alias ${args[1]}`); + Terminal.print(`Set global alias ${args[1]}`); return; } } } - terminal.error('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]'); + Terminal.error('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]'); } diff --git a/src/Terminal/commands/analyze.ts b/src/Terminal/commands/analyze.ts index 2544d837f..674b1db76 100644 --- a/src/Terminal/commands/analyze.ts +++ b/src/Terminal/commands/analyze.ts @@ -1,18 +1,9 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; -export function analyze( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function analyze(args: (string | number | boolean)[]): void { if (args.length !== 0) { - terminal.error("Incorrect usage of analyze command. Usage: analyze"); + Terminal.error("Incorrect usage of analyze command. Usage: analyze"); return; } - terminal.startAnalyze(player); + Terminal.startAnalyze(); } diff --git a/src/Terminal/commands/backdoor.ts b/src/Terminal/commands/backdoor.ts index 2f49745e9..9766ce073 100644 --- a/src/Terminal/commands/backdoor.ts +++ b/src/Terminal/commands/backdoor.ts @@ -1,41 +1,34 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { BaseServer } from "../../Server/BaseServer"; import { Server } from "../../Server/Server"; import { HacknetServer } from "../../Hacknet/HacknetServer"; -export function backdoor( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function backdoor(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 0) { - terminal.error("Incorrect usage of backdoor command. Usage: backdoor"); + Terminal.error("Incorrect usage of backdoor command. Usage: backdoor"); return; } if (!(server instanceof Server)) { - terminal.error("Can only backdoor normal servers"); + Terminal.error("Can only backdoor normal servers"); } const normalServer = server as Server; if (normalServer.purchasedByPlayer) { - terminal.error( + Terminal.error( "Cannot use backdoor on your own machines! You are currently connected to your home PC or one of your purchased servers", ); } else if (!normalServer.hasAdminRights) { - terminal.error("You do not have admin rights for this machine! Cannot backdoor"); - } else if (normalServer.requiredHackingSkill > player.skills.hacking) { - terminal.error( + Terminal.error("You do not have admin rights for this machine! Cannot backdoor"); + } else if (normalServer.requiredHackingSkill > Player.skills.hacking) { + Terminal.error( "Your hacking skill is not high enough to use backdoor on this machine. Try analyzing the machine to determine the required hacking skill", ); } else if (normalServer instanceof HacknetServer) { - terminal.error("Cannot use backdoor on this type of Server"); + Terminal.error("Cannot use backdoor on this type of Server"); } else { - terminal.startBackdoor(player); + Terminal.startBackdoor(); } } diff --git a/src/Terminal/commands/buy.ts b/src/Terminal/commands/buy.ts index 88a6b685c..50a90d169 100644 --- a/src/Terminal/commands/buy.ts +++ b/src/Terminal/commands/buy.ts @@ -1,35 +1,23 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { listAllDarkwebItems, buyAllDarkwebItems, buyDarkwebItem } from "../../DarkWeb/DarkWeb"; -export function buy( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { - if (!player.hasTorRouter()) { - terminal.error( +export function buy(args: (string | number | boolean)[]): void { + if (!Player.hasTorRouter()) { + Terminal.error( "You need to be able to connect to the Dark Web to use the buy command. (Maybe there's a TOR router you can buy somewhere)", ); return; } if (args.length != 1) { - terminal.print("Incorrect number of arguments. Usage: "); - terminal.print("buy -l"); - terminal.print("buy -a"); - terminal.print("buy [item name]"); + Terminal.print("Incorrect number of arguments. Usage: "); + Terminal.print("buy -l"); + Terminal.print("buy -a"); + Terminal.print("buy [item name]"); return; } const arg = args[0] + ""; - if (arg == "-l" || arg == "-1" || arg == "--list") { - listAllDarkwebItems(); - } else if (arg == "-a" || arg == "--all") { - buyAllDarkwebItems(); - } else { - buyDarkwebItem(arg); - } + if (arg == "-l" || arg == "-1" || arg == "--list") listAllDarkwebItems(); + else if (arg == "-a" || arg == "--all") buyAllDarkwebItems(); + else buyDarkwebItem(arg); } diff --git a/src/Terminal/commands/cat.ts b/src/Terminal/commands/cat.ts index 5d9723738..0807e8a84 100644 --- a/src/Terminal/commands/cat.ts +++ b/src/Terminal/commands/cat.ts @@ -1,25 +1,17 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { MessageFilenames, showMessage } from "../../Message/MessageHelpers"; import { showLiterature } from "../../Literature/LiteratureHelpers"; import { dialogBoxCreate } from "../../ui/React/DialogBox"; import { checkEnum } from "../../utils/helpers/checkEnum"; -export function cat( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function cat(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 1) { - terminal.error("Incorrect usage of cat command. Usage: cat [file]"); + Terminal.error("Incorrect usage of cat command. Usage: cat [file]"); return; } const relative_filename = args[0] + ""; - const filename = terminal.getFilepath(relative_filename); + const filename = Terminal.getFilepath(relative_filename); if ( !filename.endsWith(".msg") && !filename.endsWith(".lit") && @@ -27,7 +19,7 @@ export function cat( !filename.endsWith(".script") && !filename.endsWith(".js") ) { - terminal.error( + Terminal.error( "Only .msg, .txt, .lit, .script and .js files are viewable with cat (filename must end with .msg, .txt, .lit, .script or .js)", ); return; @@ -49,18 +41,18 @@ export function cat( } } } else if (filename.endsWith(".txt")) { - const txt = terminal.getTextFile(player, relative_filename); + const txt = Terminal.getTextFile(relative_filename); if (txt != null) { txt.show(); return; } } else if (filename.endsWith(".script") || filename.endsWith(".js")) { - const script = terminal.getScript(player, relative_filename); + const script = Terminal.getScript(relative_filename); if (script != null) { dialogBoxCreate(`${script.filename}

    ${script.code}`); return; } } - terminal.error(`No such file ${filename}`); + Terminal.error(`No such file ${filename}`); } diff --git a/src/Terminal/commands/cd.ts b/src/Terminal/commands/cd.ts index 174f557bd..e67ef32ed 100644 --- a/src/Terminal/commands/cd.ts +++ b/src/Terminal/commands/cd.ts @@ -1,20 +1,12 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { evaluateDirectoryPath, removeTrailingSlash } from "../DirectoryHelpers"; import { containsFiles } from "../DirectoryServerHelpers"; -export function cd( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function cd(args: (string | number | boolean)[], server: BaseServer): void { if (args.length > 1) { - terminal.error("Incorrect number of arguments. Usage: cd [dir]"); + Terminal.error("Incorrect number of arguments. Usage: cd [dir]"); } else { let dir = args.length === 1 ? args[0] + "" : "/"; @@ -25,23 +17,22 @@ export function cd( // Ignore trailing slashes dir = removeTrailingSlash(dir); - evaledDir = evaluateDirectoryPath(dir, terminal.cwd()); + evaledDir = evaluateDirectoryPath(dir, Terminal.cwd()); if (evaledDir === null || evaledDir === "") { - terminal.error("Invalid path. Failed to change directories"); + Terminal.error("Invalid path. Failed to change directories"); return; } - if (terminal.cwd().length > 1 && dir === "..") { - terminal.setcwd(evaledDir); + if (Terminal.cwd().length > 1 && dir === "..") { + Terminal.setcwd(evaledDir); return; } - const server = player.getCurrentServer(); if (!containsFiles(server, evaledDir)) { - terminal.error("Invalid path. Failed to change directories"); + Terminal.error("Invalid path. Failed to change directories"); return; } } - terminal.setcwd(evaledDir); + Terminal.setcwd(evaledDir); } } diff --git a/src/Terminal/commands/check.ts b/src/Terminal/commands/check.ts index 0bc198a2f..852874570 100644 --- a/src/Terminal/commands/check.ts +++ b/src/Terminal/commands/check.ts @@ -1,24 +1,16 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { findRunningScript } from "../../Script/ScriptHelpers"; import { isScriptFilename, validScriptExtensions } from "../../Script/isScriptFilename"; -export function check( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function check(args: (string | number | boolean)[], server: BaseServer): void { if (args.length < 1) { - terminal.error(`Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...`); + Terminal.error(`Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...`); } else { - const scriptName = terminal.getFilepath(args[0] + ""); + const scriptName = Terminal.getFilepath(args[0] + ""); // Can only tail script files if (!isScriptFilename(scriptName)) { - terminal.error( + Terminal.error( `'check' can only be called on scripts files (filename must end with ${validScriptExtensions.join(", ")})`, ); return; @@ -27,7 +19,7 @@ export function check( // Check that the script is running on this machine const runningScript = findRunningScript(scriptName, args.slice(1), server); if (runningScript == null) { - terminal.error(`No script named ${scriptName} is running on the server`); + Terminal.error(`No script named ${scriptName} is running on the server`); return; } runningScript.displayLog(); diff --git a/src/Terminal/commands/common/editor.ts b/src/Terminal/commands/common/editor.ts index f24e0b029..8fab8804c 100644 --- a/src/Terminal/commands/common/editor.ts +++ b/src/Terminal/commands/common/editor.ts @@ -1,7 +1,7 @@ -import { ITerminal } from "../../ITerminal"; +import { Terminal } from "../../../Terminal"; import { removeLeadingSlash, removeTrailingSlash } from "../../DirectoryHelpers"; -import { IRouter, ScriptEditorRouteOptions } from "../../../ui/Router"; -import { IPlayer } from "../../../PersonObjects/IPlayer"; +import { ScriptEditorRouteOptions } from "../../../ui/Router"; +import { Router } from "../../../ui/GameRoot"; import { BaseServer } from "../../../Server/BaseServer"; import { isScriptFilename } from "../../../Script/isScriptFilename"; import { CursorPositions } from "../../../ScriptEditor/CursorPositions"; @@ -9,11 +9,8 @@ import { Script } from "../../../Script/Script"; import { isEmpty } from "lodash"; interface EditorParameters { - terminal: ITerminal; - router: IRouter; - player: IPlayer; - server: BaseServer; args: (string | number | boolean)[]; + server: BaseServer; } function isNs2(filename: string): boolean { @@ -38,21 +35,17 @@ function containsSimpleGlob(filename: string): boolean { return filename.includes("*"); } -function detectSimpleScriptGlob( - args: EditorParameters["args"], - player: IPlayer, - terminal: ITerminal, -): ISimpleScriptGlob | null { +function detectSimpleScriptGlob({ args, server }: EditorParameters): ISimpleScriptGlob | null { if (args.length == 1 && containsSimpleGlob(`${args[0]}`)) { const filename = `${args[0]}`; - const scripts = player.getCurrentServer().scripts; - const parsedGlob = parseSimpleScriptGlob(filename, scripts, terminal); + const scripts = server.scripts; + const parsedGlob = parseSimpleScriptGlob(filename, scripts); return parsedGlob; } return null; } -function parseSimpleScriptGlob(globString: string, globDatabase: Script[], terminal: ITerminal): ISimpleScriptGlob { +function parseSimpleScriptGlob(globString: string, globDatabase: Script[]): ISimpleScriptGlob { const parsedGlob: ISimpleScriptGlob = { glob: globString, preGlob: "", @@ -76,7 +69,7 @@ function parseSimpleScriptGlob(globString: string, globDatabase: Script[], termi parsedGlob.preGlob = removeLeadingSlash(parsedGlob.preGlob); // Add CWD to preGlob path - const cwd = removeTrailingSlash(terminal.cwd()); + const cwd = removeTrailingSlash(Terminal.cwd()); parsedGlob.preGlob = `${cwd}/${parsedGlob.preGlob}`; // For every script on the current server, filter matched scripts per glob values & persist @@ -95,17 +88,17 @@ function parseSimpleScriptGlob(globString: string, globDatabase: Script[], termi export function commonEditor( command: string, - { terminal, router, player, args }: EditorParameters, + { args, server }: EditorParameters, scriptEditorRouteOptions?: ScriptEditorRouteOptions, ): void { if (args.length < 1) { - terminal.error(`Incorrect usage of ${command} command. Usage: ${command} [scriptname]`); + Terminal.error(`Incorrect usage of ${command} command. Usage: ${command} [scriptname]`); return; } let filesToLoadOrCreate = args; try { - const globSearch = detectSimpleScriptGlob(args, player, terminal); + const globSearch = detectSimpleScriptGlob({ args, server }); if (globSearch) { if (isEmpty(globSearch.globError) === false) throw new Error(globSearch.globError); filesToLoadOrCreate = globSearch.globMatches; @@ -115,8 +108,8 @@ export function commonEditor( const filename = `${arg}`; if (isScriptFilename(filename)) { - const filepath = terminal.getFilepath(filename); - const script = terminal.getScript(player, filename); + const filepath = Terminal.getFilepath(filename); + const script = Terminal.getScript(filename); const fileIsNs2 = isNs2(filename); const code = script !== null ? script.code : fileIsNs2 ? newNs2Template : ""; @@ -131,8 +124,8 @@ export function commonEditor( } if (filename.endsWith(".txt")) { - const filepath = terminal.getFilepath(filename); - const txt = terminal.getTextFile(player, filename); + const filepath = Terminal.getFilepath(filename); + const txt = Terminal.getTextFile(filename); return [filepath, txt === null ? "" : txt.text]; } @@ -145,8 +138,8 @@ export function commonEditor( throw new Error(`Could not find any valid files to open with ${command} using glob: \`${globSearch.glob}\``); } - router.toScriptEditor(Object.fromEntries(files), scriptEditorRouteOptions); + Router.toScriptEditor(Object.fromEntries(files), scriptEditorRouteOptions); } catch (e) { - terminal.error(`${e}`); + Terminal.error(`${e}`); } } diff --git a/src/Terminal/commands/connect.ts b/src/Terminal/commands/connect.ts index c36e5541f..a5583010f 100644 --- a/src/Terminal/commands/connect.ts +++ b/src/Terminal/commands/connect.ts @@ -1,21 +1,13 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { getServerOnNetwork } from "../../Server/ServerHelpers"; import { GetServer } from "../../Server/AllServers"; import { Server } from "../../Server/Server"; -export function connect( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { - // Disconnect from current server in terminal and connect to new one +export function connect(args: (string | number | boolean)[], server: BaseServer): void { + // Disconnect from current server in Terminal and connect to new one if (args.length !== 1) { - terminal.error("Incorrect usage of connect command. Usage: connect [hostname]"); + Terminal.error("Incorrect usage of connect command. Usage: connect [hostname]"); return; } @@ -25,7 +17,7 @@ export function connect( const other = getServerOnNetwork(server, i); if (other === null) throw new Error(`Server on network should not be null`); if (other.hostname == hostname) { - terminal.connectToServer(player, hostname); + Terminal.connectToServer(hostname); return; } } @@ -33,13 +25,13 @@ export function connect( const other = GetServer(hostname); if (other !== null) { if (other instanceof Server && other.backdoorInstalled) { - terminal.connectToServer(player, hostname); + Terminal.connectToServer(hostname); return; } - terminal.error( + Terminal.error( `Cannot directly connect to ${hostname}. Make sure the server is backdoored or adjacent to your current Server`, ); } else { - terminal.error("Host not found"); + Terminal.error("Host not found"); } } diff --git a/src/Terminal/commands/cp.ts b/src/Terminal/commands/cp.ts index 021e9c60d..1038cd6f7 100644 --- a/src/Terminal/commands/cp.ts +++ b/src/Terminal/commands/cp.ts @@ -1,50 +1,45 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { isScriptFilename } from "../../Script/isScriptFilename"; import { getDestinationFilepath, areFilesEqual } from "../DirectoryHelpers"; export function cp( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { try { if (args.length !== 2) { - terminal.error("Incorrect usage of cp command. Usage: cp [src] [dst]"); + Terminal.error("Incorrect usage of cp command. Usage: cp [src] [dst]"); return; } // Convert a relative path source file to the absolute path. - const src = terminal.getFilepath(args[0] + ""); + const src = Terminal.getFilepath(args[0] + ""); if (src === null) { - terminal.error("src cannot be a directory"); + Terminal.error("src cannot be a directory"); return; } // Get the destination based on the source file and the current directory - const t_dst = getDestinationFilepath(args[1] + "", src, terminal.cwd()); + const t_dst = getDestinationFilepath(args[1] + "", src, Terminal.cwd()); if (t_dst === null) { - terminal.error("error parsing dst file"); + Terminal.error("error parsing dst file"); return; } // Convert a relative path destination file to the absolute path. - const dst = terminal.getFilepath(t_dst); + const dst = Terminal.getFilepath(t_dst); if (areFilesEqual(src, dst)) { - terminal.error("src and dst cannot be the same"); + Terminal.error("src and dst cannot be the same"); return; } const srcExt = src.slice(src.lastIndexOf(".")); const dstExt = dst.slice(dst.lastIndexOf(".")); if (srcExt !== dstExt) { - terminal.error("src and dst must have the same extension."); + Terminal.error("src and dst must have the same extension."); return; } if (!isScriptFilename(src) && !src.endsWith(".txt")) { - terminal.error("cp only works for scripts and .txt files"); + Terminal.error("cp only works for scripts and .txt files"); return; } @@ -59,20 +54,20 @@ export function cp( } if (txtFile === null) { - return terminal.error("No such file exists!"); + return Terminal.error("No such file exists!"); } const tRes = server.writeToTextFile(dst, txtFile.text); if (!tRes.success) { - terminal.error("cp failed"); + Terminal.error("cp failed"); return; } if (tRes.overwritten) { - terminal.print(`WARNING: ${dst} already exists and will be overwriten`); - terminal.print(`${dst} overwritten`); + Terminal.print(`WARNING: ${dst} already exists and will be overwriten`); + Terminal.print(`${dst} overwritten`); return; } - terminal.print(`${dst} copied`); + Terminal.print(`${dst} copied`); return; } @@ -85,22 +80,22 @@ export function cp( } } if (sourceScript == null) { - terminal.error("cp failed. No such script exists"); + Terminal.error("cp failed. No such script exists"); return; } const sRes = server.writeToScriptFile(dst, sourceScript.code); if (!sRes.success) { - terminal.error(`cp failed`); + Terminal.error(`cp failed`); return; } if (sRes.overwritten) { - terminal.print(`WARNING: ${dst} already exists and will be overwritten`); - terminal.print(`${dst} overwritten`); + Terminal.print(`WARNING: ${dst} already exists and will be overwritten`); + Terminal.print(`${dst} overwritten`); return; } - terminal.print(`${dst} copied`); + Terminal.print(`${dst} copied`); } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/download.ts b/src/Terminal/commands/download.ts index 7060ee4b7..6a0902639 100644 --- a/src/Terminal/commands/download.ts +++ b/src/Terminal/commands/download.ts @@ -1,6 +1,4 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { isScriptFilename } from "../../Script/isScriptFilename"; import FileSaver from "file-saver"; @@ -37,16 +35,10 @@ export function exportScripts(pattern: string, server: BaseServer): void { zip.generateAsync({ type: "blob" }).then((content: Blob) => FileSaver.saveAs(content, zipFn)); } -export function download( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function download(args: (string | number | boolean)[], server: BaseServer): void { try { if (args.length !== 1) { - terminal.error("Incorrect usage of download command. Usage: download [script/text file]"); + Terminal.error("Incorrect usage of download command. Usage: download [script/text file]"); return; } const fn = args[0] + ""; @@ -60,28 +52,28 @@ export function download( if (e !== null && typeof e == "object" && e.hasOwnProperty("message")) { msg = String((e as { message: unknown }).message); } - return terminal.error(msg); + return Terminal.error(msg); } } else if (isScriptFilename(fn)) { // Download a single script - const script = terminal.getScript(player, fn); + const script = Terminal.getScript(fn); if (script != null) { return script.download(); } } else if (fn.endsWith(".txt")) { // Download a single text file - const txt = terminal.getTextFile(player, fn); + const txt = Terminal.getTextFile(fn); if (txt != null) { return txt.download(); } } else { - terminal.error(`Cannot download this filetype`); + Terminal.error(`Cannot download this filetype`); return; } - terminal.error(`${fn} does not exist`); + Terminal.error(`${fn} does not exist`); return; } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); return; } } diff --git a/src/Terminal/commands/expr.ts b/src/Terminal/commands/expr.ts index 5645431e3..fffd00d9a 100644 --- a/src/Terminal/commands/expr.ts +++ b/src/Terminal/commands/expr.ts @@ -1,17 +1,8 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; -export function expr( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function expr(args: (string | number | boolean)[]): void { if (args.length === 0) { - terminal.error("Incorrect usage of expr command. Usage: expr [math expression]"); + Terminal.error("Incorrect usage of expr command. Usage: expr [math expression]"); return; } const expr = args.join(""); @@ -22,8 +13,8 @@ export function expr( try { result = eval(sanitizedExpr); } catch (e) { - terminal.error(`Could not evaluate expression: ${sanitizedExpr}`); + Terminal.error(`Could not evaluate expression: ${sanitizedExpr}`); return; } - terminal.print(result); + Terminal.print(result); } diff --git a/src/Terminal/commands/free.ts b/src/Terminal/commands/free.ts index d86917003..88cc43ac4 100644 --- a/src/Terminal/commands/free.ts +++ b/src/Terminal/commands/free.ts @@ -1,29 +1,19 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { numeralWrapper } from "../../ui/numeralFormat"; -export function free( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function free(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 0) { - terminal.error("Incorrect usage of free command. Usage: free"); + Terminal.error("Incorrect usage of free command. Usage: free"); return; } - const ram = numeralWrapper.formatRAM(player.getCurrentServer().maxRam); - const used = numeralWrapper.formatRAM(player.getCurrentServer().ramUsed); - const avail = numeralWrapper.formatRAM(player.getCurrentServer().maxRam - player.getCurrentServer().ramUsed); + const ram = numeralWrapper.formatRAM(server.maxRam); + const used = numeralWrapper.formatRAM(server.ramUsed); + const avail = numeralWrapper.formatRAM(server.maxRam - server.ramUsed); const maxLength = Math.max(ram.length, Math.max(used.length, avail.length)); - const usedPercent = numeralWrapper.formatPercentage( - player.getCurrentServer().ramUsed / player.getCurrentServer().maxRam, - ); + const usedPercent = numeralWrapper.formatPercentage(server.ramUsed / server.maxRam); - terminal.print(`Total: ${" ".repeat(maxLength - ram.length)}${ram}`); - terminal.print(`Used: ${" ".repeat(maxLength - used.length)}${used} (${usedPercent})`); - terminal.print(`Available: ${" ".repeat(maxLength - avail.length)}${avail}`); + Terminal.print(`Total: ${" ".repeat(maxLength - ram.length)}${ram}`); + Terminal.print(`Used: ${" ".repeat(maxLength - used.length)}${used} (${usedPercent})`); + Terminal.print(`Available: ${" ".repeat(maxLength - avail.length)}${avail}`); } diff --git a/src/Terminal/commands/grow.ts b/src/Terminal/commands/grow.ts index 6169a3a99..a87cd1847 100644 --- a/src/Terminal/commands/grow.ts +++ b/src/Terminal/commands/grow.ts @@ -1,23 +1,19 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { BaseServer } from "../../Server/BaseServer"; import { Server } from "../../Server/Server"; export function grow( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { if (args.length !== 0) { - terminal.error("Incorrect usage of grow command. Usage: grow"); + Terminal.error("Incorrect usage of grow command. Usage: grow"); return; } if (!(server instanceof Server)) { - terminal.error( + Terminal.error( "Cannot grow your own machines! You are currently connected to your home PC or one of your purchased servers", ); } @@ -25,20 +21,20 @@ export function grow( // Hack the current PC (usually for money) // You can't grow your home pc or servers you purchased if (normalServer.purchasedByPlayer) { - terminal.error( + Terminal.error( "Cannot grow your own machines! You are currently connected to your home PC or one of your purchased servers", ); return; } if (!normalServer.hasAdminRights) { - terminal.error("You do not have admin rights for this machine! Cannot grow"); + Terminal.error("You do not have admin rights for this machine! Cannot grow"); return; } - if (normalServer.requiredHackingSkill > player.skills.hacking) { - terminal.error( + if (normalServer.requiredHackingSkill > Player.skills.hacking) { + Terminal.error( "Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill", ); return; } - terminal.startGrow(player); + Terminal.startGrow(); } diff --git a/src/Terminal/commands/hack.ts b/src/Terminal/commands/hack.ts index cc66bd26a..039ad6461 100644 --- a/src/Terminal/commands/hack.ts +++ b/src/Terminal/commands/hack.ts @@ -1,23 +1,19 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { BaseServer } from "../../Server/BaseServer"; import { Server } from "../../Server/Server"; export function hack( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { if (args.length !== 0) { - terminal.error("Incorrect usage of hack command. Usage: hack"); + Terminal.error("Incorrect usage of hack command. Usage: hack"); return; } if (!(server instanceof Server)) { - terminal.error( + Terminal.error( "Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers", ); } @@ -25,20 +21,20 @@ export function hack( // Hack the current PC (usually for money) // You can't hack your home pc or servers you purchased if (normalServer.purchasedByPlayer) { - terminal.error( + Terminal.error( "Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers", ); return; } if (!normalServer.hasAdminRights) { - terminal.error("You do not have admin rights for this machine! Cannot hack"); + Terminal.error("You do not have admin rights for this machine! Cannot hack"); return; } - if (normalServer.requiredHackingSkill > player.skills.hacking) { - terminal.error( + if (normalServer.requiredHackingSkill > Player.skills.hacking) { + Terminal.error( "Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill", ); return; } - terminal.startHack(player); + Terminal.startHack(); } diff --git a/src/Terminal/commands/help.ts b/src/Terminal/commands/help.ts index 23de8028f..6bdf2a0d5 100644 --- a/src/Terminal/commands/help.ts +++ b/src/Terminal/commands/help.ts @@ -1,29 +1,20 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; import { TerminalHelpText, HelpTexts } from "../HelpText"; -export function help( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function help(args: (string | number | boolean)[]): void { if (args.length !== 0 && args.length !== 1) { - terminal.error("Incorrect usage of help command. Usage: help"); + Terminal.error("Incorrect usage of help command. Usage: help"); return; } if (args.length === 0) { - TerminalHelpText.forEach((line) => terminal.print(line)); + TerminalHelpText.forEach((line) => Terminal.print(line)); } else { const cmd = args[0] + ""; const txt = HelpTexts[cmd]; if (txt == null) { - terminal.error("No help topics match '" + cmd + "'"); + Terminal.error("No help topics match '" + cmd + "'"); return; } - txt.forEach((t) => terminal.print(t)); + txt.forEach((t) => Terminal.print(t)); } } diff --git a/src/Terminal/commands/history.ts b/src/Terminal/commands/history.ts index 32a51f162..57076e406 100644 --- a/src/Terminal/commands/history.ts +++ b/src/Terminal/commands/history.ts @@ -1,27 +1,19 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; -export function history( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function history(args: (string | number | boolean)[]): void { if (args.length === 0) { - terminal.commandHistory.forEach((command, index) => { - terminal.print(`${index.toString().padStart(2)} ${command}`); + Terminal.commandHistory.forEach((command, index) => { + Terminal.print(`${index.toString().padStart(2)} ${command}`); }); return; } const arg = args[0] + ""; if (arg === "-c" || arg === "--clear") { - player.terminalCommandHistory = []; - terminal.commandHistory = []; - terminal.commandHistoryIndex = 1; + Player.terminalCommandHistory = []; + Terminal.commandHistory = []; + Terminal.commandHistoryIndex = 1; } else { - terminal.error("Incorrect usage of history command. usage: history [-c]"); + Terminal.error("Incorrect usage of history command. usage: history [-c]"); } } diff --git a/src/Terminal/commands/home.ts b/src/Terminal/commands/home.ts index b20fdebd0..d26f44ef0 100644 --- a/src/Terminal/commands/home.ts +++ b/src/Terminal/commands/home.ts @@ -1,22 +1,16 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; export function home( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], ): void { if (args.length !== 0) { - terminal.error("Incorrect usage of home command. Usage: home"); + Terminal.error("Incorrect usage of home command. Usage: home"); return; } - player.getCurrentServer().isConnectedTo = false; - player.currentServer = player.getHomeComputer().hostname; - player.getCurrentServer().isConnectedTo = true; - terminal.print("Connected to home"); - terminal.setcwd("/"); + Player.getCurrentServer().isConnectedTo = false; + Player.currentServer = Player.getHomeComputer().hostname; + Player.getCurrentServer().isConnectedTo = true; + Terminal.print("Connected to home"); + Terminal.setcwd("/"); } diff --git a/src/Terminal/commands/hostname.ts b/src/Terminal/commands/hostname.ts index 7c061d93f..767763808 100644 --- a/src/Terminal/commands/hostname.ts +++ b/src/Terminal/commands/hostname.ts @@ -1,18 +1,10 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; -export function hostname( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function hostname(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 0) { - terminal.error("Incorrect usage of hostname command. Usage: hostname"); + Terminal.error("Incorrect usage of hostname command. Usage: hostname"); return; } - terminal.print(player.getCurrentServer().hostname); + Terminal.print(server.hostname); } diff --git a/src/Terminal/commands/kill.ts b/src/Terminal/commands/kill.ts index 652043496..92f0f89f4 100644 --- a/src/Terminal/commands/kill.ts +++ b/src/Terminal/commands/kill.ts @@ -1,19 +1,11 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { killWorkerScript } from "../../Netscript/killWorkerScript"; -export function kill( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function kill(args: (string | number | boolean)[], server: BaseServer): void { try { if (args.length < 1) { - terminal.error("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]..."); + Terminal.error("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]..."); return; } if (typeof args[0] === "boolean") { @@ -25,23 +17,23 @@ export function kill( const pid = args[0]; const res = killWorkerScript(pid); if (res) { - terminal.print(`Killing script with PID ${pid}`); + Terminal.print(`Killing script with PID ${pid}`); } else { - terminal.error(`Failed to kill script with PID ${pid}. No such script is running`); + Terminal.error(`Failed to kill script with PID ${pid}. No such script is running`); } return; } - const scriptName = terminal.getFilepath(args[0]); + const scriptName = Terminal.getFilepath(args[0]); const runningScript = server.getRunningScript(scriptName, args.slice(1)); if (runningScript == null) { - terminal.error("No such script is running. Nothing to kill"); + Terminal.error("No such script is running. Nothing to kill"); return; } killWorkerScript({ runningScript: runningScript, hostname: server.hostname }); - terminal.print(`Killing ${scriptName}`); + Terminal.print(`Killing ${scriptName}`); } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/killall.ts b/src/Terminal/commands/killall.ts index 6c670fe07..28ec0950d 100644 --- a/src/Terminal/commands/killall.ts +++ b/src/Terminal/commands/killall.ts @@ -1,14 +1,12 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { killWorkerScript } from "../../Netscript/killWorkerScript"; import { WorkerScriptStartStopEventEmitter } from "../../Netscript/WorkerScriptStartStopEventEmitter"; -export function killall(terminal: ITerminal, router: IRouter, player: IPlayer, server: BaseServer): void { +export function killall(_args: (string | number | boolean)[], server: BaseServer): void { for (let i = server.runningScripts.length - 1; i >= 0; --i) { killWorkerScript({ runningScript: server.runningScripts[i], hostname: server.hostname }); } WorkerScriptStartStopEventEmitter.emit(); - terminal.print("Killing all running scripts"); + Terminal.print("Killing all running scripts"); } diff --git a/src/Terminal/commands/ls.tsx b/src/Terminal/commands/ls.tsx index f66560e77..a05e43235 100644 --- a/src/Terminal/commands/ls.tsx +++ b/src/Terminal/commands/ls.tsx @@ -3,17 +3,15 @@ import createStyles from "@mui/styles/createStyles"; import makeStyles from "@mui/styles/makeStyles"; import { toString } from "lodash"; import React from "react"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import { BaseServer } from "../../Server/BaseServer"; import { evaluateDirectoryPath, getFirstParentDirectory, isValidDirectoryPath } from "../DirectoryHelpers"; -import { IRouter } from "../../ui/Router"; -import { ITerminal } from "../ITerminal"; +import { Router } from "../../ui/GameRoot"; +import { Terminal } from "../../Terminal"; import libarg from "arg"; import { showLiterature } from "../../Literature/LiteratureHelpers"; import { MessageFilenames, showMessage } from "../../Message/MessageHelpers"; -import { ScriptArg } from "../../Netscript/ScriptArg"; -export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server: BaseServer, args: ScriptArg[]): void { +export function ls(args: (string | number | boolean)[], server: BaseServer): void { interface LSFlags { ["-l"]: boolean; ["--grep"]: string; @@ -37,7 +35,7 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server const numArgs = args.length; function incorrectUsage(): void { - terminal.error("Incorrect usage of ls command. Usage: ls [dir] [-l] [-g, --grep pattern]"); + Terminal.error("Incorrect usage of ls command. Usage: ls [dir] [-l] [-g, --grep pattern]"); } if (numArgs > 4) { @@ -45,14 +43,14 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server } // Directory path - let prefix = terminal.cwd(); + let prefix = Terminal.cwd(); if (!prefix.endsWith("/")) { prefix += "/"; } // If first arg doesn't contain a - it must be the file/folder const dir = args[0] && typeof args[0] == "string" && !args[0].startsWith("-") ? args[0] : ""; - const newPath = evaluateDirectoryPath(dir + "", terminal.cwd()); + const newPath = evaluateDirectoryPath(dir + "", Terminal.cwd()); prefix = newPath || ""; if (!prefix.endsWith("/")) { prefix += "/"; @@ -107,12 +105,11 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server } // Get all of the programs and scripts on the machine into one temporary array - const s = player.getCurrentServer(); - for (const program of s.programs) handleFn(program, allPrograms); - for (const script of s.scripts) handleFn(script.filename, allScripts); - for (const txt of s.textFiles) handleFn(txt.fn, allTextFiles); - for (const contract of s.contracts) handleFn(contract.fn, allContracts); - for (const msgOrLit of s.messages) handleFn(msgOrLit, allMessages); + for (const program of server.programs) handleFn(program, allPrograms); + for (const script of server.scripts) handleFn(script.filename, allScripts); + for (const txt of server.textFiles) handleFn(txt.fn, allTextFiles); + for (const contract of server.contracts) handleFn(contract.fn, allContracts); + for (const msgOrLit of server.messages) handleFn(msgOrLit, allMessages); // Sort the files/folders alphabetically then print each allPrograms.sort(); @@ -149,13 +146,13 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server rowSplitArray = rowSplitArray.filter((x) => !!x[0]); function onScriptLinkClick(filename: string): void { - if (player.getCurrentServer().hostname !== hostname) { - return terminal.error(`File is not on this server, connect to ${hostname} and try again`); + if (!server.isConnectedTo) { + return Terminal.error(`File is not on this server, connect to ${hostname} and try again`); } if (filename.startsWith("/")) filename = filename.slice(1); - const filepath = terminal.getFilepath(`${prefix}${filename}`); - const code = toString(terminal.getScript(player, filepath)?.code); - router.toScriptEditor({ [filepath]: code }); + const filepath = Terminal.getFilepath(`${prefix}${filename}`); + const code = toString(Terminal.getScript(filepath)?.code); + Router.toScriptEditor({ [filepath]: code }); } return ( @@ -193,11 +190,11 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server rowSplitArray = rowSplitArray.filter((x) => !!x[0]); function onMessageLinkClick(filename: string): void { - if (player.getCurrentServer().hostname !== hostname) { - return terminal.error(`File is not on this server, connect to ${hostname} and try again`); + if (!server.isConnectedTo) { + return Terminal.error(`File is not on this server, connect to ${hostname} and try again`); } if (filename.startsWith("/")) filename = filename.slice(1); - const filepath = terminal.getFilepath(`${prefix}${filename}`); + const filepath = Terminal.getFilepath(`${prefix}${filename}`); if (filepath.endsWith(".lit")) { showLiterature(filepath); @@ -254,16 +251,16 @@ export function ls(terminal: ITerminal, router: IRouter, player: IPlayer, server switch (group.type) { case FileType.Folder: - terminal.printRaw({row}); + Terminal.printRaw({row}); break; case FileType.Script: - terminal.printRaw(); + Terminal.printRaw(); break; case FileType.Message: - terminal.printRaw(); + Terminal.printRaw(); break; default: - terminal.print(row); + Terminal.print(row); } } } diff --git a/src/Terminal/commands/lscpu.ts b/src/Terminal/commands/lscpu.ts index 8eba1239e..096793249 100644 --- a/src/Terminal/commands/lscpu.ts +++ b/src/Terminal/commands/lscpu.ts @@ -1,7 +1,6 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { BaseServer } from "../../Server/BaseServer"; -export function lscpu(terminal: ITerminal, router: IRouter, player: IPlayer): void { - terminal.print(player.getCurrentServer().cpuCores + " Core(s)"); +export function lscpu(_args: (string | number | boolean)[], server: BaseServer): void { + Terminal.print(server.cpuCores + " Core(s)"); } diff --git a/src/Terminal/commands/mem.ts b/src/Terminal/commands/mem.ts index b8acb448a..17593096d 100644 --- a/src/Terminal/commands/mem.ts +++ b/src/Terminal/commands/mem.ts @@ -1,20 +1,11 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; import { numeralWrapper } from "../../ui/numeralFormat"; import { Settings } from "../../Settings/Settings"; -export function mem( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function mem(args: (string | number | boolean)[]): void { try { if (args.length !== 1 && args.length !== 3) { - terminal.error("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]"); + Terminal.error("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]"); return; } @@ -23,36 +14,36 @@ export function mem( if (args.length === 3 && args[1] === "-t") { numThreads = Math.round(parseInt(args[2] + "")); if (isNaN(numThreads) || numThreads < 1) { - terminal.error("Invalid number of threads specified. Number of threads must be greater than 1"); + Terminal.error("Invalid number of threads specified. Number of threads must be greater than 1"); return; } } - const script = terminal.getScript(player, scriptName); + const script = Terminal.getScript(scriptName); if (script == null) { - terminal.error("mem failed. No such script exists!"); + Terminal.error("mem failed. No such script exists!"); return; } const ramUsage = script.ramUsage * numThreads; - terminal.print( + Terminal.print( `This script requires ${numeralWrapper.formatRAM(ramUsage)} of RAM to run for ${numThreads} thread(s)`, ); const verboseEntries = script.ramUsageEntries?.sort((a, b) => b.cost - a.cost) ?? []; const padding = Settings.UseIEC60027_2 ? 9 : 8; for (const entry of verboseEntries) { - terminal.print( + Terminal.print( `${numeralWrapper.formatRAM(entry.cost * numThreads).padStart(padding)} | ${entry.name} (${entry.type})`, ); } if (ramUsage > 0 && verboseEntries.length === 0) { // Let's warn the user that he might need to save his script again to generate the detailed entries - terminal.warn("You might have to open & save this script to see the detailed RAM usage information."); + Terminal.warn("You might have to open & save this script to see the detailed RAM usage information."); } } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/mv.ts b/src/Terminal/commands/mv.ts index f7f04ad94..44e07fcd9 100644 --- a/src/Terminal/commands/mv.ts +++ b/src/Terminal/commands/mv.ts @@ -1,21 +1,13 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { isScriptFilename } from "../../Script/isScriptFilename"; import { TextFile } from "../../TextFile"; import { Script } from "../../Script/Script"; import { getDestinationFilepath, areFilesEqual } from "../DirectoryHelpers"; -export function mv( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function mv(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 2) { - terminal.error(`Incorrect number of arguments. Usage: mv [src] [dest]`); + Terminal.error(`Incorrect number of arguments. Usage: mv [src] [dest]`); return; } @@ -24,28 +16,28 @@ export function mv( const t_dest = args[1] + ""; if (!isScriptFilename(source) && !source.endsWith(".txt")) { - terminal.error(`'mv' can only be used on scripts and text files (.txt)`); + Terminal.error(`'mv' can only be used on scripts and text files (.txt)`); return; } - const srcFile = terminal.getFile(player, source); + const srcFile = Terminal.getFile(source); if (srcFile == null) { - terminal.error(`Source file ${source} does not exist`); + Terminal.error(`Source file ${source} does not exist`); return; } - const sourcePath = terminal.getFilepath(source); + const sourcePath = Terminal.getFilepath(source); // Get the destination based on the source file and the current directory - const dest = getDestinationFilepath(t_dest, source, terminal.cwd()); + const dest = getDestinationFilepath(t_dest, source, Terminal.cwd()); if (dest === null) { - terminal.error("error parsing dst file"); + Terminal.error("error parsing dst file"); return; } - const destFile = terminal.getFile(player, dest); - const destPath = terminal.getFilepath(dest); + const destFile = Terminal.getFile(dest); + const destPath = Terminal.getFilepath(dest); if (areFilesEqual(sourcePath, destPath)) { - terminal.error(`Source and destination files are the same file`); + Terminal.error(`Source and destination files are the same file`); return; } @@ -54,13 +46,13 @@ export function mv( if (isScriptFilename(source)) { const script = srcFile as Script; if (!isScriptFilename(destPath)) { - terminal.error(`Source and destination files must have the same type`); + Terminal.error(`Source and destination files must have the same type`); return; } // Command doesnt work if script is running if (server.isRunning(sourcePath)) { - terminal.error(`Cannot use 'mv' on a script that is running`); + Terminal.error(`Cannot use 'mv' on a script that is running`); return; } @@ -69,16 +61,16 @@ export function mv( // Command doesnt work if script is running if (server.isRunning(destPath)) { - terminal.error(`Cannot use 'mv' on a script that is running`); + Terminal.error(`Cannot use 'mv' on a script that is running`); return; } const status = server.removeFile(destPath); if (!status.res) { - terminal.error(`Something went wrong...please contact game dev (probably a bug)`); + Terminal.error(`Something went wrong...please contact game dev (probably a bug)`); return; } else { - terminal.print("Warning: The destination file was overwritten"); + Terminal.print("Warning: The destination file was overwritten"); } } @@ -86,7 +78,7 @@ export function mv( } else if (srcFile instanceof TextFile) { const textFile = srcFile; if (!dest.endsWith(".txt")) { - terminal.error(`Source and destination files must have the same type`); + Terminal.error(`Source and destination files must have the same type`); return; } @@ -94,16 +86,16 @@ export function mv( // Already exists, will be overwritten, so we'll delete it const status = server.removeFile(destPath); if (!status.res) { - terminal.error(`Something went wrong...please contact game dev (probably a bug)`); + Terminal.error(`Something went wrong...please contact game dev (probably a bug)`); return; } else { - terminal.print("Warning: The destination file was overwritten"); + Terminal.print("Warning: The destination file was overwritten"); } } textFile.fn = destPath; } } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/nano.ts b/src/Terminal/commands/nano.ts index ed455923e..9e5718482 100644 --- a/src/Terminal/commands/nano.ts +++ b/src/Terminal/commands/nano.ts @@ -1,16 +1,7 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import { BaseServer } from "../../Server/BaseServer"; import { commonEditor } from "./common/editor"; -export function nano( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { - return commonEditor("nano", { terminal, router, player, server, args }); +export function nano(args: (string | number | boolean)[], server: BaseServer): void { + return commonEditor("nano", { args, server }); } diff --git a/src/Terminal/commands/ps.ts b/src/Terminal/commands/ps.ts index c213f7777..a4e226bb7 100644 --- a/src/Terminal/commands/ps.ts +++ b/src/Terminal/commands/ps.ts @@ -1,16 +1,8 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import * as libarg from "arg"; -export function ps( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function ps(args: (string | number | boolean)[], server: BaseServer): void { let flags; try { flags = libarg( @@ -22,7 +14,7 @@ export function ps( ); } catch (e) { // catch passing only -g / --grep with no string to use as the search - terminal.error("Incorrect usage of ps command. Usage: ps [-g, --grep pattern]"); + Terminal.error("Incorrect usage of ps command. Usage: ps [-g, --grep pattern]"); return; } const pattern = flags["--grep"]; @@ -35,7 +27,7 @@ export function ps( for (let j = 0; j < rsObj.args.length; ++j) { res += " " + rsObj.args[j].toString(); } - terminal.print(res); + Terminal.print(res); } } if (args.length === 0) { @@ -45,7 +37,7 @@ export function ps( for (let j = 0; j < rsObj.args.length; ++j) { res += " " + rsObj.args[j].toString(); } - terminal.print(res); + Terminal.print(res); } } } diff --git a/src/Terminal/commands/rm.ts b/src/Terminal/commands/rm.ts index dc4b5e126..bc8b956ee 100644 --- a/src/Terminal/commands/rm.ts +++ b/src/Terminal/commands/rm.ts @@ -1,18 +1,10 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { IReturnStatus } from "../../types"; -export function rm( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function rm(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 1) { - terminal.error("Incorrect number of arguments. Usage: rm [program/script]"); + Terminal.error("Incorrect number of arguments. Usage: rm [program/script]"); return; } @@ -23,7 +15,7 @@ export function rm( msg: "", }; try { - delTarget = terminal.getFilepath(args[0] + ""); + delTarget = Terminal.getFilepath(args[0] + ""); status = server.removeFile(delTarget); } catch (err) { status = { @@ -33,6 +25,6 @@ export function rm( } if (!status.res && status.msg) { - terminal.error(status.msg); + Terminal.error(status.msg); } } diff --git a/src/Terminal/commands/run.ts b/src/Terminal/commands/run.ts index 594170cf6..b551d1453 100644 --- a/src/Terminal/commands/run.ts +++ b/src/Terminal/commands/run.ts @@ -1,31 +1,26 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { isScriptFilename } from "../../Script/isScriptFilename"; import { runScript } from "./runScript"; import { runProgram } from "./runProgram"; export function run( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { // Run a program or a script if (args.length < 1) { - terminal.error("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]..."); + Terminal.error("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]..."); } else { const executableName = args[0] + ""; // Check if its a script or just a program/executable if (isScriptFilename(executableName)) { - runScript(terminal, router, player, server, args); + runScript(args, server); } else if (executableName.endsWith(".cct")) { - terminal.runContract(player, executableName); + Terminal.runContract(executableName); } else { - runProgram(terminal, router, player, server, args); + runProgram(args, server); } } } diff --git a/src/Terminal/commands/runProgram.ts b/src/Terminal/commands/runProgram.ts index 5f48029e6..cd4ae1dd5 100644 --- a/src/Terminal/commands/runProgram.ts +++ b/src/Terminal/commands/runProgram.ts @@ -1,16 +1,9 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { BaseServer } from "../../Server/BaseServer"; import { Programs } from "../../Programs/Programs"; -export function runProgram( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function runProgram(args: (string | number | boolean)[], server: BaseServer): void { if (args.length < 1) { return; } @@ -19,11 +12,9 @@ export function runProgram( // display an error message const programName = args[0] + ""; - if (!player.hasProgram(programName)) { - terminal.error( - `No such (exe, script, js, ns, or cct) file! (Only programs that exist on your home computer or scripts on ${ - player.getCurrentServer().hostname - } can be run)`, + if (!Player.hasProgram(programName)) { + Terminal.error( + `No such (exe, script, js, ns, or cct) file! (Only programs that exist on your home computer or scripts on ${server.hostname} can be run)`, ); return; } @@ -35,15 +26,12 @@ export function runProgram( for (const program of Object.values(Programs)) { if (program.name.toLocaleLowerCase() === programName.toLocaleLowerCase()) { program.run( - router, - terminal, - player, - server, args.slice(1).map((arg) => arg + ""), + server, ); return; } } - terminal.error("Invalid executable. Cannot be run"); + Terminal.error("Invalid executable. Cannot be run"); } diff --git a/src/Terminal/commands/runScript.ts b/src/Terminal/commands/runScript.ts index baa18e589..90e8b206c 100644 --- a/src/Terminal/commands/runScript.ts +++ b/src/Terminal/commands/runScript.ts @@ -1,6 +1,4 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { LogBoxEvents } from "../../ui/React/LogBoxManager"; import { startWorkerScript } from "../../NetscriptWorker"; @@ -10,20 +8,17 @@ import * as libarg from "arg"; import { numeralWrapper } from "../../ui/numeralFormat"; export function runScript( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, commandArgs: (string | number | boolean)[], + server: BaseServer, ): void { if (commandArgs.length < 1) { - terminal.error( + Terminal.error( `Bug encountered with Terminal.runScript(). Command array has a length of less than 1: ${commandArgs}`, ); return; } - const scriptName = terminal.getFilepath(commandArgs[0] + ""); + const scriptName = Terminal.getFilepath(commandArgs[0] + ""); const runArgs = { "--tail": Boolean, "-t": Number }; const flags = libarg(runArgs, { @@ -33,7 +28,7 @@ export function runScript( const threadFlag = Math.round(parseFloat(flags["-t"])); const tailFlag = flags["--tail"] === true; if (flags["-t"] !== undefined && (threadFlag < 0 || isNaN(threadFlag))) { - terminal.error("Invalid number of threads specified. Number of threads must be greater than 0"); + Terminal.error("Invalid number of threads specified. Number of threads must be greater than 0"); return; } const numThreads = !isNaN(threadFlag) && threadFlag > 0 ? threadFlag : 1; @@ -41,7 +36,7 @@ export function runScript( // Check if this script is already running if (findRunningScript(scriptName, args, server) != null) { - terminal.error( + Terminal.error( "This script is already running with the same args. Cannot run multiple instances with the same args", ); return; @@ -54,17 +49,17 @@ export function runScript( } // Check for admin rights and that there is enough RAM availble to run const script = server.scripts[i]; - script.server = player.getCurrentServer().hostname; + script.server = server.hostname; const ramUsage = script.ramUsage * numThreads; const ramAvailable = server.maxRam - server.ramUsed; if (!server.hasAdminRights) { - terminal.error("Need root access to run script"); + Terminal.error("Need root access to run script"); return; } if (ramUsage > ramAvailable + 0.001) { - terminal.error( + Terminal.error( "This machine does not have enough RAM to run this script" + (numThreads === 1 ? "" : ` with ${numThreads} threads`) + `. Script requires ${numeralWrapper.formatRAM(ramUsage)} of RAM`, @@ -78,11 +73,11 @@ export function runScript( const success = startWorkerScript(runningScript, server); if (!success) { - terminal.error(`Failed to start script`); + Terminal.error(`Failed to start script`); return; } - terminal.print( + Terminal.print( `Running script with ${numThreads} thread(s), pid ${runningScript.pid} and args: ${JSON.stringify(args)}.`, ); if (tailFlag) { @@ -91,5 +86,5 @@ export function runScript( return; } - terminal.error("No such script"); + Terminal.error("No such script"); } diff --git a/src/Terminal/commands/scan.ts b/src/Terminal/commands/scan.ts index da5c262a4..f6c61093a 100644 --- a/src/Terminal/commands/scan.ts +++ b/src/Terminal/commands/scan.ts @@ -1,23 +1,14 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { getServerOnNetwork } from "../../Server/ServerHelpers"; -export function scan( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function scan(args: (string | number | boolean)[], currServ: BaseServer): void { if (args.length !== 0) { - terminal.error("Incorrect usage of scan command. Usage: scan"); + Terminal.error("Incorrect usage of scan command. Usage: scan"); return; } // Displays available network connections using TCP - const currServ = player.getCurrentServer(); const servers = currServ.serversOnNetwork.map((_, i) => { const server = getServerOnNetwork(currServ, i); if (server === null) throw new Error("Server should not be null"); @@ -41,6 +32,6 @@ export function scan( entry += server.ip; entry += " ".repeat(maxIP - server.ip.length + 1); entry += server.hasRoot; - terminal.print(entry); + Terminal.print(entry); } } diff --git a/src/Terminal/commands/scananalyze.ts b/src/Terminal/commands/scananalyze.ts index f30c6dc9f..d9811909b 100644 --- a/src/Terminal/commands/scananalyze.ts +++ b/src/Terminal/commands/scananalyze.ts @@ -1,22 +1,14 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { Programs } from "../../Programs/Programs"; -export function scananalyze( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function scananalyze(args: (string | number | boolean)[]): void { if (args.length === 0) { - terminal.executeScanAnalyzeCommand(player, 1); + Terminal.executeScanAnalyzeCommand(); } else { // # of args must be 2 or 3 if (args.length > 2) { - terminal.error("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]"); + Terminal.error("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]"); return; } let all = false; @@ -27,19 +19,19 @@ export function scananalyze( const depth = parseInt(args[0] + ""); if (isNaN(depth) || depth < 0) { - terminal.error("Incorrect usage of scan-analyze command. depth argument must be positive numeric"); + Terminal.error("Incorrect usage of scan-analyze command. depth argument must be positive numeric"); return; } - if (depth > 3 && !player.hasProgram(Programs.DeepscanV1.name) && !player.hasProgram(Programs.DeepscanV2.name)) { - terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 3"); + if (depth > 3 && !Player.hasProgram(Programs.DeepscanV1.name) && !Player.hasProgram(Programs.DeepscanV2.name)) { + Terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 3"); return; - } else if (depth > 5 && !player.hasProgram(Programs.DeepscanV2.name)) { - terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 5"); + } else if (depth > 5 && !Player.hasProgram(Programs.DeepscanV2.name)) { + Terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 5"); return; } else if (depth > 10) { - terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 10"); + Terminal.error("You cannot scan-analyze with that high of a depth. Maximum depth is 10"); return; } - terminal.executeScanAnalyzeCommand(player, depth, all); + Terminal.executeScanAnalyzeCommand(depth, all); } } diff --git a/src/Terminal/commands/scp.ts b/src/Terminal/commands/scp.ts index d5def4d68..bef747545 100644 --- a/src/Terminal/commands/scp.ts +++ b/src/Terminal/commands/scp.ts @@ -1,111 +1,73 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { GetServer } from "../../Server/AllServers"; import { isScriptFilename } from "../../Script/isScriptFilename"; -export function scp( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function scp(args: (string | number | boolean)[], server: BaseServer): void { try { if (args.length !== 2) { - terminal.error("Incorrect usage of scp command. Usage: scp [file] [destination hostname]"); + Terminal.error("Incorrect usage of scp command. Usage: scp [file] [destination hostname]"); return; } - const scriptname = terminal.getFilepath(args[0] + ""); + const scriptname = Terminal.getFilepath(args[0] + ""); if (!scriptname.endsWith(".lit") && !isScriptFilename(scriptname) && !scriptname.endsWith(".txt")) { - terminal.error("scp only works for scripts, text files (.txt), and literature files (.lit)"); + Terminal.error("scp only works for scripts, text files (.txt), and literature files (.lit)"); return; } const destServer = GetServer(args[1] + ""); if (destServer == null) { - terminal.error(`Invalid destination. ${args[1]} not found`); + Terminal.error(`Invalid destination. ${args[1]} not found`); return; } // Scp for lit files if (scriptname.endsWith(".lit")) { - let found = false; - for (let i = 0; i < server.messages.length; ++i) { - if (server.messages[i] == scriptname) { - found = true; - break; - } - } + if (!server.messages.includes(scriptname)) return Terminal.error("No such file exists!"); - if (!found) { - return terminal.error("No such file exists!"); - } - - for (let i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - terminal.print(scriptname + " copied over to " + destServer.hostname); - return; // Already exists - } - } - destServer.messages.push(scriptname); - return terminal.print(scriptname + " copied over to " + destServer.hostname); + const onDestServer = destServer.messages.includes(scriptname); + if (!onDestServer) destServer.messages.push(scriptname); + return Terminal.print(`${scriptname} ${onDestServer ? "was already on" : "copied to"} ${destServer.hostname}`); } // Scp for txt files if (scriptname.endsWith(".txt")) { - let txtFile = null; - for (let i = 0; i < server.textFiles.length; ++i) { - if (server.textFiles[i].fn === scriptname) { - txtFile = server.textFiles[i]; - break; - } - } - - if (txtFile === null) { - return terminal.error("No such file exists!"); - } + const txtFile = server.textFiles.find((txtFile) => txtFile.fn === scriptname); + if (!txtFile) return Terminal.error("No such file exists!"); const tRes = destServer.writeToTextFile(txtFile.fn, txtFile.text); if (!tRes.success) { - terminal.error("scp failed"); + Terminal.error("scp failed"); return; } if (tRes.overwritten) { - terminal.print(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwriten`); - terminal.print(`${scriptname} overwritten on ${destServer.hostname}`); + Terminal.print(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwriten`); + Terminal.print(`${scriptname} overwritten on ${destServer.hostname}`); return; } - terminal.print(`${scriptname} copied over to ${destServer.hostname}`); + Terminal.print(`${scriptname} copied over to ${destServer.hostname}`); return; } // Get the current script - let sourceScript = null; - for (let i = 0; i < server.scripts.length; ++i) { - if (scriptname == server.scripts[i].filename) { - sourceScript = server.scripts[i]; - break; - } - } - if (sourceScript == null) { - terminal.error("scp failed. No such script exists"); + const sourceScript = server.scripts.find((script) => script.filename === scriptname); + if (!sourceScript) { + Terminal.error("scp failed. No such script exists"); return; } const sRes = destServer.writeToScriptFile(scriptname, sourceScript.code); if (!sRes.success) { - terminal.error(`scp failed`); + Terminal.error(`scp failed`); return; } if (sRes.overwritten) { - terminal.print(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwritten`); - terminal.print(`${scriptname} overwritten on ${destServer.hostname}`); + Terminal.print(`WARNING: ${scriptname} already exists on ${destServer.hostname} and will be overwritten`); + Terminal.print(`${scriptname} overwritten on ${destServer.hostname}`); return; } - terminal.print(`${scriptname} copied over to ${destServer.hostname}`); + Terminal.print(`${scriptname} copied over to ${destServer.hostname}`); } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/sudov.ts b/src/Terminal/commands/sudov.ts index d5cfc3394..f80bec452 100644 --- a/src/Terminal/commands/sudov.ts +++ b/src/Terminal/commands/sudov.ts @@ -1,23 +1,18 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; export function sudov( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { if (args.length !== 0) { - terminal.error("Incorrect number of arguments. Usage: sudov"); + Terminal.error("Incorrect number of arguments. Usage: sudov"); return; } if (server.hasAdminRights) { - terminal.print("You have ROOT access to this machine"); + Terminal.print("You have ROOT access to this machine"); } else { - terminal.print("You do NOT have root access to this machine"); + Terminal.print("You do NOT have root access to this machine"); } } diff --git a/src/Terminal/commands/tail.ts b/src/Terminal/commands/tail.ts index d1101e76a..834b433ce 100644 --- a/src/Terminal/commands/tail.ts +++ b/src/Terminal/commands/tail.ts @@ -1,26 +1,18 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { findRunningScriptByPid } from "../../Script/ScriptHelpers"; import { isScriptFilename, validScriptExtensions } from "../../Script/isScriptFilename"; import { compareArrays } from "../../utils/helpers/compareArrays"; import { LogBoxEvents } from "../../ui/React/LogBoxManager"; -export function tail( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - commandArray: (string | number | boolean)[], -): void { +export function tail(commandArray: (string | number | boolean)[], server: BaseServer): void { try { if (commandArray.length < 1) { - terminal.error("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]..."); + Terminal.error("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]..."); } else if (typeof commandArray[0] === "string") { - const scriptName = terminal.getFilepath(commandArray[0]); + const scriptName = Terminal.getFilepath(commandArray[0]); if (!isScriptFilename(scriptName)) { - terminal.error(`tail can only be called on ${validScriptExtensions.join(", ")} files, or by PID`); + Terminal.error(`tail can only be called on ${validScriptExtensions.join(", ")} files, or by PID`); return; } @@ -59,23 +51,23 @@ export function tail( // otherwise lists all possible conflicting choices. if (candidates.length > 1) { - terminal.error("Found several potential candidates:"); - for (const candidate of candidates) terminal.error(`${candidate.filename} ${candidate.args.join(" ")}`); - terminal.error("Script arguments need to be specified."); + Terminal.error("Found several potential candidates:"); + for (const candidate of candidates) Terminal.error(`${candidate.filename} ${candidate.args.join(" ")}`); + Terminal.error("Script arguments need to be specified."); return; } // if there's no candidate then we just don't know. - terminal.error(`No script named ${scriptName} is running on the server`); + Terminal.error(`No script named ${scriptName} is running on the server`); } else if (typeof commandArray[0] === "number") { const runningScript = findRunningScriptByPid(commandArray[0], server); if (runningScript == null) { - terminal.error(`No script with PID ${commandArray[0]} is running on the server`); + Terminal.error(`No script with PID ${commandArray[0]} is running on the server`); return; } LogBoxEvents.emit(runningScript); } } catch (e) { - terminal.error(e + ""); + Terminal.error(e + ""); } } diff --git a/src/Terminal/commands/top.ts b/src/Terminal/commands/top.ts index 283951f44..a57de4779 100644 --- a/src/Terminal/commands/top.ts +++ b/src/Terminal/commands/top.ts @@ -1,19 +1,14 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { getRamUsageFromRunningScript } from "../../Script/RunningScriptHelpers"; import { numeralWrapper } from "../../ui/numeralFormat"; export function top( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { if (args.length !== 0) { - terminal.error("Incorrect usage of top command. Usage: top"); + Terminal.error("Incorrect usage of top command. Usage: top"); return; } @@ -33,7 +28,7 @@ export function top( const headers = `${scriptTxt}${spacesAfterScriptTxt}${pidTxt}${spacesAfterPidTxt}${threadsTxt}${spacesAfterThreadsTxt}${ramTxt}`; - terminal.print(headers); + Terminal.print(headers); const currRunningScripts = server.runningScripts; // Iterate through scripts on current server @@ -58,6 +53,6 @@ export function top( const entry = [script.filename, spacesScript, script.pid, spacesPid, script.threads, spacesThread, ramUsage].join( "", ); - terminal.print(entry); + Terminal.print(entry); } } diff --git a/src/Terminal/commands/unalias.ts b/src/Terminal/commands/unalias.ts index 48dc3e8d6..d2ebd5ada 100644 --- a/src/Terminal/commands/unalias.ts +++ b/src/Terminal/commands/unalias.ts @@ -1,22 +1,15 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; -import { BaseServer } from "../../Server/BaseServer"; +import { Terminal } from "../../Terminal"; import { removeAlias } from "../../Alias"; export function unalias( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], ): void { if (args.length !== 1) { - terminal.error("Incorrect usage of unalias name. Usage: unalias [alias]"); + Terminal.error("Incorrect usage of unalias name. Usage: unalias [alias]"); return; } else if (removeAlias(args[0] + "")) { - terminal.print(`Removed alias ${args[0]}`); + Terminal.print(`Removed alias ${args[0]}`); } else { - terminal.error(`No such alias exists: ${args[0]}`); + Terminal.error(`No such alias exists: ${args[0]}`); } } diff --git a/src/Terminal/commands/vim.ts b/src/Terminal/commands/vim.ts index 58cffba31..9ae834fb0 100644 --- a/src/Terminal/commands/vim.ts +++ b/src/Terminal/commands/vim.ts @@ -1,16 +1,7 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; import { BaseServer } from "../../Server/BaseServer"; import { commonEditor } from "./common/editor"; -export function vim( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { - return commonEditor("vim", { terminal, router, player, server, args }, { vim: true }); +export function vim(args: (string | number | boolean)[], server: BaseServer): void { + return commonEditor("vim", { args, server }, { vim: true }); } diff --git a/src/Terminal/commands/weaken.ts b/src/Terminal/commands/weaken.ts index 9586db7c0..0d2d56715 100644 --- a/src/Terminal/commands/weaken.ts +++ b/src/Terminal/commands/weaken.ts @@ -1,23 +1,16 @@ -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Player } from "../../Player"; import { BaseServer } from "../../Server/BaseServer"; import { Server } from "../../Server/Server"; -export function weaken( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, - args: (string | number | boolean)[], -): void { +export function weaken(args: (string | number | boolean)[], server: BaseServer): void { if (args.length !== 0) { - terminal.error("Incorrect usage of weaken command. Usage: weaken"); + Terminal.error("Incorrect usage of weaken command. Usage: weaken"); return; } if (!(server instanceof Server)) { - terminal.error( + Terminal.error( "Cannot weaken your own machines! You are currently connected to your home PC or one of your purchased servers", ); } @@ -25,20 +18,20 @@ export function weaken( // Hack the current PC (usually for money) // You can't weaken your home pc or servers you purchased if (normalServer.purchasedByPlayer) { - terminal.error( + Terminal.error( "Cannot weaken your own machines! You are currently connected to your home PC or one of your purchased servers", ); return; } if (!normalServer.hasAdminRights) { - terminal.error("You do not have admin rights for this machine! Cannot weaken"); + Terminal.error("You do not have admin rights for this machine! Cannot weaken"); return; } - if (normalServer.requiredHackingSkill > player.skills.hacking) { - terminal.error( + if (normalServer.requiredHackingSkill > Player.skills.hacking) { + Terminal.error( "Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill", ); return; } - terminal.startWeaken(player); + Terminal.startWeaken(); } diff --git a/src/Terminal/commands/wget.ts b/src/Terminal/commands/wget.ts index 77e3444bc..afdcb0fdd 100644 --- a/src/Terminal/commands/wget.ts +++ b/src/Terminal/commands/wget.ts @@ -1,27 +1,22 @@ import $ from "jquery"; -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; import { BaseServer } from "../../Server/BaseServer"; import { isScriptFilename } from "../../Script/isScriptFilename"; export function wget( - terminal: ITerminal, - router: IRouter, - player: IPlayer, - server: BaseServer, args: (string | number | boolean)[], + server: BaseServer, ): void { if (args.length !== 2) { - terminal.error("Incorrect usage of wget command. Usage: wget [url] [target file]"); + Terminal.error("Incorrect usage of wget command. Usage: wget [url] [target file]"); return; } const url = args[0] + ""; - const target = terminal.getFilepath(args[1] + ""); + const target = Terminal.getFilepath(args[1] + ""); if (!isScriptFilename(target) && !target.endsWith(".txt")) { - return terminal.error(`wget failed: Invalid target file. Target file must be script or text file`); + return Terminal.error(`wget failed: Invalid target file. Target file must be script or text file`); } $.get( url, @@ -33,15 +28,15 @@ export function wget( res = server.writeToTextFile(target, String(data)); } if (!res.success) { - return terminal.error("wget failed"); + return Terminal.error("wget failed"); } if (res.overwritten) { - return terminal.print(`wget successfully retrieved content and overwrote ${target}`); + return Terminal.print(`wget successfully retrieved content and overwrote ${target}`); } - return terminal.print(`wget successfully retrieved content to new file ${target}`); + return Terminal.print(`wget successfully retrieved content to new file ${target}`); }, "text", ).fail(function (e) { - return terminal.error("wget failed: " + JSON.stringify(e)); + return Terminal.error("wget failed: " + JSON.stringify(e)); }); } diff --git a/src/Terminal/ui/TerminalInput.tsx b/src/Terminal/ui/TerminalInput.tsx index 57f2cc38f..c4bc1b85d 100644 --- a/src/Terminal/ui/TerminalInput.tsx +++ b/src/Terminal/ui/TerminalInput.tsx @@ -8,9 +8,9 @@ import Popper from "@mui/material/Popper"; import TextField from "@mui/material/TextField"; import { KEY, KEYCODE } from "../../utils/helpers/keyCodes"; -import { ITerminal } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Terminal } from "../../Terminal"; +import { Router } from "../../ui/GameRoot"; +import { Player } from "../../Player"; import { determineAllPossibilitiesForTabCompletion } from "../determineAllPossibilitiesForTabCompletion"; import { tabCompletion } from "../tabCompletion"; import { Settings } from "../../Settings/Settings"; @@ -37,15 +37,10 @@ const useStyles = makeStyles((theme: Theme) => }), ); -interface IProps { - terminal: ITerminal; - router: IRouter; - player: IPlayer; -} // Save command in case we de-load this screen. let command = ""; -export function TerminalInput({ terminal, router, player }: IProps): React.ReactElement { +export function TerminalInput(): React.ReactElement { const terminalInput = useRef(null); const [value, setValue] = useState(command); @@ -54,9 +49,9 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React const classes = useStyles(); // If we have no data in the current terminal history, let's initialize it from the player save - if (terminal.commandHistory.length === 0 && player.terminalCommandHistory.length > 0) { - terminal.commandHistory = player.terminalCommandHistory; - terminal.commandHistoryIndex = terminal.commandHistory.length; + if (Terminal.commandHistory.length === 0 && Player.terminalCommandHistory.length > 0) { + Terminal.commandHistory = Player.terminalCommandHistory; + Terminal.commandHistoryIndex = Terminal.commandHistory.length; } // Need to run after state updates, for example if we need to move cursor @@ -183,9 +178,9 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React // Catch all key inputs and redirect them to the terminal. useEffect(() => { function keyDown(this: Document, event: KeyboardEvent): void { - if (terminal.contractOpen) return; - if (terminal.action !== null && event.key === KEY.C && event.ctrlKey) { - terminal.finishAction(router, player, true); + if (Terminal.contractOpen) return; + if (Terminal.action !== null && event.key === KEY.C && event.ctrlKey) { + Terminal.finishAction(true); return; } const ref = terminalInput.current; @@ -204,8 +199,8 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React // Run command. if (event.key === KEY.ENTER && value !== "") { event.preventDefault(); - terminal.print(`[${player.getCurrentServer().hostname} ~${terminal.cwd()}]> ${value}`); - terminal.executeCommands(router, player, value); + Terminal.print(`[${Player.getCurrentServer().hostname} ~${Terminal.cwd()}]> ${value}`); + Terminal.executeCommands(value); saveValue(""); return; } @@ -228,7 +223,7 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React if (index < -1) { index = 0; } - const allPos = await determineAllPossibilitiesForTabCompletion(player, copy, index, terminal.cwd()); + const allPos = await determineAllPossibilitiesForTabCompletion(Player, copy, index, Terminal.cwd()); if (allPos.length == 0) { return; } @@ -264,7 +259,7 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React // Clear screen. if (event.key === KEY.L && event.ctrlKey) { event.preventDefault(); - terminal.clear(); + Terminal.clear(); } // Select previous command. @@ -272,20 +267,20 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React if (Settings.EnableBashHotkeys) { event.preventDefault(); } - const i = terminal.commandHistoryIndex; - const len = terminal.commandHistory.length; + const i = Terminal.commandHistoryIndex; + const len = Terminal.commandHistory.length; if (len == 0) { return; } if (i < 0 || i > len) { - terminal.commandHistoryIndex = len; + Terminal.commandHistoryIndex = len; } if (i != 0) { - --terminal.commandHistoryIndex; + --Terminal.commandHistoryIndex; } - const prevCommand = terminal.commandHistory[terminal.commandHistoryIndex]; + const prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex]; saveValue(prevCommand); if (ref) { setTimeout(function () { @@ -299,23 +294,23 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React if (Settings.EnableBashHotkeys) { event.preventDefault(); } - const i = terminal.commandHistoryIndex; - const len = terminal.commandHistory.length; + const i = Terminal.commandHistoryIndex; + const len = Terminal.commandHistory.length; if (len == 0) { return; } if (i < 0 || i > len) { - terminal.commandHistoryIndex = len; + Terminal.commandHistoryIndex = len; } // Latest command, put nothing if (i == len || i == len - 1) { - terminal.commandHistoryIndex = len; + Terminal.commandHistoryIndex = len; saveValue(""); } else { - ++terminal.commandHistoryIndex; - const prevCommand = terminal.commandHistory[terminal.commandHistoryIndex]; + ++Terminal.commandHistoryIndex; + const prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex]; saveValue(prevCommand); } } @@ -324,7 +319,7 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React if (Settings.EnableBashHotkeys) { if (event.code === KEYCODE.C && event.ctrlKey && ref && ref.selectionStart === ref.selectionEnd) { event.preventDefault(); - terminal.print(`[${player.getCurrentServer().hostname} ~${terminal.cwd()}]> ${value}`); + Terminal.print(`[${Player.getCurrentServer().hostname} ~${Terminal.cwd()}]> ${value}`); modifyInput("clearall"); } @@ -389,9 +384,9 @@ export function TerminalInput({ terminal, router, player }: IProps): React.React <> - [{player.getCurrentServer().hostname} ~{terminal.cwd()}]>  + + [{Player.getCurrentServer().hostname} ~{Terminal.cwd()}]>  ), spellCheck: false, diff --git a/src/Terminal/ui/TerminalRoot.tsx b/src/Terminal/ui/TerminalRoot.tsx index ef1e99662..6eab48a5a 100644 --- a/src/Terminal/ui/TerminalRoot.tsx +++ b/src/Terminal/ui/TerminalRoot.tsx @@ -7,9 +7,8 @@ import { Theme } from "@mui/material/styles"; import makeStyles from "@mui/styles/makeStyles"; import createStyles from "@mui/styles/createStyles"; import Box from "@mui/material/Box"; -import { ITerminal, Output, Link, RawOutput } from "../ITerminal"; -import { IRouter } from "../../ui/Router"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Output, Link, RawOutput } from "../ITerminal"; +import { Terminal } from "../../Terminal"; import { TerminalInput } from "./TerminalInput"; import { TerminalEvents, TerminalClearEvents } from "../TerminalEvents"; import { BitFlumeModal } from "../../BitNode/ui/BitFlumeModal"; @@ -18,14 +17,10 @@ import { CodingContractModal } from "../../ui/React/CodingContractModal"; import _ from "lodash"; import { ANSIITypography } from "../../ui/React/ANSIITypography"; -interface IActionTimerProps { - terminal: ITerminal; -} - -function ActionTimer({ terminal }: IActionTimerProps): React.ReactElement { +function ActionTimer(): React.ReactElement { return ( - {terminal.getProgressText()} + {Terminal.getProgressText()} ); } @@ -47,13 +42,7 @@ const useStyles = makeStyles((theme: Theme) => }), ); -interface IProps { - terminal: ITerminal; - router: IRouter; - player: IPlayer; -} - -export function TerminalRoot({ terminal, router, player }: IProps): React.ReactElement { +export function TerminalRoot(): React.ReactElement { const scrollHook = useRef(null); const setRerender = useState(0)[1]; const [key, setKey] = useState(0); @@ -108,7 +97,7 @@ export function TerminalRoot({ terminal, router, player }: IProps): React.ReactE <> - {terminal.outputHistory.map((item, i) => ( + {Terminal.outputHistory.map((item, i) => ( {item instanceof Output && } {item instanceof RawOutput && ( @@ -123,7 +112,7 @@ export function TerminalRoot({ terminal, router, player }: IProps): React.ReactE classes={{ root: classes.preformatted }} color={"secondary"} paragraph={false} - onClick={() => terminal.connectToServer(player, item.hostname)} + onClick={() => Terminal.connectToServer(item.hostname)} > {item.hostname} @@ -134,16 +123,16 @@ export function TerminalRoot({ terminal, router, player }: IProps): React.ReactE ))} - {terminal.action !== null && ( + {Terminal.action !== null && ( - {" "} + {" "} )}
    - + diff --git a/src/Themes/ui/ThemeBrowser.tsx b/src/Themes/ui/ThemeBrowser.tsx index e39b28a52..e8cee63c7 100644 --- a/src/Themes/ui/ThemeBrowser.tsx +++ b/src/Themes/ui/ThemeBrowser.tsx @@ -5,7 +5,6 @@ import { ThemeEvents } from "./Theme"; import { Settings } from "../../Settings/Settings"; import { getPredefinedThemes, IPredefinedTheme } from "../Themes"; import { Box, ButtonGroup, Button } from "@mui/material"; -import { IRouter } from "../../ui/Router"; import { ThemeEditorButton } from "./ThemeEditorButton"; import { StyleEditorButton } from "./StyleEditorButton"; import { ThemeEntry } from "./ThemeEntry"; @@ -13,14 +12,10 @@ import { ThemeCollaborate } from "./ThemeCollaborate"; import { Modal } from "../../ui/React/Modal"; import { SnackbarEvents, ToastVariant } from "../../ui/React/Snackbar"; -interface IProps { - router: IRouter; -} - // Everything dies when the theme gets reloaded, so we'll keep the current scroll to not jump around. let previousScrollY = 0; -export function ThemeBrowser({ router }: IProps): React.ReactElement { +export function ThemeBrowser(): React.ReactElement { const [modalOpen, setModalOpen] = useState(false); const [modalImageSrc, setModalImageSrc] = useState(); const predefinedThemes = getPredefinedThemes(); @@ -80,7 +75,7 @@ export function ThemeBrowser({ router }: IProps): React.ReactElement { - + {themes} diff --git a/src/Themes/ui/ThemeEditorButton.tsx b/src/Themes/ui/ThemeEditorButton.tsx index e2509802f..7e03de676 100644 --- a/src/Themes/ui/ThemeEditorButton.tsx +++ b/src/Themes/ui/ThemeEditorButton.tsx @@ -2,14 +2,9 @@ import React, { useState } from "react"; import Button from "@mui/material/Button"; import Tooltip from "@mui/material/Tooltip"; import { ThemeEditorModal } from "./ThemeEditorModal"; -import { IRouter } from "../../ui/Router"; import ColorizeIcon from "@mui/icons-material/Colorize"; -interface IProps { - router: IRouter; -} - -export function ThemeEditorButton({ router }: IProps): React.ReactElement { +export function ThemeEditorButton(): React.ReactElement { const [themeEditorOpen, setThemeEditorOpen] = useState(false); return ( <> @@ -18,7 +13,7 @@ export function ThemeEditorButton({ router }: IProps): React.ReactElement { Theme Editor - setThemeEditorOpen(false)} router={router} /> + setThemeEditorOpen(false)} /> ); } diff --git a/src/Themes/ui/ThemeEditorModal.tsx b/src/Themes/ui/ThemeEditorModal.tsx index 11d5b57ff..f8fd3d823 100644 --- a/src/Themes/ui/ThemeEditorModal.tsx +++ b/src/Themes/ui/ThemeEditorModal.tsx @@ -15,13 +15,12 @@ import { ThemeEvents } from "./Theme"; import { Settings, defaultSettings } from "../../Settings/Settings"; import { defaultTheme } from "../Themes"; import { UserInterfaceTheme } from "../../ScriptEditor/NetscriptDefinitions"; -import { IRouter } from "../../ui/Router"; +import { Router } from "../../ui/GameRoot"; import { ThemeCollaborate } from "./ThemeCollaborate"; interface IProps { open: boolean; onClose: () => void; - router: IRouter; } interface IColorEditorProps { @@ -381,7 +380,7 @@ export function ThemeEditorModal(props: IProps): React.ReactElement { - diff --git a/src/Work/ClassWork.tsx b/src/Work/ClassWork.tsx index 1a5d7dc63..3690978d6 100644 --- a/src/Work/ClassWork.tsx +++ b/src/Work/ClassWork.tsx @@ -6,7 +6,7 @@ import { numeralWrapper } from "../ui/numeralFormat"; import { dialogBoxCreate } from "../ui/React/DialogBox"; import { Money } from "../ui/React/Money"; import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { calculateClassEarnings as calculateClassEarningsRate } from "./formulas/Class"; import { Work, WorkType } from "./Work"; import { applyWorkStats, newWorkStats, sumWorkStats, WorkStats } from "./WorkStats"; @@ -146,14 +146,14 @@ export class ClassWork extends Work { return Classes[this.classType]; } - calculateRates(player: IPlayer): WorkStats { - return calculateClassEarningsRate(player, player, this.classType, this.location); + calculateRates(): WorkStats { + return calculateClassEarningsRate(Player, this.classType, this.location); } - process(player: IPlayer, cycles: number): boolean { + process(cycles: number): boolean { this.cyclesWorked += cycles; - const rate = this.calculateRates(player); - const earnings = applyWorkStats(player, player, rate, cycles, "class"); + const rate = this.calculateRates(); + const earnings = applyWorkStats(Player, rate, cycles, "class"); this.earnings = sumWorkStats(this.earnings, earnings); return false; } diff --git a/src/Work/CompanyWork.tsx b/src/Work/CompanyWork.tsx index f601904eb..85110951d 100644 --- a/src/Work/CompanyWork.tsx +++ b/src/Work/CompanyWork.tsx @@ -1,6 +1,6 @@ import React from "react"; import { Reviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver"; -import { IPlayer } from "src/PersonObjects/IPlayer"; +import { Player } from "../Player"; import { Work, WorkType } from "./Work"; import { influenceStockThroughCompanyWork } from "../StockMarket/PlayerInfluencing"; import { LocationName } from "../Locations/data/LocationNames"; @@ -33,19 +33,19 @@ export class CompanyWork extends Work { return c; } - getGainRates(player: IPlayer): WorkStats { + getGainRates(): WorkStats { let focusBonus = 1; - if (!player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { - focusBonus = player.focus ? 1 : CONSTANTS.BaseFocusBonus; + if (!Player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { + focusBonus = Player.focus ? 1 : CONSTANTS.BaseFocusBonus; } - return scaleWorkStats(calculateCompanyWorkStats(player, player, this.getCompany()), focusBonus); + return scaleWorkStats(calculateCompanyWorkStats(Player, this.getCompany()), focusBonus); } - process(player: IPlayer, cycles: number): boolean { + process(cycles: number): boolean { this.cyclesWorked += cycles; const company = this.getCompany(); - const gains = this.getGainRates(player); - applyWorkStats(player, player, gains, cycles, "work"); + const gains = this.getGainRates(); + applyWorkStats(Player, gains, cycles, "work"); company.playerReputation += gains.reputation * cycles; influenceStockThroughCompanyWork(company, gains.reputation, cycles); return false; diff --git a/src/Work/CreateProgramWork.ts b/src/Work/CreateProgramWork.ts index be5cf30f3..1a8e97070 100644 --- a/src/Work/CreateProgramWork.ts +++ b/src/Work/CreateProgramWork.ts @@ -2,7 +2,7 @@ import { dialogBoxCreate } from "../ui/React/DialogBox"; import { Reviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver"; import { AugmentationNames } from "../Augmentation/data/AugmentationNames"; import { CONSTANTS } from "../Constants"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { Programs } from "../Programs/Programs"; import { Work, WorkType } from "./Work"; import { Program } from "../Programs/Program"; @@ -13,7 +13,6 @@ export const isCreateProgramWork = (w: Work | null): w is CreateProgramWork => interface CreateProgramWorkParams { programName: string; singularity: boolean; - player: IPlayer; } export class CreateProgramWork extends Work { @@ -26,10 +25,9 @@ export class CreateProgramWork extends Work { this.unitCompleted = 0; this.programName = params?.programName ?? ""; - if (params?.player) { - const player = params.player; - for (let i = 0; i < player.getHomeComputer().programs.length; ++i) { - const programFile = player.getHomeComputer().programs[i]; + if (params) { + for (let i = 0; i < Player.getHomeComputer().programs.length; ++i) { + const programFile = Player.getHomeComputer().programs[i]; if (programFile.startsWith(this.programName) && programFile.endsWith("%-INC")) { const res = programFile.split("-"); if (res.length != 3) { @@ -40,7 +38,7 @@ export class CreateProgramWork extends Work { break; } this.unitCompleted = (percComplete / 100) * this.unitNeeded(); - player.getHomeComputer().programs.splice(i, 1); + Player.getHomeComputer().programs.splice(i, 1); } } } @@ -56,14 +54,14 @@ export class CreateProgramWork extends Work { return p; } - process(player: IPlayer, cycles: number): boolean { + process(cycles: number): boolean { let focusBonus = 1; - if (!player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { - focusBonus = player.focus ? 1 : CONSTANTS.BaseFocusBonus; + if (!Player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { + focusBonus = Player.focus ? 1 : CONSTANTS.BaseFocusBonus; } //Higher hacking skill will allow you to create programs faster const reqLvl = this.getProgram().create?.level ?? 0; - let skillMult = (player.skills.hacking / reqLvl) * player.getIntelligenceBonus(3); //This should always be greater than 1; + let skillMult = (Player.skills.hacking / reqLvl) * Player.getIntelligenceBonus(3); //This should always be greater than 1; skillMult = 1 + (skillMult - 1) / 5; //The divider constant can be adjusted as necessary skillMult *= focusBonus; //Skill multiplier directly applied to "time worked" @@ -75,11 +73,11 @@ export class CreateProgramWork extends Work { } return false; } - finish(player: IPlayer, cancelled: boolean): void { + finish(cancelled: boolean): void { const programName = this.programName; if (!cancelled) { //Complete case - player.gainIntelligenceExp( + Player.gainIntelligenceExp( (CONSTANTS.IntelligenceProgramBaseExpGain * this.cyclesWorked * CONSTANTS._idleSpeed) / 1000, ); if (!this.singularity) { @@ -90,14 +88,14 @@ export class CreateProgramWork extends Work { dialogBoxCreate(lines.join("
    ")); } - if (!player.getHomeComputer().programs.includes(programName)) { - player.getHomeComputer().programs.push(programName); + if (!Player.getHomeComputer().programs.includes(programName)) { + Player.getHomeComputer().programs.push(programName); } - } else if (!player.getHomeComputer().programs.includes(programName)) { + } else if (!Player.getHomeComputer().programs.includes(programName)) { //Incomplete case const perc = ((100 * this.unitCompleted) / this.unitNeeded()).toFixed(2); const incompleteName = programName + "-" + perc + "%-INC"; - player.getHomeComputer().programs.push(incompleteName); + Player.getHomeComputer().programs.push(incompleteName); } } diff --git a/src/Work/CrimeWork.ts b/src/Work/CrimeWork.ts index d7876047d..2ea4a0cb2 100644 --- a/src/Work/CrimeWork.ts +++ b/src/Work/CrimeWork.ts @@ -3,7 +3,7 @@ import { Crime } from "../Crime/Crime"; import { CONSTANTS } from "../Constants"; import { determineCrimeSuccess } from "../Crime/CrimeHelpers"; import { Crimes } from "../Crime/Crimes"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { dialogBoxCreate } from "../ui/React/DialogBox"; import { CrimeType } from "../utils/WorkType"; import { Work, WorkType } from "./Work"; @@ -78,12 +78,12 @@ export class CrimeWork extends Work { return crime; } - process(player: IPlayer, cycles = 1): boolean { + process(cycles = 1): boolean { this.cyclesWorked += cycles; const time = Object.values(Crimes).find((c) => c.type === this.crimeType)?.time ?? 0; this.unitCompleted += CONSTANTS._idleSpeed * cycles; while (this.unitCompleted >= time) { - this.commit(player); + this.commit(); this.unitCompleted -= time; } return false; @@ -93,7 +93,7 @@ export class CrimeWork extends Work { return calculateCrimeWorkStats(this.getCrime()); } - commit(player: IPlayer): void { + commit(): void { const crime = this.getCrime(); if (crime == null) { dialogBoxCreate( @@ -101,27 +101,27 @@ export class CrimeWork extends Work { ); return; } - const focusPenalty = player.focusPenalty(); + const focusPenalty = Player.focusPenalty(); // exp times 2 because were trying to maintain the same numbers as before the conversion // Technically the definition of Crimes should have the success numbers and failure should divide by 4 let gains = scaleWorkStats(this.earnings(), focusPenalty, false); let karma = crime.karma; - const success = determineCrimeSuccess(player, crime.type); + const success = determineCrimeSuccess(crime.type); if (success) { - player.gainMoney(gains.money, "crime"); - player.numPeopleKilled += crime.kills; - player.gainIntelligenceExp(gains.intExp); + Player.gainMoney(gains.money, "crime"); + Player.numPeopleKilled += crime.kills; + Player.gainIntelligenceExp(gains.intExp); } else { gains = scaleWorkStats(gains, 0.25); karma /= 4; } - player.gainHackingExp(gains.hackExp); - player.gainStrengthExp(gains.strExp); - player.gainDefenseExp(gains.defExp); - player.gainDexterityExp(gains.dexExp); - player.gainAgilityExp(gains.agiExp); - player.gainCharismaExp(gains.chaExp); - player.karma -= karma * focusPenalty; + Player.gainHackingExp(gains.hackExp); + Player.gainStrengthExp(gains.strExp); + Player.gainDefenseExp(gains.defExp); + Player.gainDexterityExp(gains.dexExp); + Player.gainAgilityExp(gains.agiExp); + Player.gainCharismaExp(gains.chaExp); + Player.karma -= karma * focusPenalty; } finish(): void { diff --git a/src/Work/FactionWork.tsx b/src/Work/FactionWork.tsx index d1ad4e988..a8464ce86 100644 --- a/src/Work/FactionWork.tsx +++ b/src/Work/FactionWork.tsx @@ -1,7 +1,7 @@ import React from "react"; import { Work, WorkType } from "./Work"; import { Reviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { FactionNames } from "../Faction/data/FactionNames"; import { Factions } from "../Faction/Factions"; import { Faction } from "../Faction/Faction"; @@ -37,29 +37,29 @@ export class FactionWork extends Work { return f; } - getReputationRate(player: IPlayer): number { + getReputationRate(): number { let focusBonus = 1; - if (!player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { - focusBonus = player.focus ? 1 : CONSTANTS.BaseFocusBonus; + if (!Player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { + focusBonus = Player.focus ? 1 : CONSTANTS.BaseFocusBonus; } - return calculateFactionRep(player, this.factionWorkType, this.getFaction().favor) * focusBonus; + return calculateFactionRep(Player, this.factionWorkType, this.getFaction().favor) * focusBonus; } - getExpRates(player: IPlayer): WorkStats { + getExpRates(): WorkStats { let focusBonus = 1; - if (!player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { - focusBonus = player.focus ? 1 : CONSTANTS.BaseFocusBonus; + if (!Player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { + focusBonus = Player.focus ? 1 : CONSTANTS.BaseFocusBonus; } - const rate = calculateFactionExp(player, this.factionWorkType); + const rate = calculateFactionExp(Player, this.factionWorkType); return scaleWorkStats(rate, focusBonus, false); } - process(player: IPlayer, cycles: number): boolean { + process(cycles: number): boolean { this.cyclesWorked += cycles; - this.getFaction().playerReputation += this.getReputationRate(player) * cycles; + this.getFaction().playerReputation += this.getReputationRate() * cycles; - const rate = this.getExpRates(player); - applyWorkStats(player, player, rate, cycles, "class"); + const rate = this.getExpRates(); + applyWorkStats(Player, rate, cycles, "class"); return false; } diff --git a/src/Work/GraftingWork.tsx b/src/Work/GraftingWork.tsx index c0279235d..6b8c75dc0 100644 --- a/src/Work/GraftingWork.tsx +++ b/src/Work/GraftingWork.tsx @@ -2,7 +2,7 @@ import React from "react"; import { CONSTANTS } from "../Constants"; import { AugmentationNames } from "../Augmentation/data/AugmentationNames"; import { GraftableAugmentations } from "../PersonObjects/Grafting/ui/GraftingRoot"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; import { Work, WorkType } from "./Work"; import { graftingIntBonus } from "../PersonObjects/Grafting/GraftingHelpers"; import { applyAugmentation } from "../Augmentation/AugmentationHelpers"; @@ -15,7 +15,6 @@ export const isGraftingWork = (w: Work | null): w is GraftingWork => w !== null interface GraftingWorkParams { augmentation: string; - player: IPlayer; singularity: boolean; } @@ -28,33 +27,33 @@ export class GraftingWork extends Work { this.unitCompleted = 0; this.augmentation = params?.augmentation ?? AugmentationNames.Targeting1; const gAugs = GraftableAugmentations(); - if (params?.player) params.player.loseMoney(gAugs[this.augmentation].cost, "augmentations"); + if (params) Player.loseMoney(gAugs[this.augmentation].cost, "augmentations"); } unitNeeded(): number { return new GraftableAugmentation(StaticAugmentations[this.augmentation]).time; } - process(player: IPlayer, cycles: number): boolean { + process(cycles: number): boolean { let focusBonus = 1; - if (!player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { - focusBonus = player.focus ? 1 : CONSTANTS.BaseFocusBonus; + if (!Player.hasAugmentation(AugmentationNames.NeuroreceptorManager, true)) { + focusBonus = Player.focus ? 1 : CONSTANTS.BaseFocusBonus; } this.cyclesWorked += cycles; - this.unitCompleted += CONSTANTS._idleSpeed * cycles * graftingIntBonus(player) * focusBonus; + this.unitCompleted += CONSTANTS._idleSpeed * cycles * graftingIntBonus() * focusBonus; return this.unitCompleted >= this.unitNeeded(); } - finish(player: IPlayer, cancelled: boolean): void { + finish(cancelled: boolean): void { const augName = this.augmentation; if (!cancelled) { applyAugmentation({ name: augName, level: 1 }); - if (!player.hasAugmentation(AugmentationNames.CongruityImplant, true)) { - player.entropy += 1; - player.applyEntropy(player.entropy); + if (!Player.hasAugmentation(AugmentationNames.CongruityImplant, true)) { + Player.entropy += 1; + Player.applyEntropy(Player.entropy); } if (!this.singularity) { @@ -62,7 +61,7 @@ export class GraftingWork extends Work { <> You've finished grafting {augName}.
    The augmentation has been applied to your body{" "} - {player.hasAugmentation(AugmentationNames.CongruityImplant, true) ? "." : ", but you feel a bit off."} + {Player.hasAugmentation(AugmentationNames.CongruityImplant, true) ? "." : ", but you feel a bit off."} , ); } @@ -78,7 +77,7 @@ export class GraftingWork extends Work { // Intelligence gain if (!cancelled) { - player.gainIntelligenceExp( + Player.gainIntelligenceExp( (CONSTANTS.IntelligenceGraftBaseExpGain * this.cyclesWorked * CONSTANTS._idleSpeed) / 10000, ); } diff --git a/src/Work/Work.ts b/src/Work/Work.ts index 9d76e36c8..2c0e3cd17 100644 --- a/src/Work/Work.ts +++ b/src/Work/Work.ts @@ -1,4 +1,3 @@ -import { IPlayer } from "../PersonObjects/IPlayer"; import { IReviverValue } from "../utils/JSONReviver"; export abstract class Work { @@ -12,8 +11,8 @@ export abstract class Work { this.cyclesWorked = 0; } - abstract process(player: IPlayer, cycles: number): boolean; - abstract finish(player: IPlayer, cancelled: boolean): void; + abstract process(cycles: number): boolean; + abstract finish(cancelled: boolean): void; abstract APICopy(): Record; abstract toJSON(): IReviverValue; } diff --git a/src/Work/WorkStats.ts b/src/Work/WorkStats.ts index 07472df41..ac3c5f25e 100644 --- a/src/Work/WorkStats.ts +++ b/src/Work/WorkStats.ts @@ -1,5 +1,5 @@ import { IPerson } from "src/PersonObjects/IPerson"; -import { IPlayer } from "../PersonObjects/IPlayer"; +import { Player } from "../Player"; export interface WorkStats { money: number; @@ -69,7 +69,6 @@ export const scaleWorkStats = (w: WorkStats, n: number, scaleMoney = true): Work }; export const applyWorkStats = ( - player: IPlayer, target: IPerson, workStats: WorkStats, cycles: number, @@ -87,7 +86,7 @@ export const applyWorkStats = ( chaExp: expStats.chaExp, intExp: expStats.intExp, }; - player.gainMoney(gains.money, source); + Player.gainMoney(gains.money, source); return gains; }; diff --git a/src/Work/formulas/Class.ts b/src/Work/formulas/Class.ts index b5263498c..46509366b 100644 --- a/src/Work/formulas/Class.ts +++ b/src/Work/formulas/Class.ts @@ -2,7 +2,7 @@ import { Locations } from "../../Locations/Locations"; import { Location } from "../../Locations/Location"; import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers"; import { CONSTANTS } from "../../Constants"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Class, Classes, ClassType } from "../ClassWork"; import { WorkStats } from "../WorkStats"; import { Server } from "../../Server/Server"; @@ -21,13 +21,12 @@ export function calculateCost(classs: Class, location: Location): number { } export function calculateClassEarnings( - player: IPlayer, - target: IPerson, + person: IPerson, type: ClassType, locationName: LocationName, ): WorkStats { //Find cost and exp gain per game cycle - const hashManager = player.hashManager; + const hashManager = Player.hashManager; const classs = Classes[type]; const location = Locations[locationName]; @@ -47,12 +46,12 @@ export function calculateClassEarnings( return { money: cost, reputation: 0, - hackExp: hackExp * target.mults.hacking_exp * BitNodeMultipliers.ClassGymExpGain, - strExp: strExp * target.mults.strength_exp * BitNodeMultipliers.ClassGymExpGain, - defExp: defExp * target.mults.defense_exp * BitNodeMultipliers.ClassGymExpGain, - dexExp: dexExp * target.mults.dexterity_exp * BitNodeMultipliers.ClassGymExpGain, - agiExp: agiExp * target.mults.agility_exp * BitNodeMultipliers.ClassGymExpGain, - chaExp: chaExp * target.mults.charisma_exp * BitNodeMultipliers.ClassGymExpGain, + hackExp: hackExp * person.mults.hacking_exp * BitNodeMultipliers.ClassGymExpGain, + strExp: strExp * person.mults.strength_exp * BitNodeMultipliers.ClassGymExpGain, + defExp: defExp * person.mults.defense_exp * BitNodeMultipliers.ClassGymExpGain, + dexExp: dexExp * person.mults.dexterity_exp * BitNodeMultipliers.ClassGymExpGain, + agiExp: agiExp * person.mults.agility_exp * BitNodeMultipliers.ClassGymExpGain, + chaExp: chaExp * person.mults.charisma_exp * BitNodeMultipliers.ClassGymExpGain, intExp: 0, }; } diff --git a/src/Work/formulas/Company.ts b/src/Work/formulas/Company.ts index 40b757161..801b8813b 100644 --- a/src/Work/formulas/Company.ts +++ b/src/Work/formulas/Company.ts @@ -1,13 +1,13 @@ import { CompanyPositions } from "../../Company/CompanyPositions"; import { Company } from "../../Company/Company"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { WorkStats } from "../WorkStats"; import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers"; import { CONSTANTS } from "../../Constants"; import { IPerson } from "src/PersonObjects/IPerson"; -export const calculateCompanyWorkStats = (player: IPlayer, worker: IPerson, company: Company): WorkStats => { - const companyPositionName = player.jobs[company.name]; +export const calculateCompanyWorkStats = (worker: IPerson, company: Company): WorkStats => { + const companyPositionName = Player.jobs[company.name]; const companyPosition = CompanyPositions[companyPositionName]; // If player has SF-11, calculate salary multiplier from favor @@ -17,7 +17,7 @@ export const calculateCompanyWorkStats = (player: IPlayer, worker: IPerson, comp } let bn11Mult = 1; - if (player.sourceFileLvl(11) > 0) { + if (Player.sourceFileLvl(11) > 0) { bn11Mult = favorMult; } diff --git a/src/engine.tsx b/src/engine.tsx index f7037ee06..03ceac12d 100644 --- a/src/engine.tsx +++ b/src/engine.tsx @@ -91,7 +91,7 @@ const Engine: { Player.playtimeSinceLastAug += time; Player.playtimeSinceLastBitnode += time; - Terminal.process(Router, Player, numCycles); + Terminal.process(numCycles); Player.processWork(numCycles); @@ -120,7 +120,7 @@ const Engine: { // Sleeves for (let i = 0; i < Player.sleeves.length; ++i) { - Player.sleeves[i].process(Player, numCycles); + Player.sleeves[i].process(numCycles); } // Counters @@ -131,7 +131,7 @@ const Engine: { updateOnlineScriptTimes(numCycles); // Hacknet Nodes - processHacknetEarnings(Player, numCycles); + processHacknetEarnings(numCycles); }, /** @@ -205,12 +205,12 @@ const Engine: { } } if (Player.corporation instanceof Corporation) { - Player.corporation.process(Player); + Player.corporation.process(); } if (Engine.Counters.mechanicProcess <= 0) { if (Player.bladeburner instanceof Bladeburner) { try { - Player.bladeburner.process(Router, Player); + Player.bladeburner.process(); } catch (e) { exceptionAlert("Exception caught in Bladeburner.process(): " + e); } @@ -240,7 +240,7 @@ const Engine: { if (loadGame(saveString)) { ThemeEvents.emit(); - initBitNodeMultipliers(Player); + initBitNodeMultipliers(); initAugmentations(); // Also calls Player.reapplyAllAugmentations() Player.reapplyAllSourceFiles(); if (Player.hasWseAccount) { @@ -308,8 +308,8 @@ const Engine: { } // Hacknet Nodes offline progress - const offlineProductionFromHacknetNodes = processHacknetEarnings(Player, numCyclesOffline); - const hacknetProdInfo = hasHacknetServers(Player) ? ( + const offlineProductionFromHacknetNodes = processHacknetEarnings(numCyclesOffline); + const hacknetProdInfo = hasHacknetServers() ? ( <> hashes @@ -345,7 +345,7 @@ const Engine: { // Sleeves offline progress for (let i = 0; i < Player.sleeves.length; ++i) { - Player.sleeves[i].process(Player, numCyclesOffline); + Player.sleeves[i].process(numCyclesOffline); } // Update total playtime @@ -392,7 +392,7 @@ const Engine: { ); } else { // No save found, start new game - initBitNodeMultipliers(Player); + initBitNodeMultipliers(); Engine.start(); // Run main game loop and Scripts loop Player.init(); initForeignServers(Player.getHomeComputer()); diff --git a/src/ui/ErrorBoundary.tsx b/src/ui/ErrorBoundary.tsx index 67a808716..5a0ceb53a 100644 --- a/src/ui/ErrorBoundary.tsx +++ b/src/ui/ErrorBoundary.tsx @@ -2,10 +2,10 @@ import React, { ErrorInfo } from "react"; import { IErrorData, getErrorForDisplay } from "../utils/ErrorHelper"; import { RecoveryRoot } from "./React/RecoveryRoot"; -import { IRouter, Page } from "./Router"; +import { Page } from "./Router"; +import { Router } from "./GameRoot"; interface IProps { - router: IRouter; softReset: () => void; } @@ -31,7 +31,7 @@ export class ErrorBoundary extends React.Component { componentDidCatch(error: Error, errorInfo: ErrorInfo): void { this.setState({ errorInfo, - page: this.props.router.page(), + page: Router.page(), }); console.error(error, errorInfo); } @@ -47,14 +47,7 @@ export class ErrorBoundary extends React.Component { } } - return ( - this.reset()} - /> - ); + return this.reset()} />; } return this.props.children; } diff --git a/src/ui/GameRoot.tsx b/src/ui/GameRoot.tsx index 933521ac3..b7d48c2a2 100644 --- a/src/ui/GameRoot.tsx +++ b/src/ui/GameRoot.tsx @@ -1,8 +1,6 @@ import React, { useState, useEffect } from "react"; import { Player } from "../Player"; -import { Engine } from "../engine"; -import { Terminal } from "../Terminal"; import { installAugmentations } from "../Augmentation/AugmentationHelpers"; import { saveObject } from "../SaveObject"; import { onExport } from "../ExportBonus"; @@ -311,7 +309,7 @@ export function GameRoot(): React.ReactElement { let bypassGame = false; switch (page) { case Page.Recovery: { - mainPage = ; + mainPage = ; withSidebar = false; withPopups = false; bypassGame = true; @@ -341,7 +339,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.Terminal: { - mainPage = ; + mainPage = ; break; } case Page.Sleeves: { @@ -357,15 +355,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.ScriptEditor: { - mainPage = ( - - ); + mainPage = ; break; } case Page.ActiveScripts: { @@ -373,7 +363,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.Hacknet: { - mainPage = ; + mainPage = ; break; } case Page.CreateProgram: { @@ -381,7 +371,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.Factions: { - mainPage = ; + mainPage = ; break; } case Page.Faction: { @@ -389,7 +379,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.Milestones: { - mainPage = ; + mainPage = ; break; } case Page.Tutorial: { @@ -405,7 +395,7 @@ export function GameRoot(): React.ReactElement { break; } case Page.DevMenu: { - mainPage = ; + mainPage = ; break; } case Page.Gang: { @@ -425,11 +415,11 @@ export function GameRoot(): React.ReactElement { break; } case Page.Travel: { - mainPage = ; + mainPage = ; break; } case Page.StockMarket: { - mainPage = ; + mainPage = ; break; } case Page.City: { @@ -444,12 +434,10 @@ export function GameRoot(): React.ReactElement { case Page.Options: { mainPage = ( saveObject.saveGame()} export={() => { // Apply the export bonus before saving the game - onExport(Player); + onExport(); saveObject.exportGame(); }} forceKill={killAllScripts} @@ -463,7 +451,7 @@ export function GameRoot(): React.ReactElement { { // Apply the export bonus before saving the game - onExport(Player); + onExport(); saveObject.exportGame(); }} installAugmentationsFn={() => { @@ -478,11 +466,11 @@ export function GameRoot(): React.ReactElement { break; } case Page.ThemeBrowser: { - mainPage = ; + mainPage = ; break; } case Page.ImportSave: { - mainPage = ; + mainPage = ; withSidebar = false; withPopups = false; bypassGame = true; @@ -492,7 +480,7 @@ export function GameRoot(): React.ReactElement { return ( - + @@ -505,8 +493,6 @@ export function GameRoot(): React.ReactElement { {withSidebar ? ( { diff --git a/src/ui/React/CharacterOverview.tsx b/src/ui/React/CharacterOverview.tsx index adbcdc2f5..c4f2ab166 100644 --- a/src/ui/React/CharacterOverview.tsx +++ b/src/ui/React/CharacterOverview.tsx @@ -197,7 +197,7 @@ function Work(): React.ReactElement { <> rep
    ( - ) + ) ); } @@ -217,7 +217,7 @@ function Work(): React.ReactElement { <> rep
    ( - ) + ) ); } diff --git a/src/ui/React/ImportSaveRoot.tsx b/src/ui/React/ImportSaveRoot.tsx index 90b9e1fc7..a9f2f1525 100644 --- a/src/ui/React/ImportSaveRoot.tsx +++ b/src/ui/React/ImportSaveRoot.tsx @@ -31,7 +31,7 @@ import { convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFuncti import { numeralWrapper } from "../numeralFormat"; import { ConfirmationModal } from "./ConfirmationModal"; import { pushImportResult } from "../../Electron"; -import { IRouter } from "../Router"; +import { Router } from "../GameRoot"; const useStyles = makeStyles((theme: Theme) => createStyles({ @@ -105,7 +105,6 @@ function ComparisonIcon({ isBetter }: { isBetter: boolean }): JSX.Element { export interface IProps { importString: string; automatic: boolean; - router: IRouter; } let initialAutosave = 0; @@ -120,7 +119,7 @@ export function ImportSaveRoot(props: IProps): JSX.Element { function handleGoBack(): void { Settings.AutosaveInterval = initialAutosave; pushImportResult(false); - props.router.allowRouting(true); + Router.allowRouting(true); setHeadback(true); } @@ -133,11 +132,11 @@ export function ImportSaveRoot(props: IProps): JSX.Element { // We want to disable autosave while we're in this mode initialAutosave = Settings.AutosaveInterval; Settings.AutosaveInterval = 0; - props.router.allowRouting(false); + Router.allowRouting(false); }, []); useEffect(() => { - if (headback) props.router.toTerminal(); + if (headback) Router.toTerminal(); }, [headback]); useEffect(() => { diff --git a/src/ui/React/Money.tsx b/src/ui/React/Money.tsx index 90128d001..085bf65ad 100644 --- a/src/ui/React/Money.tsx +++ b/src/ui/React/Money.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import { numeralWrapper } from "../numeralFormat"; -import { IPlayer } from "../../PersonObjects/IPlayer"; +import { Player } from "../../Player"; import { Theme } from "@mui/material/styles"; import makeStyles from "@mui/styles/makeStyles"; import createStyles from "@mui/styles/createStyles"; @@ -18,14 +18,13 @@ const useStyles = makeStyles((theme: Theme) => interface IProps { money: number | string; - player?: IPlayer; + forPurchase?: boolean; } export function Money(props: IProps): React.ReactElement { const classes = useStyles(); - if (props.player !== undefined) { - if (typeof props.money !== "number") throw new Error("if player if provided, money should be number, contact dev"); - if (!props.player.canAfford(props.money)) - return {numeralWrapper.formatMoney(props.money)}; + if (props.forPurchase){ + if (typeof props.money !== "number") throw new Error("if value is for a purchase, money should be number, contact dev"); + if (!Player.canAfford(props.money)) return {numeralWrapper.formatMoney(props.money)}; } return ( diff --git a/src/ui/React/RecoveryRoot.tsx b/src/ui/React/RecoveryRoot.tsx index 341cb791f..20f24acf2 100644 --- a/src/ui/React/RecoveryRoot.tsx +++ b/src/ui/React/RecoveryRoot.tsx @@ -3,7 +3,7 @@ import React, { useEffect } from "react"; import { Typography, Link, Button, ButtonGroup, Tooltip, Box, Paper, TextField } from "@mui/material"; import { Settings } from "../../Settings/Settings"; import { load } from "../../db"; -import { IRouter } from "../Router"; +import { Router } from "../GameRoot"; import { download } from "../../SaveObject"; import { IErrorData, newIssueUrl } from "../../utils/ErrorHelper"; import { DeleteGameButton } from "./DeleteGameButton"; @@ -19,17 +19,16 @@ export function ActivateRecoveryMode(): void { } interface IProps { - router: IRouter; softReset: () => void; errorData?: IErrorData; resetError?: () => void; } -export function RecoveryRoot({ router, softReset, errorData, resetError }: IProps): React.ReactElement { +export function RecoveryRoot({ softReset, errorData, resetError }: IProps): React.ReactElement { function recover(): void { if (resetError) resetError(); RecoveryMode = false; - router.toTerminal(); + Router.toTerminal(); } Settings.AutosaveInterval = 0; diff --git a/src/ui/WorkInProgressRoot.tsx b/src/ui/WorkInProgressRoot.tsx index f99730478..dd518ec6d 100644 --- a/src/ui/WorkInProgressRoot.tsx +++ b/src/ui/WorkInProgressRoot.tsx @@ -10,7 +10,8 @@ import { LocationName } from "../Locations/data/LocationNames"; import { Locations } from "../Locations/Locations"; import { Settings } from "../Settings/Settings"; import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; -import { use } from "./Context"; +import { Player } from "../Player"; +import { Router } from "./GameRoot" import { numeralWrapper } from "./numeralFormat"; import { Money } from "./React/Money"; import { MoneyRate } from "./React/MoneyRate"; @@ -202,9 +203,6 @@ export function WorkInProgressRoot(): React.ReactElement { return () => clearInterval(id); }, []); - const player = use.Player(); - const router = use.Router(); - let workInfo: IWorkInfo = { buttons: { cancel: () => undefined, @@ -213,25 +211,25 @@ export function WorkInProgressRoot(): React.ReactElement { stopText: "", }; - if (player.currentWork === null) { - setTimeout(() => router.toTerminal()); + if (Player.currentWork === null) { + setTimeout(() => Router.toTerminal()); return <>; } - if (isCrimeWork(player.currentWork)) { - const crime = player.currentWork.getCrime(); - const completion = (player.currentWork.unitCompleted / crime.time) * 100; - const gains = player.currentWork.earnings(); - const successChance = crime.successRate(player); + if (isCrimeWork(Player.currentWork)) { + const crime = Player.currentWork.getCrime(); + const completion = (Player.currentWork.unitCompleted / crime.time) * 100; + const gains = Player.currentWork.earnings(); + const successChance = crime.successRate(Player); workInfo = { buttons: { cancel: () => { - router.toLocation(Locations[LocationName.Slums]); - player.finishWork(true); + Router.toLocation(Locations[LocationName.Slums]); + Player.finishWork(true); }, unfocus: () => { - router.toCity(); - player.stopFocusing(); + Router.toCity(); + Player.stopFocusing(); }, }, title: `You are attempting ${crime.workName}`, @@ -247,7 +245,7 @@ export function WorkInProgressRoot(): React.ReactElement { ...CrimeExpRows(gains), ], progress: { - remaining: crime.time - player.currentWork.unitCompleted, + remaining: crime.time - Player.currentWork.unitCompleted, percentage: completion, }, @@ -255,16 +253,16 @@ export function WorkInProgressRoot(): React.ReactElement { }; } - if (isClassWork(player.currentWork)) { - const classWork = player.currentWork; + if (isClassWork(Player.currentWork)) { + const classWork = Player.currentWork; function cancel(): void { - player.finishWork(true); - router.toCity(); + Player.finishWork(true); + Router.toCity(); } function unfocus(): void { - router.toCity(); - player.stopFocusing(); + Router.toCity(); + Player.stopFocusing(); } let stopText = ""; @@ -274,7 +272,7 @@ export function WorkInProgressRoot(): React.ReactElement { stopText = "Stop taking course"; } - const rates = classWork.calculateRates(player); + const rates = classWork.calculateRates(); workInfo = { buttons: { cancel: cancel, @@ -302,15 +300,15 @@ export function WorkInProgressRoot(): React.ReactElement { }; } - if (isCreateProgramWork(player.currentWork)) { - const create = player.currentWork; + if (isCreateProgramWork(Player.currentWork)) { + const create = Player.currentWork; function cancel(): void { - player.finishWork(true); - router.toTerminal(); + Player.finishWork(true); + Router.toTerminal(); } function unfocus(): void { - router.toTerminal(); - player.stopFocusing(); + Router.toTerminal(); + Player.stopFocusing(); } const completion = (create.unitCompleted / create.unitNeeded()) * 100; @@ -336,15 +334,15 @@ export function WorkInProgressRoot(): React.ReactElement { }; } - if (isGraftingWork(player.currentWork)) { - const graft = player.currentWork; + if (isGraftingWork(Player.currentWork)) { + const graft = Player.currentWork; function cancel(): void { - player.finishWork(true); - router.toTerminal(); + Player.finishWork(true); + Router.toTerminal(); } function unfocus(): void { - router.toTerminal(); - player.stopFocusing(); + Router.toTerminal(); + Player.stopFocusing(); } workInfo = { @@ -372,15 +370,15 @@ export function WorkInProgressRoot(): React.ReactElement { }; } - if (isFactionWork(player.currentWork)) { - const faction = player.currentWork.getFaction(); + if (isFactionWork(Player.currentWork)) { + const faction = Player.currentWork.getFaction(); if (!faction) { workInfo = { buttons: { - cancel: () => router.toFactions(), + cancel: () => Router.toFactions(), }, title: - `You have not joined ${player.currentWork.factionName || "(Faction not found)"} at this time,` + + `You have not joined ${Player.currentWork.factionName || "(Faction not found)"} at this time,` + " please try again if you think this should have worked", stopText: "Back to Factions", @@ -388,12 +386,12 @@ export function WorkInProgressRoot(): React.ReactElement { } function cancel(): void { - router.toFaction(faction); - player.finishWork(true); + Router.toFaction(faction); + Player.finishWork(true); } function unfocus(): void { - router.toFaction(faction); - player.stopFocusing(); + Router.toFaction(faction); + Player.stopFocusing(); } const description = { @@ -402,7 +400,7 @@ export function WorkInProgressRoot(): React.ReactElement { [FactionWorkType.SECURITY]: "performing security detail", }; - const exp = player.currentWork.getExpRates(player); + const exp = Player.currentWork.getExpRates(); workInfo = { buttons: { @@ -411,34 +409,34 @@ export function WorkInProgressRoot(): React.ReactElement { }, title: ( <> - You are currently {description[player.currentWork.factionWorkType]} for {faction.name} + You are currently {description[Player.currentWork.factionWorkType]} for {faction.name} ), description: ( <> Current Faction Reputation: ( - ) + ) ), gains: ExpRows(exp), progress: { - elapsed: player.currentWork.cyclesWorked * CONSTANTS._idleSpeed, + elapsed: Player.currentWork.cyclesWorked * CONSTANTS._idleSpeed, }, stopText: "Stop Faction work", }; } - if (isCompanyWork(player.currentWork)) { - const comp = Companies[player.currentWork.companyName]; + if (isCompanyWork(Player.currentWork)) { + const comp = Companies[Player.currentWork.companyName]; if (comp == null || !(comp instanceof Company)) { workInfo = { buttons: { - cancel: () => router.toTerminal(), + cancel: () => Router.toTerminal(), }, title: - `You cannot work for ${player.currentWork.companyName || "(Company not found)"} at this time,` + + `You cannot work for ${Player.currentWork.companyName || "(Company not found)"} at this time,` + " please try again if you think this should have worked", stopText: "Back to Terminal", @@ -448,16 +446,16 @@ export function WorkInProgressRoot(): React.ReactElement { const companyRep = comp.playerReputation; function cancel(): void { - player.finishWork(true); - router.toJob(Locations[comp.name]); + Player.finishWork(true); + Router.toJob(Locations[comp.name]); } function unfocus(): void { - player.stopFocusing(); - router.toJob(Locations[comp.name]); + Player.stopFocusing(); + Router.toJob(Locations[comp.name]); } - const position = player.jobs[player.currentWork.companyName]; - const gains = player.currentWork.getGainRates(player); + const position = Player.jobs[Player.currentWork.companyName]; + const gains = Player.currentWork.getGainRates(); workInfo = { buttons: { cancel: cancel, @@ -465,7 +463,7 @@ export function WorkInProgressRoot(): React.ReactElement { }, title: ( <> - You are currently working as a {position} at {player.currentWork.companyName} + You are currently working as a {position} at {Player.currentWork.companyName} ), @@ -488,7 +486,7 @@ export function WorkInProgressRoot(): React.ReactElement { ...ExpRows(gains), ], progress: { - elapsed: player.currentWork.cyclesWorked * CONSTANTS._idleSpeed, + elapsed: Player.currentWork.cyclesWorked * CONSTANTS._idleSpeed, }, stopText: "Stop working",