tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

203 lignes · 6399 octetsBrut · Historique
1/**
2 * Trade helper: estimates what a cargo run between two known markets would earn.
3 *
4 * PRICE MODEL (flagged for team review). Per the docs, a good's price is
5 * "its base price times its baseline over its supply, within a clamp", with a spread
6 * either side, and "every unit you trade moves the supply". So with the listed price
7 * p₀ at supply s₀, the i-th unit (0-based) is estimated at:
8 * buying (supply falls): p₀ · s₀ / (s₀ − i)
9 * selling (supply rises): p₀ · s₀ / (s₀ + i)
10 * We ignore the clamp (we don't know it), assume the spread is proportional, and assume
11 * prices don't drift back during the trip. Snapshots age; routes from old snapshots
12 * are marked `stale`.
13 *
14 * Travel and fuel come from `navigation.ts`/`rules.ts` (estimates too).
15 */
16import type { MarketGood } from '../types';
17import { planTrip, type GalaxyGraph, type TripPlan } from './navigation';
18
19export interface MarketSnapshot {
20 station: string;
21 system: string;
22 goods: MarketGood[];
23 /** ISO time the snapshot was read. */
24 at: string;
25}
26
27/** Price of the i-th unit bought (0-based); Infinity once supply would run out. */
28export function unitBuyPrice(g: MarketGood, i: number): number {
29 const left = g.supply - i;
30 return left <= 0 ? Infinity : (g.buy * g.supply) / left;
31}
32
33/** Price of the i-th unit sold (0-based). */
34export function unitSellPrice(g: MarketGood, i: number): number {
35 return (g.sell * g.supply) / (g.supply + i);
36}
37
38export function buyCost(g: MarketGood, units: number): number {
39 let total = 0;
40 for (let i = 0; i < units; i++) total += unitBuyPrice(g, i);
41 return total;
42}
43
44export function sellRevenue(g: MarketGood, units: number): number {
45 let total = 0;
46 for (let i = 0; i < units; i++) total += unitSellPrice(g, i);
47 return total;
48}
49
50/** Most units worth carrying from `buy` to `sell`: stop when a unit stops paying, space or credits run out. */
51export function bestLot(
52 buy: MarketGood,
53 sell: MarketGood,
54 maxUnits: number,
55 credits: number
56): { units: number; cost: number; revenue: number } {
57 let units = 0;
58 let cost = 0;
59 let revenue = 0;
60 while (units < maxUnits) {
61 const b = unitBuyPrice(buy, units);
62 const s = unitSellPrice(sell, units);
63 if (s <= b || cost + b > credits) break;
64 cost += b;
65 revenue += s;
66 units++;
67 }
68 return { units, cost, revenue };
69}
70
71export interface ShipForTrade {
72 /** Where the ship is, or will be when its current trip ends. */
73 waypoint: string;
74 speed: number;
75 cargoCapacity: number;
76 fuel: number;
77 fuelCapacity: number;
78 /** Seconds until the ship can act (remaining trip), 0 if idle. */
79 busySeconds?: number;
80}
81
82export interface TradeRoute {
83 good: string;
84 from: string;
85 to: string;
86 units: number;
87 cost: number;
88 revenue: number;
89 /** Fuel for the loaded leg, at the buy station's fuel price. */
90 fuelCost: number;
91 profit: number;
92 /** Ship → buy station → sell station. */
93 seconds: number;
94 profitPerMinute: number;
95 toBuy: TripPlan;
96 loaded: TripPlan;
97 /** Fuel enough to reach the buy station now, and a full tank covers the loaded leg. */
98 fuelOk: boolean;
99 stale: boolean;
100}
101
102export interface RankOptions {
103 snapshots: readonly MarketSnapshot[];
104 graph: GalaxyGraph;
105 ship: ShipForTrade;
106 credits: number;
107 now: number;
108 /** Snapshots older than this mark their routes stale. Default 10 minutes. */
109 staleAfterMs?: number;
110 limit?: number;
111}
112
113const FUEL = 'fuel';
114
115/** Best cargo runs for a ship, by profit per minute. Only profitable, plannable routes. */
116export function rankRoutes({
117 snapshots,
118 graph,
119 ship,
120 credits,
121 now,
122 staleAfterMs = 10 * 60_000,
123 limit = 5
124}: RankOptions): TradeRoute[] {
125 const routes: TradeRoute[] = [];
126 const plans = new Map<string, TripPlan | null>();
127 const plan = (a: string, b: string) => {
128 const key = `${a}>${b}`;
129 if (!plans.has(key)) plans.set(key, planTrip(graph, a, b, ship.speed));
130 return plans.get(key)!;
131 };
132
133 for (const from of snapshots) {
134 const toBuy = plan(ship.waypoint, from.station);
135 if (!toBuy) continue;
136 const fuelPrice = from.goods.find((g) => g.good === FUEL)?.buy ?? 0;
137 for (const buy of from.goods) {
138 for (const to of snapshots) {
139 if (to.station === from.station) continue;
140 const sell = to.goods.find((g) => g.good === buy.good);
141 if (!sell || sell.sell <= buy.buy) continue;
142 const loaded = plan(from.station, to.station);
143 if (!loaded) continue;
144 const lot = bestLot(buy, sell, ship.cargoCapacity, credits);
145 if (lot.units === 0) continue;
146 const fuelCost = loaded.fuel * fuelPrice;
147 const profit = lot.revenue - lot.cost - fuelCost;
148 if (profit <= 0) continue;
149 const seconds = (ship.busySeconds ?? 0) + toBuy.seconds + loaded.seconds;
150 const age = now - Math.min(Date.parse(from.at), Date.parse(to.at));
151 routes.push({
152 good: buy.good,
153 from: from.station,
154 to: to.station,
155 units: lot.units,
156 cost: Math.round(lot.cost),
157 revenue: Math.round(lot.revenue),
158 fuelCost: Math.round(fuelCost),
159 profit: Math.round(profit),
160 seconds,
161 profitPerMinute: profit / Math.max(seconds / 60, 1 / 60),
162 toBuy,
163 loaded,
164 fuelOk: toBuy.fuel <= ship.fuel && loaded.fuel <= ship.fuelCapacity,
165 stale: age > staleAfterMs
166 });
167 }
168 }
169 }
170 routes.sort((a, b) => Number(b.fuelOk) - Number(a.fuelOk) || b.profitPerMinute - a.profitPerMinute);
171 return routes.slice(0, limit);
172}
173
174/** Where a good sells best among known markets, other than `except`. */
175export function bestSellFor(
176 good: string,
177 snapshots: readonly MarketSnapshot[],
178 except?: string
179): { station: string; price: number } | null {
180 let best: { station: string; price: number } | null = null;
181 for (const s of snapshots) {
182 if (s.station === except) continue;
183 const g = s.goods.find((x) => x.good === good);
184 if (g && (!best || g.sell > best.price)) best = { station: s.station, price: g.sell };
185 }
186 return best;
187}
188
189/** Cheapest known place to buy `units` of a good, with the estimated total. */
190export function cheapestSource(
191 good: string,
192 units: number,
193 snapshots: readonly MarketSnapshot[]
194): { station: string; cost: number } | null {
195 let best: { station: string; cost: number } | null = null;
196 for (const s of snapshots) {
197 const g = s.goods.find((x) => x.good === good);
198 if (!g || g.supply <= units) continue;
199 const cost = Math.round(buyCost(g, units));
200 if (!best || cost < best.cost) best = { station: s.station, cost };
201 }
202 return best;
203}