MISC: move server constants into their own constant (#1075)

This commit is contained in:
Caldwell 2024-02-10 10:13:42 +01:00 committed by GitHub
parent fd5b0f8241
commit 4d551915b3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 56 additions and 48 deletions

@ -30,6 +30,7 @@ import { currentNodeMults } from "../BitNode/BitNodeMultipliers";
import { workerScripts } from "../Netscript/WorkerScripts"; import { workerScripts } from "../Netscript/WorkerScripts";
import { getRecordValues } from "../Types/Record"; import { getRecordValues } from "../Types/Record";
import { ServerConstants } from "../Server/data/Constants";
// Unable to correctly cast the JSON data into AchievementDataJson type otherwise... // Unable to correctly cast the JSON data into AchievementDataJson type otherwise...
const achievementData = (<AchievementDataJson>(<unknown>data)).achievements; const achievementData = (<AchievementDataJson>(<unknown>data)).achievements;
@ -232,7 +233,7 @@ export const achievements: Record<string, Achievement> = {
MAX_RAM: { MAX_RAM: {
...achievementData.MAX_RAM, ...achievementData.MAX_RAM,
Icon: "maxram", Icon: "maxram",
Condition: () => Player.getHomeComputer().maxRam === CONSTANTS.HomeComputerMaxRam, Condition: () => Player.getHomeComputer().maxRam === ServerConstants.HomeComputerMaxRam,
}, },
MAX_CORES: { MAX_CORES: {
...achievementData.MAX_CORES, ...achievementData.MAX_CORES,

@ -12,8 +12,6 @@ export const CONSTANTS: {
OfflineHackingIncome: number; OfflineHackingIncome: number;
CorpFactionRepRequirement: number; CorpFactionRepRequirement: number;
BaseFocusBonus: number; BaseFocusBonus: number;
BaseCostFor1GBOfRamHome: number;
BaseCostFor1GBOfRamServer: number;
TravelCost: number; TravelCost: number;
BaseFavorToDonate: number; BaseFavorToDonate: number;
DonateMoneyToRepDivisor: number; DonateMoneyToRepDivisor: number;
@ -23,13 +21,6 @@ export const CONSTANTS: {
CompanyReputationToFavorMult: number; CompanyReputationToFavorMult: number;
NeuroFluxGovernorLevelMult: number; NeuroFluxGovernorLevelMult: number;
NumNetscriptPorts: number; NumNetscriptPorts: number;
HomeComputerMaxRam: number;
ServerBaseGrowthIncr: number;
ServerMaxGrowthLog: number;
ServerFortifyAmount: number;
ServerWeakenAmount: number;
PurchasedServerLimit: number;
PurchasedServerMaxRam: number;
MultipleAugMultiplier: number; MultipleAugMultiplier: number;
TorRouterCost: number; TorRouterCost: number;
HospitalCostPerHp: number; HospitalCostPerHp: number;
@ -103,10 +94,6 @@ export const CONSTANTS: {
// How much reputation is needed to join a megacorporation's faction // How much reputation is needed to join a megacorporation's faction
CorpFactionRepRequirement: 400e3, CorpFactionRepRequirement: 400e3,
// Base RAM costs
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM
// Cost to travel to another city // Cost to travel to another city
TravelCost: 200e3, TravelCost: 200e3,
@ -123,16 +110,6 @@ export const CONSTANTS: {
NumNetscriptPorts: Number.MAX_SAFE_INTEGER, NumNetscriptPorts: Number.MAX_SAFE_INTEGER,
// Server-related constants
HomeComputerMaxRam: 1073741824, // 2 ^ 30
ServerBaseGrowthIncr: 0.03, // Unadjusted growth increment (growth rate is this * adjustment + 1)
ServerMaxGrowthLog: 0.00349388925425578, // Maximum possible growth rate accounting for server security, precomputed as log1p(.0035)
ServerFortifyAmount: 0.002, // Amount by which server's security increases when its hacked/grown
ServerWeakenAmount: 0.05, // Amount by which server's security decreases when weakened
PurchasedServerLimit: 25,
PurchasedServerMaxRam: 1048576, // 2^20
// Augmentation Constants // Augmentation Constants
MultipleAugMultiplier: 1.9, MultipleAugMultiplier: 1.9,

@ -3,7 +3,6 @@ import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import { CONSTANTS } from "../../Constants";
import { Player } from "@player"; import { Player } from "@player";
import { purchaseRamForHomeComputer } from "../../Server/ServerPurchases"; import { purchaseRamForHomeComputer } from "../../Server/ServerPurchases";
@ -12,6 +11,7 @@ import { formatRam } from "../../ui/formatNumber";
import { MathJax } from "better-react-mathjax"; import { MathJax } from "better-react-mathjax";
import { currentNodeMults } from "../../BitNode/BitNodeMultipliers"; import { currentNodeMults } from "../../BitNode/BitNodeMultipliers";
import { ServerConstants } from "../../Server/data/Constants";
interface IProps { interface IProps {
rerender: () => void; rerender: () => void;
@ -19,7 +19,7 @@ interface IProps {
export function RamButton(props: IProps): React.ReactElement { export function RamButton(props: IProps): React.ReactElement {
const homeComputer = Player.getHomeComputer(); const homeComputer = Player.getHomeComputer();
if (homeComputer.maxRam >= CONSTANTS.HomeComputerMaxRam) { if (homeComputer.maxRam >= ServerConstants.HomeComputerMaxRam) {
return <Button>Upgrade 'home' RAM - MAX</Button>; return <Button>Upgrade 'home' RAM - MAX</Button>;
} }

@ -38,6 +38,7 @@ import { Engine } from "../engine";
import { resolveFilePath, FilePath } from "../Paths/FilePath"; import { resolveFilePath, FilePath } from "../Paths/FilePath";
import { hasScriptExtension, ScriptFilePath } from "../Paths/ScriptFilePath"; import { hasScriptExtension, ScriptFilePath } from "../Paths/ScriptFilePath";
import { CustomBoundary } from "../ui/Components/CustomBoundary"; import { CustomBoundary } from "../ui/Components/CustomBoundary";
import { ServerConstants } from "../Server/data/Constants";
export const helpers = { export const helpers = {
string, string,
@ -540,7 +541,7 @@ function hack(ctx: NetscriptContext, hostname: string, manual: boolean, opts: un
expGainedOnSuccess, expGainedOnSuccess,
)} exp (t=${formatThreads(threads)})`, )} exp (t=${formatThreads(threads)})`,
); );
server.fortify(CONSTANTS.ServerFortifyAmount * Math.min(threads, maxThreadNeeded)); server.fortify(ServerConstants.ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
if (stock) { if (stock) {
influenceStockThroughServerHack(server, moneyDrained); influenceStockThroughServerHack(server, moneyDrained);
} }

@ -106,6 +106,7 @@ import { hasContractExtension } from "./Paths/ContractFilePath";
import { getRamCost } from "./Netscript/RamCostGenerator"; import { getRamCost } from "./Netscript/RamCostGenerator";
import { getEnumHelper } from "./utils/EnumHelper"; import { getEnumHelper } from "./utils/EnumHelper";
import { setDeprecatedProperties, deprecationWarning } from "./utils/DeprecationHelper"; import { setDeprecatedProperties, deprecationWarning } from "./utils/DeprecationHelper";
import { ServerConstants } from "./Server/data/Constants";
export const enums: NSEnums = { export const enums: NSEnums = {
CityName, CityName,
@ -220,7 +221,7 @@ export const ns: InternalAPI<NSFull> = {
} }
} }
return CONSTANTS.ServerFortifyAmount * threads; return ServerConstants.ServerFortifyAmount * threads;
}, },
hackAnalyzeChance: (ctx) => (_hostname) => { hackAnalyzeChance: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname); const hostname = helpers.string(ctx, "hostname", _hostname);
@ -346,7 +347,7 @@ export const ns: InternalAPI<NSFull> = {
threads = Math.min(threads, maxThreadsNeeded); threads = Math.min(threads, maxThreadsNeeded);
} }
return 2 * CONSTANTS.ServerFortifyAmount * threads; return 2 * ServerConstants.ServerFortifyAmount * threads;
}, },
weaken: (ctx) => async (_hostname, opts?) => { weaken: (ctx) => async (_hostname, opts?) => {
const hostname = helpers.string(ctx, "hostname", _hostname); const hostname = helpers.string(ctx, "hostname", _hostname);
@ -381,7 +382,7 @@ export const ns: InternalAPI<NSFull> = {
} }
const cores = host.cpuCores; const cores = host.cpuCores;
const coreBonus = getCoreBonus(cores); const coreBonus = getCoreBonus(cores);
const weakenAmt = CONSTANTS.ServerWeakenAmount * threads * coreBonus; const weakenAmt = ServerConstants.ServerWeakenAmount * threads * coreBonus;
server.weaken(weakenAmt); server.weaken(weakenAmt);
ctx.workerScript.scriptRef.recordWeaken(server.hostname, threads); ctx.workerScript.scriptRef.recordWeaken(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads; const expGain = calculateHackingExpGain(server, Player) * threads;
@ -404,7 +405,7 @@ export const ns: InternalAPI<NSFull> = {
const threads = helpers.number(ctx, "threads", _threads); const threads = helpers.number(ctx, "threads", _threads);
const cores = helpers.number(ctx, "cores", _cores); const cores = helpers.number(ctx, "cores", _cores);
const coreBonus = getCoreBonus(cores); const coreBonus = getCoreBonus(cores);
return CONSTANTS.ServerWeakenAmount * threads * coreBonus * currentNodeMults.ServerWeakenRate; return ServerConstants.ServerWeakenAmount * threads * coreBonus * currentNodeMults.ServerWeakenRate;
}, },
share: (ctx) => () => { share: (ctx) => () => {
const cores = helpers.getServer(ctx, ctx.workerScript.hostname).cpuCores; const cores = helpers.getServer(ctx, ctx.workerScript.hostname).cpuCores;

@ -56,6 +56,7 @@ import { ScriptFilePath, resolveScriptFilePath } from "../Paths/ScriptFilePath";
import { root } from "../Paths/Directory"; import { root } from "../Paths/Directory";
import { getRecordEntries } from "../Types/Record"; import { getRecordEntries } from "../Types/Record";
import { JobTracks } from "../Company/data/JobTracks"; import { JobTracks } from "../Company/data/JobTracks";
import { ServerConstants } from "../Server/data/Constants";
export function NetscriptSingularity(): InternalAPI<ISingularity> { export function NetscriptSingularity(): InternalAPI<ISingularity> {
const runAfterReset = function (cbScript: ScriptFilePath) { const runAfterReset = function (cbScript: ScriptFilePath) {
@ -640,7 +641,7 @@ export function NetscriptSingularity(): InternalAPI<ISingularity> {
// Check if we're at max RAM // Check if we're at max RAM
const homeComputer = Player.getHomeComputer(); const homeComputer = Player.getHomeComputer();
if (homeComputer.maxRam >= CONSTANTS.HomeComputerMaxRam) { if (homeComputer.maxRam >= ServerConstants.HomeComputerMaxRam) {
helpers.log(ctx, () => `Your home computer is at max RAM.`); helpers.log(ctx, () => `Your home computer is at max RAM.`);
return false; return false;
} }

@ -1,5 +1,5 @@
// Server and HacknetServer-related methods for the Player class (PlayerObject) // Server and HacknetServer-related methods for the Player class (PlayerObject)
import { CONSTANTS } from "../../Constants"; import { ServerConstants } from "../../Server/data/Constants";
import { currentNodeMults } from "../../BitNode/BitNodeMultipliers"; import { currentNodeMults } from "../../BitNode/BitNodeMultipliers";
import { Server } from "../../Server/Server"; import { Server } from "../../Server/Server";
@ -35,7 +35,7 @@ export function getUpgradeHomeRamCost(this: PlayerObject): number {
//Calculate cost //Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded //Have cost increase by some percentage each time RAM has been upgraded
const mult = Math.pow(1.58, numUpgrades); const mult = Math.pow(1.58, numUpgrades);
const cost = currentRam * CONSTANTS.BaseCostFor1GBOfRamHome * mult * currentNodeMults.HomeComputerRamCost; const cost = currentRam * ServerConstants.BaseCostFor1GBOfRamHome * mult * currentNodeMults.HomeComputerRamCost;
return cost; return cost;
} }

@ -10,6 +10,7 @@ import { workerScripts } from "../Netscript/WorkerScripts";
import { scriptKey } from "../utils/helpers/scriptKey"; import { scriptKey } from "../utils/helpers/scriptKey";
import type { ScriptFilePath } from "../Paths/ScriptFilePath"; import type { ScriptFilePath } from "../Paths/ScriptFilePath";
import { ServerConstants } from "../Server/data/Constants";
export function scriptCalculateOfflineProduction(runningScript: RunningScript): void { export function scriptCalculateOfflineProduction(runningScript: RunningScript): void {
//The Player object stores the last update time from when we were online //The Player object stores the last update time from when we were online
@ -83,7 +84,7 @@ export function scriptCalculateOfflineProduction(runningScript: RunningScript):
); );
runningScript.log(`Called weaken() on ${serv.hostname} ${timesWeakened} times while offline`); runningScript.log(`Called weaken() on ${serv.hostname} ${timesWeakened} times while offline`);
const coreBonus = 1 + (host.cpuCores - 1) / 16; const coreBonus = 1 + (host.cpuCores - 1) / 16;
serv.weaken(CONSTANTS.ServerWeakenAmount * timesWeakened * coreBonus); serv.weaken(ServerConstants.ServerWeakenAmount * timesWeakened * coreBonus);
} }
} }
} }

@ -3,7 +3,7 @@ import { Server, IConstructorParams } from "./Server";
import { BaseServer } from "./BaseServer"; import { BaseServer } from "./BaseServer";
import { calculateServerGrowth, calculateServerGrowthLog } from "./formulas/grow"; import { calculateServerGrowth, calculateServerGrowthLog } from "./formulas/grow";
import { CONSTANTS } from "../Constants"; import { ServerConstants } from "./data/Constants";
import { Player } from "@player"; import { Player } from "@player";
import { CompletedProgramName, LiteratureName } from "@enums"; import { CompletedProgramName, LiteratureName } from "@enums";
import { Person as IPerson } from "@nsdefs"; import { Person as IPerson } from "@nsdefs";
@ -202,7 +202,7 @@ export function processSingleServerGrowth(server: Server, threads: number, cores
let usedCycles = numCycleForGrowthCorrected(server, server.moneyAvailable, oldMoneyAvailable, cores); let usedCycles = numCycleForGrowthCorrected(server, server.moneyAvailable, oldMoneyAvailable, cores);
// Growing increases server security twice as much as hacking // Growing increases server security twice as much as hacking
usedCycles = Math.min(Math.max(0, Math.ceil(usedCycles)), threads); usedCycles = Math.min(Math.max(0, Math.ceil(usedCycles)), threads);
server.fortify(2 * CONSTANTS.ServerFortifyAmount * usedCycles); server.fortify(2 * ServerConstants.ServerFortifyAmount * usedCycles);
} }
return server.moneyAvailable / oldMoneyAvailable; return server.moneyAvailable / oldMoneyAvailable;
} }

@ -6,7 +6,7 @@ import { AddToAllServers, createUniqueRandomIp, GetServer, renameServer } from "
import { safelyCreateUniqueServer } from "./ServerHelpers"; import { safelyCreateUniqueServer } from "./ServerHelpers";
import { currentNodeMults } from "../BitNode/BitNodeMultipliers"; import { currentNodeMults } from "../BitNode/BitNodeMultipliers";
import { CONSTANTS } from "../Constants"; import { ServerConstants } from "./data/Constants";
import { Player } from "@player"; import { Player } from "@player";
import { dialogBoxCreate } from "../ui/React/DialogBox"; import { dialogBoxCreate } from "../ui/React/DialogBox";
@ -20,6 +20,7 @@ import { workerScripts } from "../Netscript/WorkerScripts";
* @returns Cost of purchasing the given server. Returns infinity for invalid arguments * @returns Cost of purchasing the given server. Returns infinity for invalid arguments
*/ */
export function getPurchaseServerCost(ram: number): number { export function getPurchaseServerCost(ram: number): number {
// TODO shift checks into
const sanitizedRam = Math.round(ram); const sanitizedRam = Math.round(ram);
if (isNaN(sanitizedRam) || !isPowerOfTwo(sanitizedRam) || !(Math.sign(sanitizedRam) === 1)) { if (isNaN(sanitizedRam) || !isPowerOfTwo(sanitizedRam) || !(Math.sign(sanitizedRam) === 1)) {
return Infinity; return Infinity;
@ -33,7 +34,7 @@ export function getPurchaseServerCost(ram: number): number {
return ( return (
sanitizedRam * sanitizedRam *
CONSTANTS.BaseCostFor1GBOfRamServer * ServerConstants.BaseCostFor1GBOfRamServer *
currentNodeMults.PurchasedServerCost * currentNodeMults.PurchasedServerCost *
Math.pow(currentNodeMults.PurchasedServerSoftcap, upg) Math.pow(currentNodeMults.PurchasedServerSoftcap, upg)
); );
@ -86,11 +87,11 @@ export const renamePurchasedServer = (hostname: string, newName: string): void =
}; };
export function getPurchaseServerLimit(): number { export function getPurchaseServerLimit(): number {
return Math.round(CONSTANTS.PurchasedServerLimit * currentNodeMults.PurchasedServerLimit); return Math.round(ServerConstants.PurchasedServerLimit * currentNodeMults.PurchasedServerLimit);
} }
export function getPurchaseServerMaxRam(): number { export function getPurchaseServerMaxRam(): number {
const ram = Math.round(CONSTANTS.PurchasedServerMaxRam * currentNodeMults.PurchasedServerMaxRam); const ram = Math.round(ServerConstants.PurchasedServerMaxRam * currentNodeMults.PurchasedServerMaxRam);
// Round this to the nearest power of 2 // Round this to the nearest power of 2
return 1 << (31 - Math.clz32(ram)); return 1 << (31 - Math.clz32(ram));
@ -155,7 +156,7 @@ export function purchaseRamForHomeComputer(): void {
} }
const homeComputer = Player.getHomeComputer(); const homeComputer = Player.getHomeComputer();
if (homeComputer.maxRam >= CONSTANTS.HomeComputerMaxRam) { if (homeComputer.maxRam >= ServerConstants.HomeComputerMaxRam) {
dialogBoxCreate(`You cannot upgrade your home computer RAM because it is at its maximum possible value`); dialogBoxCreate(`You cannot upgrade your home computer RAM because it is at its maximum possible value`);
return; return;
} }

@ -0,0 +1,24 @@
export const ServerConstants: {
BaseCostFor1GBOfRamHome: number;
BaseCostFor1GBOfRamServer: number;
HomeComputerMaxRam: number;
ServerBaseGrowthIncr: number;
ServerMaxGrowthLog: number;
ServerFortifyAmount: number;
ServerWeakenAmount: number;
PurchasedServerLimit: number;
PurchasedServerMaxRam: number;
} = {
// Base RAM costs
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM
// Server-related constants
HomeComputerMaxRam: 1073741824, // 2 ^ 30
ServerBaseGrowthIncr: 0.03, // Unadjusted growth increment (growth rate is this * adjustment + 1)
ServerMaxGrowthLog: 0.00349388925425578, // Maximum possible growth rate accounting for server security, precomputed as log1p(.0035)
ServerFortifyAmount: 0.002, // Amount by which server's security increases when its hacked/grown
ServerWeakenAmount: 0.05, // Amount by which server's security decreases when weakened
PurchasedServerLimit: 25,
PurchasedServerMaxRam: 1048576, // 2^20
};

@ -1,6 +1,6 @@
import { CONSTANTS } from "../../Constants";
import { currentNodeMults } from "../../BitNode/BitNodeMultipliers"; import { currentNodeMults } from "../../BitNode/BitNodeMultipliers";
import { Person as IPerson, Server as IServer } from "@nsdefs"; import { Person as IPerson, Server as IServer } from "@nsdefs";
import { ServerConstants } from "../data/Constants";
// Returns the log of the growth rate. When passing 1 for threads, this gives a useful constant. // Returns the log of the growth rate. When passing 1 for threads, this gives a useful constant.
export function calculateServerGrowthLog(server: IServer, threads: number, p: IPerson, cores = 1): number { export function calculateServerGrowthLog(server: IServer, threads: number, p: IPerson, cores = 1): number {
@ -10,9 +10,9 @@ export function calculateServerGrowthLog(server: IServer, threads: number, p: IP
//Get adjusted growth log, which accounts for server security //Get adjusted growth log, which accounts for server security
//log1p computes log(1+p), it is far more accurate for small values. //log1p computes log(1+p), it is far more accurate for small values.
let adjGrowthLog = Math.log1p(CONSTANTS.ServerBaseGrowthIncr / hackDifficulty); let adjGrowthLog = Math.log1p(ServerConstants.ServerBaseGrowthIncr / hackDifficulty);
if (adjGrowthLog >= CONSTANTS.ServerMaxGrowthLog) { if (adjGrowthLog >= ServerConstants.ServerMaxGrowthLog) {
adjGrowthLog = CONSTANTS.ServerMaxGrowthLog; adjGrowthLog = ServerConstants.ServerMaxGrowthLog;
} }
//Calculate adjusted server growth rate based on parameters //Calculate adjusted server growth rate based on parameters

@ -81,6 +81,7 @@ import { Directory, resolveDirectory, root } from "../Paths/Directory";
import { FilePath, isFilePath, resolveFilePath } from "../Paths/FilePath"; import { FilePath, isFilePath, resolveFilePath } from "../Paths/FilePath";
import { hasTextExtension } from "../Paths/TextFilePath"; import { hasTextExtension } from "../Paths/TextFilePath";
import { ContractFilePath } from "../Paths/ContractFilePath"; import { ContractFilePath } from "../Paths/ContractFilePath";
import { ServerConstants } from "../Server/data/Constants";
export class Terminal { export class Terminal {
// Flags to determine whether the player is currently running a hack or an analyze // Flags to determine whether the player is currently running a hack or an analyze
@ -227,7 +228,7 @@ export class Terminal {
Player.gainIntelligenceExp(expGainedOnSuccess / CONSTANTS.IntelligenceTerminalHackBaseExpGain); Player.gainIntelligenceExp(expGainedOnSuccess / CONSTANTS.IntelligenceTerminalHackBaseExpGain);
const oldSec = server.hackDifficulty; const oldSec = server.hackDifficulty;
server.fortify(CONSTANTS.ServerFortifyAmount); server.fortify(ServerConstants.ServerFortifyAmount);
const newSec = server.hackDifficulty; const newSec = server.hackDifficulty;
this.print( this.print(
@ -279,7 +280,7 @@ export class Terminal {
if (!(server instanceof Server)) throw new Error("server should be normal server"); 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 oldSec = server.hackDifficulty;
server.weaken(CONSTANTS.ServerWeakenAmount); server.weaken(ServerConstants.ServerWeakenAmount);
const newSec = server.hackDifficulty; const newSec = server.hackDifficulty;
Player.gainHackingExp(expGain); Player.gainHackingExp(expGain);