unexport AllServers

This commit is contained in:
Olivier Gagnon 2021-10-07 16:04:04 -04:00
parent 1d488565c6
commit be29481689
27 changed files with 185 additions and 159 deletions

@ -6,11 +6,11 @@ import {
} from "./CodingContracts";
import { Factions } from "./Faction/Factions";
import { Player } from "./Player";
import { AllServers } from "./Server/AllServers";
import { GetServerByHostname } from "./Server/ServerHelpers";
import { GetAllServers } from "./Server/AllServers";
import { getServer } from "./Server/ServerHelpers";
import { SpecialServerNames } from "./Server/SpecialServerIps";
import { Server } from "./Server/Server";
import { HacknetServer } from "./Hacknet/HacknetServer";
import { BaseServer } from "./Server/BaseServer";
import { getRandomInt } from "./utils/helpers/getRandomInt";
@ -68,10 +68,7 @@ export function generateContract(params: IGenerateContractParams): void {
// Server
let server;
if (params.server != null) {
server = GetServerByHostname(params.server);
if (server == null) {
server = AllServers[params.server];
}
server = getServer(params.server);
if (server == null) {
server = getRandomServer();
}
@ -165,10 +162,10 @@ function getRandomReward(): ICodingContractReward {
return reward;
}
function getRandomServer(): Server | HacknetServer {
const servers = Object.keys(AllServers);
function getRandomServer(): BaseServer {
const servers = GetAllServers();
let randIndex = getRandomInt(0, servers.length - 1);
let randServer = AllServers[servers[randIndex]];
let randServer = servers[randIndex];
// An infinite loop shouldn't ever happen, but to be safe we'll use
// a for loop with a limited number of tries
@ -181,13 +178,13 @@ function getRandomServer(): Server | HacknetServer {
break;
}
randIndex = getRandomInt(0, servers.length - 1);
randServer = AllServers[servers[randIndex]];
randServer = servers[randIndex];
}
return randServer;
}
function getRandomFilename(server: Server | HacknetServer, reward: ICodingContractReward): string {
function getRandomFilename(server: BaseServer, reward: ICodingContractReward): string {
let contractFn = `contract-${getRandomInt(0, 1e6)}`;
for (let i = 0; i < 1000; ++i) {

@ -8,8 +8,8 @@ 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 { AllServers } from "../../Server/AllServers";
import { HacknetServer } from "../../Hacknet/HacknetServer";
import { GetAllServers } from "../../Server/AllServers";
import { Server } from "../../Server/Server";
import { GetServerByHostname } from "../../Server/ServerHelpers";
import MenuItem from "@mui/material/MenuItem";
@ -21,7 +21,7 @@ export function Servers(): React.ReactElement {
function rootServer(): void {
const s = GetServerByHostname(server);
if (s === null) return;
if (s instanceof HacknetServer) return;
if (!(s instanceof Server)) return;
s.hasAdminRights = true;
s.sshPortOpen = true;
s.ftpPortOpen = true;
@ -32,9 +32,8 @@ export function Servers(): React.ReactElement {
}
function rootAllServers(): void {
for (const i in AllServers) {
const s = AllServers[i];
if (s instanceof HacknetServer) return;
for (const s of GetAllServers()) {
if (!(s instanceof Server)) return;
s.hasAdminRights = true;
s.sshPortOpen = true;
s.ftpPortOpen = true;
@ -48,30 +47,28 @@ export function Servers(): React.ReactElement {
function minSecurity(): void {
const s = GetServerByHostname(server);
if (s === null) return;
if (s instanceof HacknetServer) return;
if (!(s instanceof Server)) return;
s.hackDifficulty = s.minDifficulty;
}
function minAllSecurity(): void {
for (const i in AllServers) {
const server = AllServers[i];
if (server instanceof HacknetServer) continue;
server.hackDifficulty = server.minDifficulty;
for (const s of GetAllServers()) {
if (!(s instanceof Server)) return;
s.hackDifficulty = s.minDifficulty;
}
}
function maxMoney(): void {
const s = GetServerByHostname(server);
if (s === null) return;
if (s instanceof HacknetServer) return;
if (!(s instanceof Server)) return;
s.moneyAvailable = s.moneyMax;
}
function maxAllMoney(): void {
for (const i in AllServers) {
const server = AllServers[i];
if (server instanceof HacknetServer) continue;
server.moneyAvailable = server.moneyMax;
for (const s of GetAllServers()) {
if (!(s instanceof Server)) return;
s.moneyAvailable = s.moneyMax;
}
}
@ -89,7 +86,7 @@ export function Servers(): React.ReactElement {
</td>
<td colSpan={2}>
<Select id="dev-servers-dropdown" onChange={setServerDropdown} value={server}>
{Object.values(AllServers).map((server) => (
{GetAllServers().map((server) => (
<MenuItem key={server.hostname} value={server.hostname}>
{server.hostname}
</MenuItem>

@ -1,5 +1,6 @@
import React from "react";
import { AllServers } from "../Server/AllServers";
import { GetAllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
import { Modal } from "../ui/React/Modal";
import { numeralWrapper } from "../ui/numeralFormat";
@ -21,7 +22,8 @@ interface IServerProps {
}
function ServerAccordion(props: IServerProps): React.ReactElement {
const server = AllServers[props.ip];
const server = getServer(props.ip);
if (server === null) throw new Error("server should not be null");
let totalSize = 0;
for (const f of server.scripts) {
totalSize += f.code.length;
@ -98,9 +100,9 @@ interface IProps {
}
export function FileDiagnosticModal(props: IProps): React.ReactElement {
const ips: string[] = [];
for (const ip of Object.keys(AllServers)) {
ips.push(ip);
const keys: string[] = [];
for (const key in GetAllServers()) {
keys.push(key);
}
return (
@ -110,7 +112,7 @@ export function FileDiagnosticModal(props: IProps): React.ReactElement {
Welcome to the file diagnostic! If your save file is really big it's likely because you have too many
text/scripts. This tool can help you narrow down where they are.
</Typography>
{ips.map((ip: string) => (
{keys.map((ip: string) => (
<ServerAccordion key={ip} ip={ip} />
))}
</>

@ -19,8 +19,7 @@ import { HashUpgrades } from "./HashUpgrades";
import { generateRandomContract } from "../CodingContractGenerator";
import { iTutorialSteps, iTutorialNextStep, ITutorial } from "../InteractiveTutorial";
import { IPlayer } from "../PersonObjects/IPlayer";
import { AllServers } from "../Server/AllServers";
import { GetServerByHostname } from "../Server/ServerHelpers";
import { GetServerByHostname, getServer } from "../Server/ServerHelpers";
import { Server } from "../Server/Server";
import { SourceFileFlags } from "../SourceFile/SourceFileFlags";
@ -416,8 +415,8 @@ function processAllHacknetServerEarnings(player: IPlayer, numCycles: number): nu
// Also, update the hash rate before processing
const ip = player.hacknetNodes[i];
if (ip instanceof HacknetNode) throw new Error(`player nodes should not be HacketNode`);
const hserver = AllServers[ip];
if (hserver instanceof Server) throw new Error(`player nodes shoud not be Server`);
const hserver = getServer(ip);
if (!(hserver instanceof HacknetServer)) throw new Error(`player nodes shoud not be Server`);
hserver.updateHashRate(player.hacknet_node_money_mult);
const h = hserver.process(numCycles);
hashes += h;
@ -448,7 +447,7 @@ export function updateHashManagerCapacity(player: IPlayer): void {
}
const ip = nodes[i];
if (ip instanceof HacknetNode) throw new Error(`player nodes should be string but isn't`);
const h = AllServers[ip];
const h = getServer(ip);
if (!(h instanceof HacknetServer)) {
player.hashManager.updateCapacity(0);
return;

@ -7,6 +7,7 @@ import { GeneralInfo } from "./GeneralInfo";
import { HacknetNodeElem } from "./HacknetNodeElem";
import { HacknetServerElem } from "./HacknetServerElem";
import { HacknetNode } from "../HacknetNode";
import { HacknetServer } from "../HacknetServer";
import { HashUpgradeModal } from "./HashUpgradeModal";
import { MultiplierButtons } from "./MultiplierButtons";
import { PlayerInfo } from "./PlayerInfo";
@ -21,7 +22,7 @@ import {
} from "../HacknetHelpers";
import { IPlayer } from "../../PersonObjects/IPlayer";
import { AllServers } from "../../Server/AllServers";
import { getServer } from "../../Server/ServerHelpers";
import { Server } from "../../Server/Server";
import Typography from "@mui/material/Typography";
@ -50,8 +51,8 @@ export function HacknetRoot(props: IProps): React.ReactElement {
const node = props.player.hacknetNodes[i];
if (hasHacknetServers(props.player)) {
if (node instanceof HacknetNode) throw new Error("node was hacknet node"); // should never happen
const hserver = AllServers[node];
if (hserver instanceof Server) throw new Error("node was a normal server"); // should never happen
const hserver = getServer(node);
if (!(hserver instanceof HacknetServer)) throw new Error("node was not hacknet server"); // should never happen
if (hserver) {
totalProduction += hserver.hashRate;
} else {
@ -88,11 +89,11 @@ export function HacknetRoot(props: IProps): React.ReactElement {
const nodes = props.player.hacknetNodes.map((node: string | HacknetNode) => {
if (hasHacknetServers(props.player)) {
if (node instanceof HacknetNode) throw new Error("node was hacknet node"); // should never happen
const hserver = AllServers[node];
const hserver = getServer(node);
if (hserver == null) {
throw new Error(`Could not find Hacknet Server object in AllServers map for IP: ${node}`);
}
if (hserver instanceof Server) throw new Error("node was normal server"); // should never happen
if (!(hserver instanceof HacknetServer)) throw new Error("node was not hacknet server"); // should never happen
return (
<HacknetServerElem
player={props.player}

@ -11,7 +11,7 @@ import { RamCostConstants } from "./RamCostGenerator";
import { RunningScript } from "../Script/RunningScript";
import { Script } from "../Script/Script";
import { AllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
import { BaseServer } from "../Server/BaseServer";
import { IMap } from "../types";
@ -118,7 +118,7 @@ export class WorkerScript {
runningScriptObj.pid = sanitizedPid;
// Get the underlying script's code
const server = AllServers[this.serverIp];
const server = getServer(this.serverIp);
if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${this.serverIp}`);
}
@ -147,7 +147,7 @@ export class WorkerScript {
* Returns the Server on which this script is running
*/
getServer(): BaseServer {
const server = AllServers[this.serverIp];
const server = getServer(this.serverIp);
if (server == null) throw new Error(`Script ${this.name} pid ${this.pid} is running on non-existent server?`);
return server;
}

@ -7,7 +7,7 @@ import { workerScripts } from "./WorkerScripts";
import { WorkerScriptStartStopEventEmitter } from "./WorkerScriptStartStopEventEmitter";
import { RunningScript } from "../Script/RunningScript";
import { AllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
import { compareArrays } from "../utils/helpers/compareArrays";
import { roundToTwo } from "../utils/helpers/roundToTwo";
@ -84,7 +84,7 @@ function removeWorkerScript(workerScript: WorkerScript, rerenderUi = true): void
const name = workerScript.name;
// Get the server on which the script runs
const server = AllServers[ip];
const server = getServer(ip);
if (server == null) {
console.error(`Could not find server on which this script is running: ${ip}`);
return;

@ -1,5 +1,5 @@
import { isString } from "./utils/helpers/isString";
import { AllServers } from "./Server/AllServers";
import { getServer } from "./Server/ServerHelpers";
import { WorkerScript } from "./Netscript/WorkerScript";
export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> {
@ -14,7 +14,7 @@ export function netscriptDelay(time: number, workerScript: WorkerScript): Promis
export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
const lineNum = "";
const server = AllServers[workerScript.serverIp];
const server = getServer(workerScript.serverIp);
if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${workerScript.serverIp}`);
}

@ -101,7 +101,7 @@ import { findRunningScript, findRunningScriptByPid } from "./Script/ScriptHelper
import { isScriptFilename } from "./Script/isScriptFilename";
import { PromptEvent } from "./ui/React/PromptManager";
import { AllServers, AddToAllServers, createUniqueRandomIp } from "./Server/AllServers";
import { GetAllServers, DeleteServer, AddToAllServers, createUniqueRandomIp } from "./Server/AllServers";
import { RunningScript } from "./Script/RunningScript";
import {
GetServerByHostname,
@ -301,8 +301,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
callingFnName = "getRunningScriptgetRunningScriptByPid";
}
for (const name of Object.keys(AllServers)) {
const server = AllServers[name];
for (const server of GetAllServers()) {
const runningScript = findRunningScriptByPid(pid, server);
if (runningScript) return runningScript;
}
@ -2257,7 +2256,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}
// Delete from all servers
delete AllServers[ip];
DeleteServer(ip);
// Delete from home computer
found = false;

@ -16,7 +16,7 @@ import {
} from "../Hacknet/HacknetHelpers";
import { HacknetServer } from "../Hacknet/HacknetServer";
import { HacknetNode } from "../Hacknet/HacknetNode";
import { AllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
export interface INetscriptHacknet {
numNodes(): number;
@ -58,7 +58,7 @@ export function NetscriptHacknet(
if (hasHacknetServers(player)) {
const hi = player.hacknetNodes[i];
if (typeof hi !== "string") throw new Error("hacknet node was not a string");
const hserver = AllServers[hi];
const hserver = getServer(hi);
if (!(hserver instanceof HacknetServer)) throw new Error("hacknet server was not actually hacknet server");
if (hserver == null) {
throw helper.makeRuntimeErrorMsg(

@ -18,7 +18,7 @@ import { RunningScript } from "./Script/RunningScript";
import { getRamUsageFromRunningScript } from "./Script/RunningScriptHelpers";
import { scriptCalculateOfflineProduction } from "./Script/ScriptHelpers";
import { Script } from "./Script/Script";
import { AllServers } from "./Server/AllServers";
import { GetAllServers } from "./Server/AllServers";
import { BaseServer } from "./Server/BaseServer";
import { Settings } from "./Settings/Settings";
@ -600,28 +600,24 @@ export function loadAllRunningScripts(): void {
if (skipScriptLoad) {
console.info("Skipping the load of any scripts during startup");
}
for (const property in AllServers) {
if (AllServers.hasOwnProperty(property)) {
const server = AllServers[property];
for (const server of GetAllServers()) {
// Reset each server's RAM usage to 0
server.ramUsed = 0;
// Reset each server's RAM usage to 0
server.ramUsed = 0;
// Reset modules on all scripts
for (let i = 0; i < server.scripts.length; ++i) {
server.scripts[i].markUpdated();
}
// Reset modules on all scripts
for (let i = 0; i < server.scripts.length; ++i) {
server.scripts[i].markUpdated();
}
if (skipScriptLoad) {
// Start game with no scripts
server.runningScripts.length = 0;
} else {
for (let j = 0; j < server.runningScripts.length; ++j) {
createAndAddWorkerScript(server.runningScripts[j], server);
if (skipScriptLoad) {
// Start game with no scripts
server.runningScripts.length = 0;
} else {
for (let j = 0; j < server.runningScripts.length; ++j) {
createAndAddWorkerScript(server.runningScripts[j], server);
// Offline production
scriptCalculateOfflineProduction(server.runningScripts[j]);
}
// Offline production
scriptCalculateOfflineProduction(server.runningScripts[j]);
}
}
}

@ -18,6 +18,7 @@ import { HashManager } from "../Hacknet/HashManager";
import { HacknetNode } from "../Hacknet/HacknetNode";
import { LocationName } from "../Locations/data/LocationNames";
import { Server } from "../Server/Server";
import { BaseServer } from "../Server/BaseServer";
import { IPlayerOwnedSourceFile } from "../SourceFile/PlayerOwnedSourceFile";
import { MoneySourceTracker } from "../utils/MoneySourceTracker";
import { Exploit } from "../Exploits/Exploit";
@ -185,7 +186,7 @@ export interface IPlayer {
gainCharismaExp(exp: number): void;
gainIntelligenceExp(exp: number): void;
gainMoney(money: number): void;
getCurrentServer(): Server | HacknetServer;
getCurrentServer(): BaseServer;
getGangFaction(): Faction;
getGangName(): string;
getHomeComputer(): Server;

@ -13,6 +13,7 @@ import { Exploit } from "../../Exploits/Exploit";
import { WorkerScript } from "../../Netscript/WorkerScript";
import { CompanyPosition } from "../../Company/CompanyPosition";
import { Server } from "../../Server/Server";
import { BaseServer } from "../../Server/BaseServer";
import { HacknetServer } from "../../Hacknet/HacknetServer";
import { Faction } from "../../Faction/Faction";
import { Company } from "../../Company/Company";
@ -192,7 +193,7 @@ export class PlayerObject implements IPlayer {
gainCharismaExp: (exp: number) => void;
gainIntelligenceExp: (exp: number) => void;
gainMoney: (money: number) => void;
getCurrentServer: () => Server | HacknetServer;
getCurrentServer: () => BaseServer;
getGangFaction: () => Faction;
getGangName: () => string;
getHomeComputer: () => Server;

@ -32,9 +32,9 @@ import {
getFactionSecurityWorkRepGain,
getFactionFieldWorkRepGain,
} from "../formulas/reputation";
import { AllServers, AddToAllServers, createUniqueRandomIp } from "../../Server/AllServers";
import { AddToAllServers, createUniqueRandomIp } from "../../Server/AllServers";
import { Server } from "../../Server/Server";
import { safetlyCreateUniqueServer } from "../../Server/ServerHelpers";
import { safetlyCreateUniqueServer, getServer } from "../../Server/ServerHelpers";
import { Settings } from "../../Settings/Settings";
import { SpecialServerIps, SpecialServerNames } from "../../Server/SpecialServerIps";
import { applySourceFile } from "../../SourceFile/applySourceFile";
@ -44,6 +44,7 @@ import { SourceFileFlags } from "../../SourceFile/SourceFileFlags";
import { influenceStockThroughCompanyWork } from "../../StockMarket/PlayerInfluencing";
import { getHospitalizationCost } from "../../Hospital/Hospital";
import { WorkerScript } from "../../Netscript/WorkerScript";
import { HacknetServer } from "../../Hacknet/HacknetServer";
import Decimal from "decimal.js";
@ -578,7 +579,7 @@ export function startWork(this: IPlayer, router: IRouter, companyName: string):
export function cancelationPenalty(this: IPlayer): number {
const specialIp = SpecialServerIps[this.companyName];
if (typeof specialIp === "string" && specialIp !== "") {
const server = AllServers[specialIp];
const server = getServer(specialIp);
if (server instanceof Server) {
if (server && server.backdoorInstalled) return 0.75;
}
@ -2193,7 +2194,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
const fulcrumsecrettechonologiesFac = Factions["Fulcrum Secret Technologies"];
const fulcrumIP = SpecialServerIps[SpecialServerNames.BitRunnersServer];
if (typeof fulcrumIP !== "string") throw new Error("Fulcrum Secret Technologies should be string");
const fulcrumSecretServer = AllServers[fulcrumIP];
const fulcrumSecretServer = getServer(fulcrumIP);
if (!(fulcrumSecretServer instanceof Server)) throw new Error("Fulcrum Secret Technologies should be normal server");
if (fulcrumSecretServer == null) {
console.error("Could not find Fulcrum Secret Technologies Server");
@ -2213,7 +2214,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
const bitrunnersFac = Factions["BitRunners"];
const bitrunnerIP = SpecialServerIps[SpecialServerNames.BitRunnersServer];
if (typeof bitrunnerIP !== "string") throw new Error("BitRunners should be string");
const bitrunnersServer = AllServers[bitrunnerIP];
const bitrunnersServer = getServer(bitrunnerIP);
if (!(bitrunnersServer instanceof Server)) throw new Error("BitRunners should be normal server");
if (bitrunnersServer == null) {
console.error("Could not find BitRunners Server");
@ -2231,7 +2232,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
const theblackhandFac = Factions["The Black Hand"];
const tbhIP = SpecialServerIps[SpecialServerNames.TheBlackHandServer];
if (typeof tbhIP !== "string") throw new Error("TheBlackHand should be string");
const blackhandServer = AllServers[tbhIP];
const blackhandServer = getServer(tbhIP);
if (!(blackhandServer instanceof Server)) throw new Error("TheBlackHand should be normal server");
if (blackhandServer == null) {
console.error("Could not find The Black Hand Server");
@ -2248,7 +2249,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
const nitesecFac = Factions["NiteSec"];
const nitesecIP = SpecialServerIps[SpecialServerNames.NiteSecServer];
if (typeof nitesecIP !== "string") throw new Error("NiteSec should be string");
const nitesecServer = AllServers[nitesecIP];
const nitesecServer = getServer(nitesecIP);
if (!(nitesecServer instanceof Server)) throw new Error("NiteSec should be normal server");
if (nitesecServer == null) {
console.error("Could not find NiteSec Server");
@ -2447,8 +2448,9 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
for (let i = 0; i < this.hacknetNodes.length; ++i) {
const v = this.hacknetNodes[i];
if (typeof v === "string") {
const hserver = AllServers[v];
if (hserver instanceof Server) throw new Error("player hacknet server was not HacknetServer");
const hserver = getServer(v);
if (hserver === null || !(hserver instanceof HacknetServer))
throw new Error("player hacknet server was not HacknetServer");
totalHacknetLevels += hserver.level;
totalHacknetRam += hserver.maxRam;
totalHacknetCores += hserver.cores;
@ -2487,7 +2489,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
const cybersecFac = Factions["CyberSec"];
const cyberSecIP = SpecialServerIps[SpecialServerNames.CyberSecServer];
if (typeof cyberSecIP !== "string") throw new Error("cybersec should be string");
const cybersecServer = AllServers[cyberSecIP];
const cybersecServer = getServer(cyberSecIP);
if (!(cybersecServer instanceof Server)) throw new Error("cybersec should be normal server");
if (cybersecServer == null) {
console.error("Could not find CyberSec Server");

@ -7,22 +7,24 @@ import { CONSTANTS } from "../../Constants";
import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers";
import { Server } from "../../Server/Server";
import { BaseServer } from "../../Server/BaseServer";
import { HacknetServer } from "../../Hacknet/HacknetServer";
import { AddToAllServers, AllServers, createUniqueRandomIp } from "../../Server/AllServers";
import { AddToAllServers, createUniqueRandomIp } from "../../Server/AllServers";
import { getServer } from "../../Server/ServerHelpers";
import { SpecialServerIps } from "../../Server/SpecialServerIps";
export function hasTorRouter(this: IPlayer): boolean {
return SpecialServerIps.hasOwnProperty("Darkweb Server");
}
export function getCurrentServer(this: IPlayer): Server | HacknetServer {
const server = AllServers[this.currentServer];
export function getCurrentServer(this: IPlayer): BaseServer {
const server = getServer(this.currentServer);
if (server === null) throw new Error("somehow connected to a server that does not exist.");
return server;
}
export function getHomeComputer(this: IPlayer): Server {
const home = AllServers[this.homeComputer];
const home = getServer(this.homeComputer);
if (home instanceof Server) return home;
throw new Error("home computer was not a normal server");
}

@ -17,8 +17,8 @@ import { Router } from "./ui/GameRoot";
import { resetPidCounter } from "./Netscript/Pid";
import { LiteratureNames } from "./Literature/data/LiteratureNames";
import { AllServers, AddToAllServers, initForeignServers, prestigeAllServers } from "./Server/AllServers";
import { prestigeHomeComputer } from "./Server/ServerHelpers";
import { AddToAllServers, initForeignServers, prestigeAllServers } from "./Server/AllServers";
import { prestigeHomeComputer, getServer } from "./Server/ServerHelpers";
import { SourceFileFlags, updateSourceFileFlags } from "./SourceFile/SourceFileFlags";
import { SpecialServerIps, prestigeSpecialServerIps, SpecialServerNames } from "./Server/SpecialServerIps";
import { deleteStockMarket, initStockMarket, initSymbolToStockMap } from "./StockMarket/StockMarket";
@ -133,10 +133,10 @@ function prestigeAugmentation(): void {
if (augmentationExists(AugmentationNames.TheRedPill) && Augmentations[AugmentationNames.TheRedPill].owned) {
const WorldDaemonIP = SpecialServerIps[SpecialServerNames.WorldDaemon];
if (typeof WorldDaemonIP !== "string") throw new Error("WorldDaemonIP should be string");
const WorldDaemon = AllServers[WorldDaemonIP];
const WorldDaemon = getServer(WorldDaemonIP);
const DaedalusServerIP = SpecialServerIps[SpecialServerNames.DaedalusServer];
if (typeof DaedalusServerIP !== "string") throw new Error("DaedalusServerIP should be string");
const DaedalusServer = AllServers[DaedalusServerIP];
const DaedalusServer = getServer(DaedalusServerIP);
if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);

@ -230,8 +230,8 @@ export const programsMetadata: IProgramCreationParams[] = [
return;
}
if (targetServer instanceof HacknetServer) {
terminal.print(`ServerProfiler.exe cannot be run on a Hacknet Server.`);
if (!(targetServer instanceof Server)) {
terminal.print(`ServerProfiler.exe can only be run on normal servers.`);
return;
}

@ -5,7 +5,7 @@ import { Factions, loadFactions } from "./Faction/Factions";
import { loadAllGangs, AllGangs } from "./Gang/AllGangs";
import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers";
import { Player, loadPlayer } from "./Player";
import { AllServers, loadAllServers } from "./Server/AllServers";
import { saveAllServers, loadAllServers } from "./Server/AllServers";
import { Settings } from "./Settings/Settings";
import { loadSpecialServerIps, SpecialServerIps } from "./Server/SpecialServerIps";
import { SourceFileFlags } from "./SourceFile/SourceFileFlags";
@ -41,21 +41,7 @@ class BitburnerSaveObject {
getSaveString(): string {
this.PlayerSave = JSON.stringify(Player);
// Delete all logs from all running scripts
const TempAllServers = JSON.parse(JSON.stringify(AllServers), Reviver);
for (const ip in TempAllServers) {
const server = TempAllServers[ip];
if (server == null) {
continue;
}
for (let i = 0; i < server.runningScripts.length; ++i) {
const runningScriptObj = server.runningScripts[i];
runningScriptObj.logs.length = 0;
runningScriptObj.logs = [];
}
}
this.AllServersSave = JSON.stringify(TempAllServers);
this.AllServersSave = saveAllServers();
this.CompaniesSave = JSON.stringify(Companies);
this.FactionsSave = JSON.stringify(Factions);
this.SpecialServerIpsSave = JSON.stringify(SpecialServerIps);

@ -1,4 +1,4 @@
import { AllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
import { RunningScript } from "./RunningScript";
export function getRamUsageFromRunningScript(script: RunningScript): number {
@ -6,7 +6,7 @@ export function getRamUsageFromRunningScript(script: RunningScript): number {
return script.ramUsage; // Use cached value
}
const server = AllServers[script.server];
const server = getServer(script.server);
if (server == null) {
return 0;
}

@ -1,10 +1,9 @@
import { CONSTANTS } from "../Constants";
import { Player } from "../Player";
import { AllServers } from "../Server/AllServers";
import { BaseServer } from "../Server/BaseServer";
import { Server } from "../Server/Server";
import { RunningScript } from "../Script/RunningScript";
import { processSingleServerGrowth } from "../Server/ServerHelpers";
import { processSingleServerGrowth, getServer } from "../Server/ServerHelpers";
import { numeralWrapper } from "../ui/numeralFormat";
@ -32,7 +31,7 @@ export function scriptCalculateOfflineProduction(runningScript: RunningScript):
if (runningScript.dataMap[ip][2] == 0 || runningScript.dataMap[ip][2] == null) {
continue;
}
const serv = AllServers[ip];
const serv = getServer(ip);
if (serv == null) {
continue;
}
@ -40,7 +39,8 @@ export function scriptCalculateOfflineProduction(runningScript: RunningScript):
((0.5 * runningScript.dataMap[ip][2]) / runningScript.onlineRunningTime) * timePassed,
);
runningScript.log(`Called on ${serv.hostname} ${timesGrown} times while offline`);
const host = AllServers[runningScript.server];
const host = getServer(runningScript.server);
if (host === null) throw new Error("getServer of null key?");
if (!(serv instanceof Server)) throw new Error("trying to grow a non-normal server");
const growth = processSingleServerGrowth(serv, timesGrown, Player, host.cpuCores);
runningScript.log(
@ -64,13 +64,14 @@ export function scriptCalculateOfflineProduction(runningScript: RunningScript):
if (runningScript.dataMap[ip][3] == 0 || runningScript.dataMap[ip][3] == null) {
continue;
}
const serv = AllServers[ip];
const serv = getServer(ip);
if (serv == null) {
continue;
}
if (!(serv instanceof Server)) throw new Error("trying to weaken a non-normal server");
const host = AllServers[runningScript.server];
const host = getServer(runningScript.server);
if (host === null) throw new Error("getServer of null key?");
const timesWeakened = Math.round(
((0.5 * runningScript.dataMap[ip][3]) / runningScript.onlineRunningTime) * timePassed,
);

@ -1,4 +1,5 @@
import { Server } from "./Server";
import { BaseServer } from "./BaseServer";
import { SpecialServerIps } from "./SpecialServerIps";
import { serverMetadata } from "./data/servers";
@ -14,7 +15,28 @@ import { Reviver } from "../utils/JSONReviver";
* Key (string) = IP
* Value = Server object
*/
export let AllServers: IMap<Server | HacknetServer> = {};
let AllServers: IMap<Server | HacknetServer> = {};
export function GetServerByIP(ip: string): Server | HacknetServer | undefined {
return AllServers[ip];
}
export function GetAllServers(): BaseServer[] {
const servers: BaseServer[] = [];
for (const key in AllServers) {
servers.push(AllServers[key]);
}
return servers;
}
export function DeleteServer(serverkey: string): void {
for (const key in AllServers) {
const server = AllServers[key];
if (server.ip !== serverkey && server.hostname !== serverkey) continue;
delete AllServers[key];
break;
}
}
export function ipExists(ip: string): boolean {
return AllServers[ip] != null;
@ -148,5 +170,18 @@ export function prestigeAllServers(): void {
export function loadAllServers(saveString: string): void {
AllServers = JSON.parse(saveString, Reviver);
console.log(AllServers);
}
export function saveAllServers(): string {
const TempAllServers = JSON.parse(JSON.stringify(AllServers), Reviver);
for (const key in TempAllServers) {
const server = TempAllServers[key];
for (let i = 0; i < server.runningScripts.length; ++i) {
const runningScriptObj = server.runningScripts[i];
runningScriptObj.logs.length = 0;
runningScriptObj.logs = [];
}
}
return JSON.stringify(TempAllServers);
}

@ -1,4 +1,4 @@
import { AllServers, createUniqueRandomIp, ipExists } from "./AllServers";
import { GetAllServers, GetServerByIP, createUniqueRandomIp, ipExists } from "./AllServers";
import { Server, IConstructorParams } from "./Server";
import { BaseServer } from "./BaseServer";
import { calculateServerGrowth } from "./formulas/grow";
@ -121,12 +121,10 @@ export function prestigeHomeComputer(homeComp: Server): void {
//Returns server object with corresponding hostname
// Relatively slow, would rather not use this a lot
export function GetServerByHostname(hostname: string): Server | HacknetServer | null {
for (const ip in AllServers) {
if (AllServers.hasOwnProperty(ip)) {
if (AllServers[ip].hostname == hostname) {
return AllServers[ip];
}
export function GetServerByHostname(hostname: string): BaseServer | null {
for (const server of GetAllServers()) {
if (server.hostname == hostname) {
return server;
}
}
@ -134,12 +132,13 @@ export function GetServerByHostname(hostname: string): Server | HacknetServer |
}
//Get server by IP or hostname. Returns null if invalid
export function getServer(s: string): Server | HacknetServer | null {
export function getServer(s: string): BaseServer | null {
if (!isValidIPAddress(s)) {
return GetServerByHostname(s);
}
if (AllServers[s] !== undefined) {
return AllServers[s];
const server = GetServerByIP(s);
if (server !== undefined) {
return server;
}
return null;
@ -148,17 +147,17 @@ export function getServer(s: string): Server | HacknetServer | null {
// Returns the i-th server on the specified server's network
// A Server's serverOnNetwork property holds only the IPs. This function returns
// the actual Server object
export function getServerOnNetwork(server: BaseServer, i: number): Server | HacknetServer | null {
export function getServerOnNetwork(server: BaseServer, i: number): BaseServer | null {
if (i > server.serversOnNetwork.length) {
console.error("Tried to get server on network that was out of range");
return null;
}
return AllServers[server.serversOnNetwork[i]];
return getServer(server.serversOnNetwork[i]);
}
export function isBackdoorInstalled(server: Server | HacknetServer): boolean {
if ("backdoorInstalled" in server) {
export function isBackdoorInstalled(server: BaseServer): boolean {
if (server instanceof Server) {
return server.backdoorInstalled;
}
return false;

@ -12,7 +12,7 @@ import { TextFile } from "../TextFile";
import { Script } from "../Script/Script";
import { isScriptFilename } from "../Script/isScriptFilename";
import { CONSTANTS } from "../Constants";
import { AllServers } from "../Server/AllServers";
import { GetAllServers } from "../Server/AllServers";
import { removeLeadingSlash, isInRootDirectory, evaluateFilePath } from "./DirectoryHelpers";
import { checkIfConnectedToDarkweb } from "../DarkWeb/DarkWeb";
@ -116,6 +116,7 @@ export class Terminal implements ITerminal {
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");
}
@ -125,6 +126,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
this.startAction(calculateGrowTime(server, player) / 16, "g");
}
startWeaken(player: IPlayer): void {
@ -133,6 +135,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
this.startAction(calculateWeakenTime(server, player) / 16, "w");
}
@ -143,6 +146,7 @@ export class Terminal implements ITerminal {
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");
}
@ -163,6 +167,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
// Calculate whether hack was successful
const hackChance = calculateHackingChance(server, player);
@ -218,6 +223,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
const expGain = calculateHackingExpGain(server, player);
const growth = processSingleServerGrowth(server, 1, player, server.cpuCores) - 1;
this.print(
@ -235,6 +241,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
const expGain = calculateHackingExpGain(server, player);
server.weaken(CONSTANTS.ServerWeakenAmount);
this.print(
@ -251,6 +258,7 @@ export class Terminal implements ITerminal {
this.error("Cannot hack this kind of server");
return;
}
if (!(server instanceof Server)) throw new Error("server should be normal server");
if (
SpecialServerIps[SpecialServerNames.WorldDaemon] &&
SpecialServerIps[SpecialServerNames.WorldDaemon] == server.ip
@ -287,7 +295,7 @@ export class Terminal implements ITerminal {
}
this.print(
`Total money available on server: ${
!(currServ instanceof HacknetServer) ? numeralWrapper.formatMoney(currServ.moneyAvailable) : "N/A"
currServ instanceof Server ? numeralWrapper.formatMoney(currServ.moneyAvailable) : "N/A"
}`,
);
if (currServ instanceof Server) {
@ -449,8 +457,8 @@ export class Terminal implements ITerminal {
const visited: {
[key: string]: number | undefined;
} = {};
for (const ip in AllServers) {
visited[ip] = 0;
for (const server of GetAllServers()) {
visited[server.hostname] = 0;
}
const stack: BaseServer[] = [];
@ -465,12 +473,12 @@ export class Terminal implements ITerminal {
const isHacknet = s instanceof HacknetServer;
if (!all && (s as any).purchasedByPlayer && s.hostname != "home") {
continue; // Purchased server
} else if (visited[s.ip] || d > depth) {
} else if (visited[s.hostname] || d > depth) {
continue; // Already visited or out-of-depth
} else if (!all && isHacknet) {
continue; // Hacknet Server
} else {
visited[s.ip] = 1;
visited[s.hostname] = 1;
}
for (let i = s.serversOnNetwork.length - 1; i >= 0; --i) {
const newS = getServerOnNetwork(s, i);

@ -5,7 +5,8 @@ import { Aliases, GlobalAliases } from "../Alias";
import { DarkWebItems } from "../DarkWeb/DarkWebItems";
import { Message } from "../Message/Message";
import { IPlayer } from "../PersonObjects/IPlayer";
import { AllServers } from "../Server/AllServers";
import { GetAllServers } from "../Server/AllServers";
import { getServer } from "../Server/ServerHelpers";
// An array of all Terminal commands
const commands = [
@ -223,9 +224,9 @@ export function determineAllPossibilitiesForTabCompletion(
}
if (isCommand("scp") && index === 1) {
for (const iphostname in AllServers) {
allPos.push(AllServers[iphostname].ip);
allPos.push(AllServers[iphostname].hostname);
for (const server of GetAllServers()) {
allPos.push(server.ip);
allPos.push(server.hostname);
}
return allPos;
@ -243,7 +244,7 @@ export function determineAllPossibilitiesForTabCompletion(
if (isCommand("connect")) {
// All network connections
for (let i = 0; i < currServ.serversOnNetwork.length; ++i) {
const serv = AllServers[currServ.serversOnNetwork[i]];
const serv = getServer(currServ.serversOnNetwork[i]);
if (serv == null) {
continue;
}

@ -16,7 +16,7 @@ import { ITutorialEvents } from "./InteractiveTutorial/ITutorialEvents";
import { Faction } from "../Faction/Faction";
import { prestigeAugmentation } from "../Prestige";
import { dialogBoxCreate } from "./React/DialogBox";
import { AllServers } from "../Server/AllServers";
import { GetAllServers } from "../Server/AllServers";
import { Factions } from "../Faction/Factions";
import { buyStock, sellStock, shortStock, sellShort } from "../StockMarket/BuyingAndSelling";
import {
@ -356,8 +356,8 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
save={() => saveObject.saveGame()}
export={() => saveObject.exportGame()}
forceKill={() => {
for (const hostname of Object.keys(AllServers)) {
AllServers[hostname].runningScripts = [];
for (const server of GetAllServers()) {
server.runningScripts = [];
}
dialogBoxCreate("Forcefully deleted all running scripts. Please save and refresh page.");
}}

@ -8,7 +8,6 @@ import Button from "@mui/material/Button";
import Paper from "@mui/material/Paper";
import Draggable from "react-draggable";
import { ResizableBox } from "react-resizable";
import { Theme } from "@mui/material";
import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles";
import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos";

@ -4,8 +4,9 @@
* Configurable to only contain certain types of servers
*/
import React from "react";
import { AllServers } from "../../Server/AllServers";
import { GetAllServers } from "../../Server/AllServers";
import { Server } from "../../Server/Server";
import { BaseServer } from "../../Server/BaseServer";
import { HacknetServer } from "../../Hacknet/HacknetServer";
import Select, { SelectChangeEvent } from "@mui/material/Select";
@ -30,7 +31,7 @@ export function ServerDropdown(props: IProps): React.ReactElement {
* Checks if the server should be shown in the dropdown menu, based on the
* 'serverType' property
*/
function isValidServer(s: Server | HacknetServer): boolean {
function isValidServer(s: BaseServer): boolean {
const purchased = s instanceof Server && s.purchasedByPlayer;
const type = props.serverType;
switch (type) {
@ -49,8 +50,7 @@ export function ServerDropdown(props: IProps): React.ReactElement {
}
const servers = [];
for (const serverName in AllServers) {
const server = AllServers[serverName];
for (const server of GetAllServers()) {
if (isValidServer(server)) {
servers.push(
<MenuItem key={server.hostname} value={server.hostname}>