bitburner-scripts/src/ezgame/server/buy-max.ts
2026-05-04 00:39:11 +08:00

69 lines
2.2 KiB
TypeScript

import { NS } from "@ns";
export const buyMax = (ns: NS, serverNamePrefix: string) => {
// get the maximum number of servers that can be purchased
const maxServers = ns.cloud.getServerLimit();
// get the number of servers currently owned
const currentServers = ns.cloud.getServerNames().length;
// calculate the number of servers that can still be purchased
const serversToPurchase = maxServers - currentServers;
// if we can't buy any more servers, return
if (serversToPurchase <= 0) {
ns.tprint("Cannot purchase any more servers. Maximum limit reached.");
return;
}
// get current money available
const moneyAvailable = ns.getServerMoneyAvailable("home");
// find the maximum ram we can afford spread out over the number of servers we can buy
// the ram amount that can be bought is in power of 2
// we start with 2^1, then increase the power
// once we hit the max, we return the -1 power that was working before
let targetRam = 0;
// do until 2^67
for (let pow = 1; pow <= 67; pow++) {
// calculate the ram based on power
const ram = Math.pow(2, pow);
// get the cost of the server with the ram
const totalCost = ns.cloud.getServerCost(ram) * serversToPurchase;
// check if can buy
if (totalCost <= moneyAvailable) {
// if can then update the target to the new one
targetRam = ram;
} else {
// if not then break, it will return the previous ram amount
break;
}
}
// check if we found a valid target ram amount
if (targetRam < 2) {
ns.tprint("Unable to find affordable server configuration. Try buying fewer servers.");
return;
}
// now buy the servers with the target ram
let serversPurchased = 0;
while (serversPurchased < serversToPurchase) {
const serverName = `${serverNamePrefix}-${currentServers + serversPurchased + 1}`;
if (!ns.serverExists(serverName)) {
ns.cloud.purchaseServer(serverName, targetRam);
serversPurchased++;
}
}
ns.tprint(`Servers purchased: ${serversPurchased}`);
ns.tprint(`RAM: ${targetRam} GB RAM each`);
};
export const main = (ns: NS) => {
const serverNamePrefix = "worker";
buyMax(ns, serverNamePrefix);
};