44 lines
1.6 KiB
TypeScript
44 lines
1.6 KiB
TypeScript
import { COMMODITIES, portBuys, type Pattern } from './commodities';
|
|
|
|
export interface PortState {
|
|
sector: number;
|
|
name: string;
|
|
pattern: Pattern;
|
|
/** For a commodity the port sells: units on hand. For one it buys: units of demand left.
|
|
* Fractional (double precision) so lazy regeneration isn't rounded away; floor for trading. */
|
|
stock: number[];
|
|
cap: number[];
|
|
lastUpdate: Date;
|
|
}
|
|
|
|
/** Lazily regenerates stock toward capacity based on elapsed time. Mutates and returns the port. */
|
|
export function regenPort(port: PortState, now: Date, perHour: number): PortState {
|
|
const hours = Math.max(0, (now.getTime() - port.lastUpdate.getTime()) / 3_600_000);
|
|
if (hours > 0) {
|
|
for (let i = 0; i < port.stock.length; i++) {
|
|
port.stock[i] = Math.min(port.cap[i], port.stock[i] + port.cap[i] * perHour * hours);
|
|
}
|
|
port.lastUpdate = now;
|
|
}
|
|
return port;
|
|
}
|
|
|
|
export function ratio(port: PortState, c: number): number {
|
|
return port.cap[c] > 0 ? Math.max(0, Math.min(1, port.stock[c] / port.cap[c])) : 0;
|
|
}
|
|
|
|
/**
|
|
* Per-unit price the port quotes before haggling.
|
|
* Selling ports are cheap when well stocked (0.70x..1.15x base);
|
|
* buying ports pay more when demand is high (1.00x..1.50x base).
|
|
*/
|
|
export function unitPrice(port: PortState, c: number): number {
|
|
const base = COMMODITIES[c].base;
|
|
const r = ratio(port, c);
|
|
return portBuys(port.pattern, c) ? base * (1.0 + 0.5 * r) : base * (1.15 - 0.45 * r);
|
|
}
|
|
|
|
export function quoteTotal(port: PortState, c: number, qty: number): number {
|
|
return Math.max(1, Math.round(unitPrice(port, c) * qty));
|
|
}
|